Creating a web app using WinJS in Visual Studio

By Jan 24, 2017

Description:

Creating a web app using WinJS in Visual Studio

Preferencesoft

WinJS

The HTML/CSS language lack of predefined widgets. For example, the bar menu with image buttons, floating menus, listviews that contains text and icons...

To compensate for this deficiency, there are JavaScript libraries like WinJS that provide many widgets, necessary to increase user interaction on a website.

Creating a WinJS application

Open Visual Studio, create a New project select JavaScript and WinJS application (Windows Universal)

Give a name to the app: App1 for example and press OK.

Index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
       <meta charset="utf-8" />
       <title>App1</title>
       <link href="lib/winjs-4.0.1/css/ui-light.css" rel="stylesheet" />
       <script src="lib/winjs-4.0.1/js/base.js"></script>
       <script src="lib/winjs-4.0.1/js/ui.js"></script>
       <link href="css/default.css" rel="stylesheet" />
       <script src="js/main.js"></script>
</head>
<body class="win-type-body">
       <div>Content here.</div>
</body>
</html>

main.js

(function () {
             "use strict";
 
             var app = WinJS.Application;
             //var activation = Windows.ApplicationModel.Activation;
             var isFirstActivation = true;
 
             app.onactivated = function (args) {
               /*
                         if (args.detail.kind === activation.ActivationKind.voiceCommand) {
                                         // TODO: Handle relevant ActivationKinds. For example, if your app can be started by voice commands,
                       // this is a good place to decide whether to populate an input field or choose a different initial view.
                         }
                         else if (args.detail.kind === activation.ActivationKind.launch) {
                                         // A Launch activation happens when the user launches your app via the tile
                       // or invokes a toast notification by clicking or tapping on the body.
                                       if (args.detail.arguments) {
                                                     // TODO: If the app supports toasts, use this value from the toast payload to determine where in the app
                               // to take the user in response to them invoking a toast notification.
                                       }
                                       else if (args.detail.previousExecutionState === activation.ApplicationExecutionState.terminated) {
                                                     // TODO: This application had been suspended and was then terminated to reclaim memory.
                               // To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
                               // Note: You may want to record the time when the app was last suspended and only restore state if they've returned after a short period.
                                       }
                         }
               */
 
                         if (!args.detail.prelaunchActivated) {
                                // TODO: If prelaunchActivated were true, it would mean the app was prelaunched in the background as an optimization.
                                // In that case it would be suspended shortly thereafter.
                                // Any long-running operations (like expensive network or disk I/O) or changes to user state which occur at launch
                                // should be done here (to avoid doing them in the prelaunch case).
                                // Alternatively, this work can be done in a resume or visibilitychanged handler.
                         }
 
                         if (isFirstActivation) {
                                // TODO: The app was activated and had not been running. Do general startup initialization here.
                                       document.addEventListener("visibilitychange", onVisibilityChanged);
                                       args.setPromise(WinJS.UI.processAll());
 
                         }
 
                         isFirstActivation = false;
             };
 
             function onVisibilityChanged(args) {
                         if (!document.hidden) {
                                       // TODO: The app just became visible. This may be a good time to refresh the view.
                         }
             }
 
             app.oncheckpoint = function (args) {
                    // TODO: This application is about to be suspended. Save any state
                    // that needs to persist across suspensions here. You might use the
                    // WinJS.Application.sessionState object, which is automatically
                    // saved and restored across suspension. If you need to complete an
                    // asynchronous operation before your application is suspended, call
                    // args.setPromise().
 
             };
 
             app.start();
 
})();

 

We commented out all lines of code using the variable activation to have no error when running in a browser.

Now look for the following instruction in the main.js file:

args.setPromise(WinJS.UI.processAll());

The code associated with the WinJS objects will be placed just after.

But we don't always access a web site by the first page, so let's delete the application declaration in this homepage.

main.js

(function () {
       "use strict";
 
 
})();

 

To create a WinJS control, we need to declare it in a <div> block in the HTML code and optionally initialize the event handler in the JavaScript file that is associated with the HTML file.

Usually in the <div> tag are added two custom attributes: data-win-control and data-win-options.

  • Ø  The first attribute, data-win-control is required and specifies the constructor of the control.

  • Ø  The second, data-win-options takes a JavaScript object containing key-value pairs separated by commas: { <key1>: <value1>, <key2>: <value2>, ... }.

You can find many examples at these addresses: http://try.buildwinjs.com/  and http://winjs.azurewebsites.net/ 
We are going to try a few in a Web page.

ToolBar

 

Index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <title>App1</title>
    <link href="lib/winjs-4.0.1/css/ui-light.css" rel="stylesheet" />
    <script src="lib/winjs-4.0.1/js/base.js"></script>
    <script src="lib/winjs-4.0.1/js/ui.js"></script>
    <link href="css/default.css" rel="stylesheet" />
    <script src="js/main.js"></script>
</head>
<body class="win-type-body">
    <div class="Toolbar" data-win-control="WinJS.UI.ToolBar">
        <!-- Primary commands -->
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'editButton',
            label:'edit',
            section:'primary',
            type:'button',
            icon: 'edit'
            }"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'deleteButton',
            label:'delete',
            section:'primary',
            type:'button',
            icon: 'delete'
            }"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'favoriteButton',
            label:'favorite',
            section:'primary',
            type:'toggle',
            icon: 'favorite'
            }"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'openWithButton',
            label:'open with',
            section:'primary',
            type:'button',
            icon: 'openfile',
            onclick: appbar.outputCommand
            }"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'downloadButton',
            label:'download',
            section:'primary',
            type:'button',
            icon: 'download',
            onclick: appbar.outputCommand
            }"></button>
        <!-- Secondary command -->
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'settingsButton',
            label:'settings',
            section:'secondary',
            type:'button',
            onclick: appbar.outputCommand
            }"></button>
        <button data-win-control="WinJS.UI.Command" data-win-options="{
            id:'shareButton',
            label:'share',
            section:'secondary',
            type:'button',
            onclick: appbar.outputCommand
            }"></button>
    </div>
    <br />
    <br />
    <br />
    <br />
    <div class="status"></div>
</body>
</html>

main.js

 

(function () {
       "use strict";
 
       function initAppBar() {
           WinJS.Namespace.define("appbar", {
               outputCommand: WinJS.UI.eventHandler(function (ev) {
                   var status = document.querySelector(".status");
                   var command = ev.currentTarget;
                   if (command.winControl) {
                       var commandWinControl = command.winControl;
                       var label = commandWinControl.label || commandWinControl.icon || "button";
                       var section = commandWinControl.section || "";
                       var msg = section + " command <b>" + label + "</b> was pressed";
                       status.innerHTML = msg;
                   }
               })
           });
       }
 
       function initAppBarEvents() {
           var editButton = document.getElementById("editButton");
           var deleteButton = document.getElementById("deleteButton");
           var favoriteButton = document.getElementById("favoriteButton");
           editButton.addEventListener("click", function (ev) {
               var status = document.querySelector(".status");
               status.innerHTML = "primary command <b>edit</b> pressed";
           });
           deleteButton.addEventListener("click", function (ev) {
               var status = document.querySelector(".status");
               status.innerHTML = "primary command <b>delete</b> pressed";
           });
           favoriteButton.addEventListener("click", function (ev) {
               var status = document.querySelector(".status");
               status.innerHTML = "primary command <b>favorite</b> pressed";
           });
       }
 
       initAppBar();
       WinJS.UI.processAll().then(function () {
           initAppBarEvents();
       });
 
})();

 

To run the application simply press the CTRL F9 and to navigate through the pages in the browser simply double click index.html.

Menu

Menu

Add new pages to our project. Go to Project > Add a New Element, select Page Control, name the page: page.html then press ADD.

Three pages are automatically created: page.html, page.js and page.css

We then add the code to get a menu with all items pointing to the home page.

Add a link to the index.html page to the new page <a href="page.html"> Go to page</a>

page.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <title>page</title>
    <link href="lib/winjs-4.0.1/css/ui-light.css" rel="stylesheet" />
    <script src="lib/winjs-4.0.1/js/base.js"></script>
    <script src="lib/winjs-4.0.1/js/ui.js"></script>
    <link href="page.css" rel="stylesheet" />
    <script src="page.js"></script>
</head>
<body>
    <div id="app">
        <!-- The content that will be loaded and displayed. -->
        <header aria-label="Header content" role="banner">
            <div class="titlearea win-type-ellipsis">
                <button class="titlecontainer">
                    <h1>
                        <span class="pagetitle">Menu</span>
                        <span class="chevron win-type-x-large">&#xe099</span>
                    </h1>
                </button>
            </div>
        </header>
        <div id="headerMenu" data-win-control="WinJS.UI.Menu">
            <button data-win-control="WinJS.UI.MenuCommand" data-win-options="{id:'section1MenuItem',label:'Page 1', type:'button'}"></button>
            <button data-win-control="WinJS.UI.MenuCommand" data-win-options="{id:'section2MenuItem',label:'Page 2', type:'button'}"></button>
            <hr data-win-control="WinJS.UI.MenuCommand" data-win-options="{id:'separator',type:'separator'}" />
            <button data-win-control="WinJS.UI.MenuCommand" data-win-options="{id:'homeMenuItem',label:'Home', type:'button'}"></button>
        </div>
        <h1>Article</h1>
    </div>
</body>
</html>

page.js

(function () {
    "use strict";
 
    function initMenuEvents() {
        document.querySelector(".titlearea").addEventListener("click", showHeaderMenu.bind(this), false);
        document.getElementById("section1MenuItem").addEventListener("click", goHome.bind(this), false);
        document.getElementById("section2MenuItem").addEventListener("click", goHome.bind(this), false);
        document.getElementById("homeMenuItem").addEventListener("click", goHome.bind(this), false);
    }
    function showHeaderMenu() {
        var title = document.querySelector("header .titlearea");
        var menu = document.getElementById("headerMenu").winControl;
        menu.anchor = title;
        menu.placement = "bottom";
        menu.alignment = "left";
        menu.show();
    }
  
    // Go to the home screen
    function goHome(evt) {
        //window.location.href = "ms-appx:///index.html";
        window.location.href = "index.html";
    }
 
    WinJS.UI.processAll().then(function () {
        //Register Events
        initMenuEvents();
    });
 
})();

 

Navigation

 

We did not use the WinJS navigation system that considers all pages as a subpage of the homepage. We use the JavaScript instruction window.location.href or HTML hyperlinks.

 

Conclusion

 

We have not tried all the WinJS controls, but this very complete library allows you to enhance a web site or even turn it into a real application.


JavaScript

Categories

Share

Follow


KodFor Privacy Policy