Le Post de MCNEXT

Les articles des consultants de MCNEXT

Bienvenue sur le Post de MCNEXT !

Retrouvez ici les posts des consultants du groupe MCNEXT ( déjà plus de 500 !)
Vous voulez en savoir plus sur MCNEXT ou vous souhaitez nous rejoindre ?

Consultez notre site corporate ici
Suivez nous sur twitter: @LE_FIL_MCNEXT
Regardez nos videos sur notre chaîne YouTube McnextTV

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.

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.

PASSBAC – retour sur les 2 keynotes

Lors de la première Keynote animée par Carlo Ratti, professeur au MIT et architecte, Carlo nous a sensibilisé sur le fait que le volume de données que nous générons aujourd’hui est en constante progression. Le volume de données produit depuis le début de l’humanité jusqu’en 2003 équivaut actuellement au volume généré en 2 jours. La démultiplication et la démocratisation des terminaux et objets connectés font que chacune de nos actions est désormais numérisée. Il est désormais possible, grâce aux solutions de Big Data, de tirer parti de cette manne gigantesque d’information.

« Big Data is what you cannot put in an Excel spreadsheet »

Carlo nous a montré les résultats des études menées avec son équipe autour de différents projets :

  • l’activité des téléphones mobiles à Rome lors de la finale France/Italie de la coupe de monde de football de 2006
  • utilisation des cartes de crédit en Espagne pendant la période de noël
  • utilisation des données gps des taxis à Lisbonne
  • pattern des déplacements en Italie de touristes américains vs italiens
  • etc.

Je vous conseille fortement de visiter le site du Senseable City Lab; les vidéos sont vraiment impressionnantes et permettent d’entrevoir ce qu’il est possible de collecter et d’analyser, afin de mieux comprendre notre monde et de pouvoir adapter nos comportements en conséquence (ou pas). Les champs d’application sont énormes et uniquement limités à notre propre imagination.

La Keynote d’aujourd’hui a été animée par Miko Yuk,  fondatrice de BI Brainz, entreprise leader dans le dataviz et le story telling. Miko part du constat que la plupart des entreprises ont une organisation décisionnelle en silo (IT Pros, Analysts, Data Scientists), tout en narrant ses retours d’expérience qui sonnent comme un écho dans ma tête.Vous avez beau avoir travaillé des heures ou des jours durant sur un dashboard; au final l’utilisateur s’intéressera en premier lieu à la forme et non aux données.

La BI est présente dans la plupart des sociétés, l’année dernière on estime que 97 milliards de dollars ont été dépensés en BI. Néanmoins, les utilisateurs sont loin d’adopter massivement les solutions qui leur sont proposées, en moyenne, on ne capte que 21% des utilisateurs.

« Data visualisation and visual story telling are the future of useful and intelligent analytics »

La façon de présenter et de scénariser la donnée est primordiale afin de capter l’ensemble de nos utilisateurs et doit répondre aux deux principaux aspects suivants:

  • communicate knowledge
  • interpret experiences

La data visualisation et le story telling sont les facteurs clés qui vous permettront de communiquer l’information de la façon la plus efficiente. A travers les exemples exposés par Miko, j’ai pu noter quelques outils à regarder de plus prêt :  , .

Ces deux keynotes sont dans la mouvance actuelle du big data et de la data visualisation. Ce sont ces deux points clés qui permette(nt)(ront) aux entreprises de se démarquer et d’être plus réactives vis-à-vis de leurs clients et de la concurrence.

Fred.

PASSBAC 2015 – Day #1

PASSBAC2015

Pour une fois, les annonces ne sont pas venues de la Keynote, mais de la session de Miguel Llopis intitulée « Data Hunters & Gatherers: Discover, Acquire, and Transform Your Data with Power Query »

  • Power Query sera disponible sur toutes les versions d’Excel et non plus réservée à l’Office Pro Plus, exceptés quelques connecteurs qui ne seront disponibles que sur la version Pro Plus.
  • Sur la version Excel 2016, actuellement en Public Preview, Power Query
    • sera intégré et supportera les requêtes VBA et l’enregistrement de macro
    • supportera les actions undo/redo
    • supportera le copier/coller même d’un classeur à un autre
    • sera mis à jour régulièrement et pas uniquement à chaque montée de version Office
  • Quant à la version actuelle, la mise à jour de Mai intégrera :
    • Le support de OData V4
    • L’usage d’authentification ADFS custom
    • La possibilité de désactiver les prompts « native database queries »
    • L’usage de Windows credentials alternatif pour exécuter les requêtes
    • Et de nouvelles transformations (la fonction mediane pour les opérations Group By et Aggregate Column, la conversion de DateTimeZone en LocalTime et la possibilité de supprimer les lignes vides)

Pour les autres sessions suivies dans la journée, j’ai appréciée:

  • la session de Jen Underwood intitulée « Best Practice Mobile Dashboard Design  » et plus particulièrement les démos effectuées sur DataZen
  • la session de Marc Reguerra et Jeff Lumpkin intitulée « The Valued Analyst: From Data to Insight in 60 Minutes » pour leur dynamisme, leurs conseils et l’originalité de leurs démos Power BI

Deux sessions que je détaillerai, prochainement, plus précisément.

Entre deux sessions, j’ai pu aussi me balader dans l’espace exposant et m’intérresser plus particulièrement aux solutions proposées par deux d’entre eux :

  • Pyramide Analytics qui propose une solution front BI intéressante
  • et SQL Sentry, qui n’est plus a présenté, mais qui propose une solution de monitoring plus sexy et bien plus légère que celle proposée par Microsoft avec SCOM

Fred.

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

Introducing WinJS Contrib

Last time we tried to explain why and when WinJS can be a good fit for your HTML application. As an application framework, WinJS is very lean. It’s a great strength, but if you have worked a little with it, you may have found that you write a lot of boilerplate code.

After many applications using WinJS, we decided to share the various helpers that we use as a contrib project, available on Github. If you want to get a glimpse of what WinJS Contrib can do for you, you could have a look at the source, or install the showcase app from the Windows Store. The showcase app illustrate many of the features and allow you to watch the code and the API documentation. The source code for the showcase app is also available on Github.

In this series we will look at the different pieces of WinJS Contrib. But for now, we will provide a general overview.

WinJS Contrib is not delivered as a big library. Instead, we choose to provide several small pieces with dedicated purpose. You will find helpers for communicating with webworkers or iframes, a tiny search engine, helpers to ease the implementation of WinRT features (background transfert, multiscreen, contact API, …), and a bunch of UI controls.

Each of those pieces have been developped and used in one or many applications. Some of those applications can be found in the Windows Store like XBMC Commander, or I’m hungry, and several others apps for our customers.

The heart of WinJS Contrib is in the « core » library. It contains all the helpers for improving syntax and productivity. It’s required by many of the other parts. In addition to the helpers, the core library is also replacing the page control from WinJS. We tried many ways to improve WinJS syntax but unfortunately, WinJS is not built with extensibility in mind, and we find it to be the least invasive way.

The custom page control does not remove anything from core page but it adds a lot. Our page control extend the lifecycle provided in WinJS pages, and provide extension points to unlock many features (enhance the page object, productivity and memory management, using ES6 classes, providing a way to use webcomponent syntax, …).

One package we use in all our projects is the « bindings ». It contains a mecanism for having arguments with your bindings, and a whole lot of basic bindings. For example, bindings for show/hide, enable/disable, binding for images, or for adding ellipsis on text.

Another usefull package is the « animations ». WinJS animations are visually appealing, but one thing that makes them useless in many cases is the fact that you cannot set the duration of the animation, or the item delay. WinJS Contrib animations are all configurable.

To illustrate the various features over this series, we decided to provide a specific Github repository with a small application. You will find a version built only with WinJS, and other versions leveraging features of WinJS Contrib.

In the following episodes, we will go into more details on the various improvements that you will be able to leverage with WinJS & WinJS Contrib, using this application for code demonstrations.

Article dans le Magazine Solutions IT & Logiciels : Applications métiers de terrain, mobiles et tactiles

Magazine Solutions IT & Logiciels : 4 pages consacrées à MCNEXT – Parution ce mois-ci – « MCNEXT développe des applications métiers de terrain, mobiles et tactiles » avec les témoignages de deux de ses clients – http://bit.ly/1DPBDtH ou http://bit.ly/1HzNQUV

Event Paris : Les Cubes selon Microsoft – Jeudi 7 mai 2015

Event Paris : Les Cubes selon Microsoft donnez une nouvelle dimension à vos analyses ! Jeudi 7 mai 2015 de 08h45 à 12h00 dans les locaux de MCNEXT – Inscription : Café MCNEXT / Les Cubes selon Microsoft – Le jeudi 7 mai 2015

Why WinJS can be a good front-end framework…

We are still early in 2015 and the JavaScript front-end ecosystem is still hot.

There are many popular frameworks out there, Angular 1.x, Angular 2 in alpha, React, Ember, Backbone, Aurelia, Polymer, …

This post is the first on a series about WinJS. In this first episode, we will see what is WinJS, and what it is good for.

Web vs Native

All those framework have their own personnality, strengths and weaknesses. But they all have one thing in common : they are built for the web. To my point of view, none of those frameworks are built for making embedded applications like native HTML Windows apps, Cordova apps, Firefox OS apps, …

Designing and optimizing a mobile application for web, or for an embedded applications is different. When building for the mobile web, your worse ennemy is network latency. Every image, stylesheet or script is slowing your site down, and every bytes count. You try to bundle your files as much as possible to avoid those pitfalls.

When you are building for an embedded application, you don’t care about those network latencies. Every file resides on the device, and loading them is as fast as the SSD is on the device. In fact, on most modern hard drives, it can be faster to load several small files than loading a big one. In addition, in those applications, you will favor loading your application incrementally. It helps your app start fast, and saves memory and battery on the device.

Users don’t care…

With an embedded application, users expectations are different. The user does not know, or care, that your application is built using web technologies. He click on your app icon and assumes that it will perform as any other app on his device. The rendering engines are getting faster and faster but it is still not as performant as native.

To achieve a native look and feel, you must have a fine grained control over the DOM, and you sometimes have to orchestrate how and when your views are built and rendered. Common frameworks tends to abstract DOM away and relies on data binding to build UI. It could lead to a lot of frictions when it comes to optimizing your views. Some frameworks, especially Ionic are built with that performance constraint in mind, but unfortunately, they does not work well on all platforms.

WinJS

WinJS is a JavaScript front-end framework that was publicly announced in september 2011, at the first Microsoft //Build conference. At that time, it was designed to make native Windows applications using HTML and javascript. Since then, it has been open-sources (go have a look at it on Github) and the latest version are designed to work well on all recent mobile devices. WinJS has basics for the different peaces needed by an application framework (templates, binding, messaging, …) and a rich set of UI widgets.

WinJS has been designed for making fast, native looking applications, and it’s great for that. Whether it is on Android, iOS, or Windows, you can take the most of what your device can do with web technologies. You can use it for web (it is still HTML/CSS/Javascript) but it’s really not designed for it.

What is great with it is that the framework rely on componentization of your UI. You are building your UI by composing controls. Controls can be simple JavaScript classes, or they can rely on « Fragments ». A fragment is loaded from an HTML file, and all dependencies defined in the HTML are loaded along with the fragment. You could modularize your UI and logic, and load it incrementally in a very natural way.

As you can see, the mindset when building an application with WinJS is very much like what you have with WebComponents approaches (except for the Shadow DOM aspects). The main difference is about the syntax you use for declaring your controls (instead of defining custom elements, you use attributes).

So, WinJS is wonderful ?

Well… considering what you can do with it, yes. But it is far from perfect. Sometimes, it’s really not developper friendly.

WinJS is very unopiniated about how to do things. It’s great because you stay in control but it means you have to do a lot of things by hand. What is really sad is that, in its almost 4 years, WinJS has not improved at all for that matter. Microsoft has focused their efforts on UI widgets (making them cross platform for example), but you are still writing a lot of unnecessary boilerplate code.

We have made dozens of applications with WinJS, for Windows, as well as Android or iOS. From time to time we gathered a lot of tools and helpers, and a while ago we decided to publish them to the community, as a « WinJS Contrib » project. In the other parts of this series, we will show you the different aspects that you could improve by using WinJS Contrib.

We will see how to reduce boilerplate code, use ES6/Typescript classes, use WinJS with webcomponents syntax in the markup… so stay tuned !

Suivre

Recevez les nouvelles publications par mail.

Rejoignez 36 autres abonnés