Hey Cortana, do you speak JavaScript?

In this article I will try to describe every steps to use Cortana with your JavaScript UWP app.

The first step is to create an xml file that represents the Voice Command Definition :

<?xml version="1.0" encoding="utf-8" ?>
<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
  <CommandSet xml:lang="fr-fr" Name="VDM_fr-fr">
    <CommandPrefix> VDM, </CommandPrefix>
    <Example> Affiche les dernières VDM </Example>
    
    <Command Name="showlast">
      <Example> Affiche les dernières VDM </Example>
      <ListenFor RequireAppName="BeforeOrAfterPhrase"> Affiche [les] dernières </ListenFor>
      <ListenFor RequireAppName="BeforeOrAfterPhrase"> Affiche [mes] dernières </ListenFor>
      <ListenFor RequireAppName="BeforeOrAfterPhrase"> Ouvre [les] dernières </ListenFor>
      <ListenFor RequireAppName="BeforeOrAfterPhrase"> montre [moi] [les] dernières </ListenFor>
      <Feedback> affichage des dernières VDM </Feedback>
      <Navigate />
    </Command>
    <Command Name="showcategorie">
      <Example> Affiche les VDM de travail</Example>
      <ListenFor RequireAppName="ExplicitlySpecified"> ouvre les {builtin:AppName} [de] {cat}</ListenFor>
      <ListenFor RequireAppName="ExplicitlySpecified"> affiche les {builtin:AppName} [de] {cat}</ListenFor>
      <Feedback> ouverture des VDM de {cat}</Feedback>
      <Navigate />
    </Command>

    <PhraseList Label="cat">
    </PhraseList>
  </CommandSet>
  <CommandSet xml:lang="en-us" Name="VDM_en-us">
    <CommandPrefix> FML </CommandPrefix>
    <Example> Show me the latest </Example>

    <Command Name="showlast">
      <Example> Show me the latest </Example>
      <ListenFor RequireAppName="AfterPhrase"> show [me] the latest </ListenFor>
      <ListenFor RequireAppName="AfterPhrase"> open the latest </ListenFor>
      <ListenFor RequireAppName="AfterPhrase"> display the latest </ListenFor>
      <Feedback>  display of the last FML</Feedback>
      <Navigate />
    </Command>

    <Command Name="showcategorie">
      <Example> Displays the FML of love </Example>
      <ListenFor RequireAppName="ExplicitlySpecified"> Opens the  {builtin:AppName} [of] {cat}</ListenFor>
      <ListenFor RequireAppName="ExplicitlySpecified"> Displays the {builtin:AppName} [of] {cat}</ListenFor>
      <Feedback> opening FML of {cat}</Feedback>
      <Navigate />
    </Command>

    <PhraseList Label="cat">
    </PhraseList>
  </CommandSet>

</VoiceCommands>
  • In this file the root element is the VoiceCommands Element, it’s contains a list of commandSet elements. Each commandSet is for a language.
    • An commandSet contains a list of command (and others things …)
      • A command is a “command” and contains an example, and multiple elements of ListenFor, a feedback element, and an instruction element (navigate in the first sample) that explicitly specifies that this command will navigate to your app.
        • ListenFor is the command phrase, it has a RequireAppName attribute that specifies where the app name can appear in the voice command.
      • A PhraseList that contains multiple item, each Item specifies a word or phrase that can be recognized to initiate the command that references the PhraseList (optional). You can optionnaly load dynamically a list of items from your code.

You have to be very careful, when you write this file! If you don’t respect the structure or If you miss an element, the Cortana API will fall in error without any information*.

The final step.
Instantiate your new XML file of VCD, in your JavaScript code.

In this following code, I call initCortana function to initialize the VCD file using de VoiceCommandDefinitionManager API located in the Windows.ApplicationModel.VoiceCommands namespace.

You have to pass your xml file to the « installCommandDefinitionsFromStorageFileAsync » function. If everything it’s not OK the callback of the promise returns a error and you pass by:

console.error(‘error file vdmvoicecommands.xml’, er);

In this case: check and re check an re re re check your VCD file 🙂

If the file was initialized correctly, you could add a list of items to populate the phrase lists.



    var wap = Windows.ApplicationModel.Package;
    var voiceCommandManager = Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager;

    var initCortana = function (categories) {
        categories = categories || [];
        return wap.current.installedLocation.getFileAsync("vdmvoicecommands.xml").then(function (file) {
            return voiceCommandManager.installCommandDefinitionsFromStorageFileAsync(file);
        }, function (er) {
            console.error('error file vdmvoicecommands.xml', er);
        }).then(function () {
           var language = window.navigator.userLanguage || window.navigator.language;

            var commandSetName = "VDM_" + language.toLowerCase();
            var commansets = Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.installedCommandDefinitions;
            if (commansets.hasKey(commandSetName)) {
                var vcd = commansets.lookup(commandSetName);
                var phraseList = [];
                categories.forEach(function (c) {
                    phraseList.push(c.title);
                });
                return vcd.setPhraseListAsync("cat", phraseList).then(function () {
                    console.log("VCD loaded !");
                 }, function (er) {
                    console.error('error set phraseList', er);
                })
            } else {
                console.warning("VCD not installed yet?");
            }
        }, function (ee) {
            console.error("installCommandDefinitionsFromStorageFileAsync error", ee);
        });
    }

Now you have to handle the activation event that will get sent to your app, and parse arguments.

  app.addEventListener("activated", function (args) {
        var appLaunchVoiceCommand = activation.ActivationKind.voiceCommand || 16;
        if (args.detail.kind === appLaunchVoiceCommand) {
            return handleVoiceCommand(args);
        }
    });

The handleVoiceCommand function parse the args passed from the activated app event and do the navigation to the right place

    var app = WinJS.Application;
    var commands = {
        "showlast": function (commandresult) {
            return WinJS.Navigation.navigate(VDM.Pages.VDMList, { viewType: 'last', viewLabel: WinJS.Resources.getString('appbar_views_last') });
        },
        "showcategorie": function (commandresult) {
            var categorie = commandresult.semanticInterpretation.properties.cat[0];
            return WinJS.Navigation.navigate(VDM.Pages.VDMList, { viewType: categorie.toLowerCase(), viewLabel: categorie });
        }
    }
    var handleVoiceCommand = function(args) {
        if (args.detail && args.detail.detail) {
            var voicecommand = args.detail.detail[0];
            if (voicecommand) {
                var result = voicecommand.result;

                if (result) {
                    var commandname = result.rulePath ? result.rulePath[0] : '';
                    var properties = result.semanticInterpretation ? result.semanticInterpretation.properties : {};
                    console.log("voice activation (" + commandname + ") confidence: " + result.rawConfidence, result);
                    var cmd = commands[commandname];
                    if (cmd) {
                        return cmd(result).then(function () {
                            VDM.Utils.loadMainAds();
                        });
                    }
                }

            }
        }
    }
    app.addEventListener("activated", function (args) {
        var appLaunchVoiceCommand = activation.ActivationKind.voiceCommand || 16;
        if (args.detail.kind === appLaunchVoiceCommand) {
            return handleVoiceCommand(args);
        }
    });

Let’s talk more with the app (with appService)

If you need a deeper integration with Cortana, you could also « talk » with her using an app service.

An app service is a Background task that Cortana could call when you use a command. You will have to explicitely declare which service Cortana must call in your command file.

    <Command Name="getFML">
      <Example> tell me a FML </Example>
      <ListenFor RequireAppName="ExplicitlySpecified"> tell me a {builtin:AppName} </ListenFor>
      <Feedback> Here an FML </Feedback>
      <VoiceCommandService Target="FMLVoiceCommandService"/>
    </Command>

Now let’s implement the Application Service. You must add it to your application manifest by pointing to JavaScript file, and give it the name you use in the command file :

 <uap:Extension Category="windows.personalAssistantLaunch"/>
 <uap:Extension Category="windows.appService" StartPage="js/voiceCommandService.js">
    <uap:AppService Name="FMLVoiceCommandService"/>
 </uap:Extension>

Beware the visual studio appxmanifest editor, it removes this entry if anything changes in it (like a upgrade of version when you generate a new appx package) this bug will certainly be corrected in the update 1 of Visual Studio.

Now let’s create the javascript file and implement the service itself.

When you are using JavaScript App Services are a lot like independant web workers. You can import all the JS file you need to run your code by using importScripts

importScripts("/WinJS/js/base.js");
importScripts("/js/FML.API.js");

The service is loaded by cortana, so when is loaded the doWork function is called.
If the Windows.UI.WebUI.WebUIBackgroundTaskInstance.current.triggerDetails is an instance of Windows.ApplicationModel.AppService.AppServiceTriggerDetails, we can get voice command used to launch this task and do things like:

  • Send an waiting response message
  • displays items
  • Send a final response message
var appService = Windows.ApplicationModel.AppService;
var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;
var details = backgroundTaskInstance.triggerDetails;
var deferral = backgroundTaskInstance.getDeferral();

if (details instanceof appService.AppServiceTriggerDetails) {
    voiceServiceConnection = voiceCommands.VoiceCommandServiceConnection.fromAppServiceTriggerDetails(details);
    voiceServiceConnection.addEventListener("voiceCommandCompleted", onVoiceCommandCompleted);

    voiceServiceConnection.getVoiceCommandAsync().then(function completed(voiceCommand) {

    // here you can check the voiceCommand, call an API (or read a file) and send messages to Cortana UI

            var userMessage = new voiceCommands.VoiceCommandUserMessage();
                    userMessage.spokenMessage = "I'm Cortana and I read this awesome message";
                    userMessage.displayMessage = "I'm Cortana and I read this awesome message";
            var response = voiceCommands.VoiceCommandResponse.createResponse(userMessage);
            return voiceServiceConnection.reportSuccessAsync(response);

    });
}

The displayMessage string must not exceed 256 character

And now, with this, you can ask Cortana: « hey cortana, tell me a FML »

Bouton précédent (Back Button) avec le System Navigation Manager dans les applications (UWP) Windows 10

Dans les nouvelles applications Windows 10, nous avons la possibilité dans la version desktop d’une application d’utiliser le bouton de navigation (bouton précédent) du système qui est placé à coté du nom de l’application dans la barre de titre (comme celui qu’on trouve dans l’application de paramètres:

back

Ce bouton est nativement géré par WinJSContrib, il suffit pour cela d’activer l’option « enableSystemBackButton » :

 WinJSContrib.UI.enableSystemBackButton = true;

Un sample est disponible ici 🙂

Vous pouvez aussi l’implémenter manuellement. Il suffit d’utiliser la classe SystemNavigationManager et de modifier la propriété appViewBackButtonVisibility pour afficher ou cacher le bouton.

// il faut vérifier la disponibilité de l'api (disponible que sur desktop)
if (window.Windows && window.Windows.UI && Windows.UI.Core && Windows.UI.Core.SystemNavigationManager) {
    Windows.UI.Core.SystemNavigationManager.getForCurrentView().appViewBackButtonVisibility = Windows.UI.Core.AppViewBackButtonVisibility.visible;
    // ou pour cacher le bouton
    Windows.UI.Core.SystemNavigationManager.getForCurrentView().appViewBackButtonVisibility = Windows.UI.Core.AppViewBackButtonVisibility.collapsed;
}

Et pour gérer le clique il suffit de se brancher sur l’événement onbackrequested:

if (window.Windows && window.Windows.UI && Windows.UI.Core && Windows.UI.Core.SystemNavigationManager) {
    var systemNavigationManager = Windows.UI.Core.SystemNavigationManager.getForCurrentView();
    systemNavigationManager.onbackrequested = function (args) {
        if (WinJS.Navigation.canGoBack) {
            WinJS.Navigation.back();
            args.handled = true;
        } else {
            systemNavigationManager.appViewBackButtonVisibility = Windows.UI.Core.AppViewBackButtonVisibility.visible;
        }
    }
}

Pour la version en C# (et ma source) c’est par ici

Resolving WinJS webcomponents attributes

Now that you know how to use WinJS as webcomponents, and how to declare your controls, we will talk about the mecanism for resolving attribute values.

Lets work with an example :

<win-listview id="recentItemsList" member 
	itemdatasource="list:ctrl:recentItemsPromise" 
	itemtemplate="select:#pictureItem" 
	iteminvoked="event:ctrl:recentListItemInvoked"></win-listview>

You could think of attribute resolution as

[what to do]:[where to look]:[string token]

If you look at the « itemdatasource » attribute, you could read it like this : get the « recentItemsPromise » property from parent control, and wrap it in a WinJS.Binding.List for the ListView.

In this example, « recentItemsPromise » is just a string, and « ctrl » and « list » are operators. The list operator is smart enougth to see that it received a promise, and await it to set value.

Operators are just functions referenced in the namespace WinJSContrib.Utils.ValueParsers. You could provide your own operators by adding them to this namespace.

When the attribute is resolved, you will endup with something equivalent to :

list(domelement, ctrl(domelement, "recentItemsPromise"));

As you can see, their is no complex parsing involved, it is very efficient, and enforce composition. You have no limit at the number of operators you can chain like this.

You could find the list and details about built-in operators in the API documentation.

registering your WinJS webcomponents

In the last episode, we had a glimpse of using WinJS controls with webcomponents syntax, thanks to WinJS Contrib. Let’s dig a little deeper and see how you could use your own controls with it.

On platforms with non native implementation of webcomponents, the WinJS Contrib module is attaching an observer on each page controls (and releasing it on when disposing the page). This observer uses MutationObserver to track changes in the DOM and automatically build the WinJS controls that you registered. It means that controls, not on a page (like controls in default.html) are not instantiated. In such case, you must call « WinJSContrib.UI.WebComponents.inspect(element) » just like you would have to call WinJS.UI.processAll with vanilla WinJS.

Registering a control is just about providing the name of the DOM element, and how to map DOM attributes to your control implementation. If you don’t want to use DOM element attribute, you could still use data-win-options, or use both.

Declaring a control is quite easy. If you look in « winjscontrib.ui.webcomponents.js », you will find the declarations for WinJS controls. Lets look at the declaration for the DatePicker :

	WinJSContrib.UI.WebComponents.register('win-datepicker', WinJS.UI.DatePicker, {
		properties: ['calendar', 'datePattern', 'disabled', 'maxYear', 'minYear', 
				'monthPattern', 'yearPattern', 'onchange', 'current'],
		events : ['change']
	});	

You must call WinJSContrib.UI.WebComponents.register to wrap your control. You must at least provide the name of the DOM element, and the constructor for your control. The third argument is an object containing the mapping for your control. Within this object, the items in « properties » indicate the name of the properties that you want to map as attribute on the element, and « events » indicate the name of the events you want to map.

« properties » and « events » are shortcuts to build a mapping. You could provide a raw map if you have to do fancy stuf. Lets imagine that the calendar attribute used on DOM element must map to something like _calendarBuilder.calendar in your control. In such case you could use :

	WinJSContrib.UI.WebComponents.register('win-datepicker', WinJS.UI.DatePicker, {
		properties: ['datePattern', 'disabled', 'maxYear', 'minYear', 
				'monthPattern', 'yearPattern', 'onchange', 'current'],
		events : ['change'],
		map: {
			"CALENDAR" : {
				attribute : "calendar",
				property : "_calendarBuilder.calendar",
				type : "property",
				resolve : true
			},
			"CHANGE" : {
				attribute : "change",
				property : "_calendarBuilder.changeevent",
				type : "event",
				resolve : true
			}
		}
	});	

This syntax is more verbose but you have total control over the mapping. Note that the mapping key should be uppercase.

Another scenario that may come in mind is how do I map a fragment/page to a webcomponent ?

This is a lesser known feature of WinJS but WinJS.UI.Pages.define actually returns the constructor for the page, with the exact constructor signature of common WinJS controls (first parameters provides containing DOM element, and second parameter for control options).

To map a page/fragment to a component, you just have to pass the constructor. If you look at the searchbar control in the sample application, you will find an example that looks like this :

var SearchBarCtor = WinJS.UI.Pages.define("/controls/searchbar/searchbar.html", {
	//control implementation not mentionned here for brievity
});

//for use as standard control with data-win-control
WinJS.Namespace.define('Flickity.UI', { SearchBar: SearchBarCtor });

if (WinJSContrib.UI.WebComponents) {
   	WinJSContrib.UI.WebComponents.register('flickity-searchbar', SearchBarCtor);
}

The last use case we will cover now is for controls containing controls. Sometimes you write a control that wraps one or more other controls. You can map those controls directly to DOM attributes by using their own registration. WinJS Contrib has a control that wrap a SemanticZoom and the two associated ListView for managing list with groupings. The declaration for this control use that pattern :

WinJSContrib.UI.WebComponents.register('mcn-semanticlistviews', WinJSContrib.UI.SemanticListViews, {
	properties: [],
	controls: {
		"listview": WinJS.UI.ListView,
		"zoomedOutListview": WinJS.UI.ListView,
		"semanticZoom": WinJS.UI.SemanticZoom
	},
	map: {
		"DEFAULTGROUPLIMIT": { attribute: 'defaultGroupLimit', property: '_dataManager.defaultGroupLimit', resolve: true },
		"GROUPKIND": { attribute: 'groupKind', property: '_dataManager.groupKind', resolve: true },
		"FIELD": { attribute: 'field', property: '_dataManager.field', resolve: true },
		"ITEMS": { attribute: 'items', property: '_dataManager.items', resolve: true },
	}
});

The mapping can also have a « controls » section, which is used as a map. The key is the prefix for the control, and the value is the constructor for the control. When you register a control, the webcomponents module is creating a mapping and attach it to the constructor. That’s why you have nothing more to pass to map child control. However, the controls you are using as child map should have been declared before declaring this one.

The control can then be declared like this :

<mcn-semanticlistviews id="semanticzoom"
	listview.itemtemplate="select:#listItemTemplate"
	listview.groupheadertemplate="select:#groupItemTemplate"
	zoomedoutlistview.itemtemplate="select:#semanticItemTemplate"
	defaultGroupLimit="12"
	groupKind="global:WinJSContrib.UI.DataSources.Grouping.byField"
	field="metadata.genre"
	items="global:moviesSample">				
</mcn-semanticlistviews>

Next time we will have a look at the resolution of properties and detail the various options you have.

Using WinJS controls as webcomponents

WinJS Contrib goal is to makes WinJS development faster, and simplify common tasks. Last time we saw that WinJS contrib enables using JavaScript classes to define your pages, enabling ECMAScript 6 or Typescript in your applications.

This time we will talk about something that could radically change the way you write your pages. As stated previously, WinJS Contrib override core page control. This new control has the benefit of providing an extensible page lifecycle.

The code snippets in this post are coming from the sample applications we built to illustrate WinJS Contrib features. The first is from a vanilla WinJS application, and the other is from the exact same application with WinJS Contrib and webcomponents.

With vanilla WinJS, you declare controls like this:

<div id="recentItemsList" 
    data-win-control="WinJS.UI.ListView" 
    data-win-options="{ 
        itemTemplate : select('#pictureItem') 
    }"></div>

The control model in WinJS is very effective but this syntax for declaring controls is a bit ugly. It’s verbose, and the parsing of options does not allow extensions. In all WinJS samples, the list is bound to data in the options using a static variable. Believe me, it is really a bad practice. In some templates, you will find the data bound with syntax like this « select(‘.pagecontrol’).winControl.myData ». Despite the fact that this syntax is also ugly, in any real world application, you have to link some of your controls property to something coming from a promise. It can be http call, data stored in files, local database, etc. You end up writing code for wiring data and controls.

enter webcomponents !

WebComponents is a new paradigm, currently under discussion by W3C, to declare components as custom DOM elements. You can get details on this by looking at webcomponents.org. As the time of this writing, Webcomponents have native implementation in Blink (engine used in Chrome and Opera) and partial support in Firefox. No support in IE or Spartan yet.

Webcomponents is really a very promising spec, and almost all modern front-end framework uses this syntax. Unfortunately, WinJS does not…

WinJS Contrib has a new module, that enables using controls with a webcomponents syntax like this :

<win-listview id="recentItemsList" member 
    itemdatasource="list:ctrl:recentItemsPromise" 
    itemtemplate="select:#pictureItem" 
    iteminvoked="event:ctrl:recentListItemInvoked"></win-listview>

Using this also allow many improvements on the syntax. As you can see, some of the code that resides in the controller with vanilla WinJS now moved to the declaration of the control. The resolution of control properties can be extended and use the same mecanism we described previously for providing arguments to other WinJS Contrib helpers.

We will deep dive into this mecanism in another post, but to give you a sneek peak, this mecanism use operators to resolve the property. If we look at the « itemdatasource », the string « list:ctrl:recentItemsPromise » could be read as : get the recentItemsPromise property from the containing control, and wrap the result in a WinJS.Binding.List datasource. WinJS Contrib has several operators and you could add your own.

To use webcomponents in your application, you just have to include « winjscontrib.core.js » and « winjscontrib.ui.webcomponents.js ». The module is defining the components for most WinJS controls. It maps control’s properties as attributes on the DOM element. We haven’t tested them all with this new syntax. We would be pleased to get any feedback from you if you encounter troubles with it, or if we missed some properties.

This module use core webcomponents on platform supporting it, and a polyfill for the others. The polyfill uses « MutationObserver ». It means it will work on IE11 and above, so you can use it in your Windows 8.1 and Windows Phone 8.1 applications, and obviously on Windows 10. We haven’t fully tested on Android and iOS yet but it’s the next step, because we use WinJS in many cross platform applications.

In the next posts, we will detail the resolution of properties, and the way you could declare your controls to use webcomponents syntax. In the meantime, go check the sample application, and feel free to send us feedback.

WinJS and ES6

It’s time for a new episode about WinJS and WinJS Contrib ! this time we will talk about using ECMAScript 6 with WinJS and more specifically about using JavaScript classes.

With WinJS pages, you use object literal to define your pages, something like :

WinJS.UI.Pages.define('/pages/home/home.html', {    
    processed: function(element, option){ 
    },
    ready : function(element, options){
    }
});

WinJS will build a constructor for the page and add the content of the object literal as a mixin on that constructor. When the page is invoked, the constructor is used to produce a new object that hold those methods on its prototype. What is great is that you could call WinJS.UI.Pages.define multiple time on the same page, using some external mixin. This model is very interesting because you could work in the best possible way for a developper : composition.

This programming model has no limit in terms of what you can do, however it has some drawbacks. First, a lot of developpers are not JavaScript gurus. Using OO languages along with JavaScript, they are not familiar or comfortable with the concept of mixins and this syntax looks like some esotheric thing. It’s also a different programming model than the business logic where you may enforce something more « object oriented ». I know « object oriented » is not in the « pure » JavaScript paradigm, but that’s where JavaScript is going with things like ES6 classes.

The other problem with this syntax is about the tooling. More often than not, intellisense goes nuts and does not provide you any help about a variable you created in another function, 5 lines of code above.

Last but not least, the object literal makes things like ECMAScript 6 classes, or Typescript a hell to work with WinJS. This is really odd because : 1 – Typescript is from Microsoft and it does not fit well with their own UI/front-end framework, and 2 – if you play with Windows 10 preview and dev tools, you may have noticed that, if you create an universal app in JavaScript, you can use ES6 in your application. It has not been officially announced yet but it looks like Windows 10 UAP in HTML and JavaScript uses some form of EdgeHTML (the Spartan engine). It means that you can use all the ES6/HTML/CSS goodness that comes along with it, as well as the performance benefits.

So, how could you use JavaScript / ES6 / Typescript classes with WinJS ? in fact it is quite simple. Last time we looked at the basic features of WinJS Contrib, and more specifically the fact that WinJS Contrib override WinJS page control. Once you put WinJS Contrib, you could call WinJS.UI.Pages.define with a constructor instead of an object literal.

class HomePage{
    ready(element, options){
    }
}
WinJS.UI.Pages.define('/pages/home/home.html', HomePage);

If you start playing with ES6 or Typescript, you may also use some of the other ES6 features. One that could help you improve readability and reduce code is arrow functions. Arrow functions are anonymous function with a syntax identical to lambdas in C#. In addition to syntactic sugar, the arrow functions does not change scope. If you use arrow function instead of functions, the « this » scope is preserved, and you avoid writing tons of ugly code like « that = this ».

To demonstrate those features, we made an ES6 version of the demo application using JavaScript classes. This version is still a Windows 8 version transpiled using Babel, but if you want to have a lot a fun, you could bring it to a Windows 10 UAP (it’s just copying files) and drop Babel, it will work just fine and it is a wonderful playground to experiment with new features of HTML/Javascript in the new rendering engine in Windows 10.

If you want a more direct look, you could check the « searchbar » control that we used to illustrate WinJS Contrib basics on the previous post.

WinJS Contrib Basics

Now that we set the stage for WinJS and WinJS Contrib, it’s time to dig into some code goodness.
In this episode, we will look at the fundamental of WinJS Contrib.

interactive elements

You have interactive elements in all apps. Weither it is with mouse or touch, it is good practice to provide visual feedback on interactions, otherwise the user feel trust in your application. WinJS Contrib has an abstraction over interactive element. Using it will provide an appropriate cursor with mouse, and a visual feedback with touch. It is as simple as :

WinJSContrib.UI.tap(domElement, callback, options);

the third argument is optional and allow you to specify such thing as « disableAnimation » to avoid the « pressed » effect with touch, or « lock » to add interactivity on elements in a scrollable are (like adding a button inside an item in a listview). The beauty is that « tap » is cross platform and will act as « fastclick » on Android and iOS.

When using it, a css class « tap » will be added on the element, and when element is pressed a « tapped » will be set as long as the element is pressed. You can use this to override the default animation.

In previous post, we explained that WinJS Contrib replaces the page implementation of WinJS. Our page control allow you to declare taps in your markup. You must simply add a « tap » attribute on an element, and as a value, you pass the name of the function on your page, like this :

<div class="button" tap="someFunctionOnMyPage"></div>

When called, your function will be bound to the page, it means that when the function is called, « this » refer to your page.

You could specify arguments to tap by adding a « tap-args » attribute. The value will be passed in the argument to the function on your page. The value could be a simple string, or use the resolution pipeline from WinJS Contrib. We will expand on this pipeline in another post, for now, just note that you can inject argument from a property or a function of your page.

<div class="button" tap="someFunctionOnMyPage" tap-args="ctrl:somePropertyOrFunctionOnMyPage"></div>

Another thing that is really common in all applications is to navigate after clicking a button. You can implement this as easily as tap with a « linkto » attribute. As a value, you will specify the url of the target page.

<div class="button" linkto="/pages/home/home.html"></div>

In case you want more, linkto can have arguments, just like tap. The arguments will be passed to the navigation

<div class="button" linkto="/pages/home/home.html" linktoargs="obj:{ index: 3}"></div>

interacting with DOM

When writing a WinJS page, you end up writing tons of DOM selector to get instances of the controls, or DOM element that you will interact with. Your page end up looking a bit ugly with things like this all around the place :

var listView = page.element.querySelector('#myListView').winControl;

If you are wandering why scoping selector to page, go have a look at some WinJS best practices.

WinJS Contrib page introduce a mecanism to map elements and controls as properties on your page by adding a « member » attribute on the node. You could leave it blank, and the name of the property will be the « id » on the node, or you could specify the name of the property.

<div class="button" member="btnClose"></div>

If the element has a control attached on it, the property will hold the control, otherwise it will be the DOM element :

<div member="listview" data-win-control="WinJS.UI.ListView"></div>

then you will use it magically in your page :

page.listview.itemDataSource = new WinJS.Binding.List().dataSource;

If you prefer having the declarations in your page, we still have some goodness for you. The page control has « q » and « qAll » functions for running querySelector and querySelectorAll from your page element, which is at least shorter than the full syntax. The « qAll » function is also kind enougth to map the result as an array, so you can use forEach on the result.

page.qAll('.button').forEach(function(buttonElement){
    //do something
});

preventing leaks

The first cause of memory leaks is unreleased event listeners having a closure on some global variable. To ensure releasing your listener without adding some (ugly) extra code to your page, WinJS Contrib provide an event tracker object. The page control holds an instance of it that you can use. You use this object to attach functions to event listeners, and when you dispose the tracker, it will dispose all attached events automatically. If you use the page instance, the page will take care of releasing the tracker.

instead of

ctrl.showBinded = ctrl.show.bind(ctrl);    		 
ctrl.searchInput.addEventListener('focus', ctrl.showBinded);
...
ctrl.searchInput.removeEventListener('focus', ctrl.showBinded);

you have :

ctrl.eventTracker.addEvent(ctrl.searchInput, 'focus', ctrl.show.bind(ctrl));    

does all this really help ?

Well, see for yourself by looking at the small sample application that we made. You have one version with WinJS only, and another with WinJS Contrib.

This application is for searching Flickr. If you look at the code for the search bar control and compare the pure WinJS and the WinJS Contrib version, you will see a real difference (it removed 45 lines of code on 154…)

Next time we will see other features enabled by the WinJS Contrib page