Share
Embed
WorkWave Frontend Technologies
Internal presentation of technologies used in WorkWave projects
Matteo Ronchi
January 25, 2017
Transcript
88 slides
-
• Server-side generated HTML pages • Static CSS files •
Most interactions trigger a page reload • Javascript is used only for UI interactions • Javascript is inlined inside the HTML code • Limited User Experience • Poor Developer Experience -
JS Javascript (1997) ECMAScript 5 (2009) ECMAScript 5.1 (2011) ES
2015 ES 2016 ES NEXT -
• Javascript generated HTML pages • Compiled CSS • The
page is never reloaded • Javascript is used for everything • Javascript files are compiled, minified and bundled • Improved User Experience • Rich Developer Experience -
<div> <h1 id="my-title"></h1> <p id="my-contents"></p> </div> <script type="text/javascript"> $(document).ready(() =>
{ $.ajax("my-url.php") .done((data) => { $("#my-title").text(data.title) $("#my-contents").text(data.contents) }) }) </script> JQUERY -
<div ng-app="app"> <my-page my-url="my-url.php"></my-page> </div> <script type="text/javascript"> angular.module("app", []).directive("myPage", function($http)
{ return { scope: { myUrl: "@"} template: `<div> <h1>{{myTitle}}</h1> <p>{{myContents}}</p> </div>` link: function(scope) { $http.get(scope.myUrl).success((data) => { scope.myTitle = data.title scope.myContents = data.contents }) } } }) </script> ANGULAR -
<div id="root" /> <script type="text/javascript"> class App extends React.Component {
componentWillMount() { axios.get(this.props.myUrl).then(({ title, contents }) => { this.setState({ title, contents }) }) } render() { return ( <div> <h1>{this.state.title}</h1> <p>{this.state.contents}</p> </div> ) } } ReactDOM.render( <App myUrl="my-url.php" />, document.getElementById("root") ) </script> REACT -
1997 2016 Documents Page based architectures View based architectures Component
based architectures -
PROS Maintained by Google Declarative syntax Encourage code maintainability Encourage
Components reusability Built-in utilities to facilitate Unit tests Play nice with distributed teams Rich ecosystem of ready-to-use components Huge number of developers available -
CONS Steep learning curve Complex scaffold Requires full control over
the web page Old framework (6+years) -
“You can think of a module as a container for
the different elements of your app.” -
A MODULE CAN BE The whole Application A single Component
A collection of Components and/or services -
function loadBeers($http) { return function (){ // load data from
remote source return $http.then( function dataReceived(result)) { return result.data } } } angular.module('myApp') .factory('loadBeers', loadBeers) SERVICE - FACTORY - PROVIDER -
–Angular Docs “Angular services are substitutable objects that are wired
together using dependency injection. You can use services to organize and share code across your app. Lazily instantiated – Angular only instantiates a service when an application component depends on it. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.” -
// JS function myCtrl($scope, loadBeers) { loadBeers().then( function beerLoaded(beers) {
$scope.beers = beers }) } angular.module(‘myApp') .controller('myCtrl', myCtrl) // HTML <body ng-app="myApp"> <div ng-controller="myCtrl"> <ul> <li ng-repeat="beer in beers track by $index”> {{beer}} </li> </ul> </div> </body> CONTROLLERS -
// JS function beer() { return { scope: { provider:
'=' }, restrict: 'E', // E = Element, A = Attribute templateUrl: 'beerTemplate.html' } } angular.module('myApp').directive('beer', beer) // beerTemplate.html <li>{{provider.name}} - {{provider.price}}€</li> // main-view.html <ul> <beer ng-repeat="beer in beers track by $index” provider="beer" ></beer> </ul> DIRECTIVES -
–Angular Docs “At a high level, directives are markers on
a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element or even transform the DOM element and its children.” -
// DOM <input id="toggleShowHide" type="checkbox"> <div id="status"></div> <div id="showText">Hello JQuery!</div>
// JS $(function() { function toggle() { var isChecked = $('#toggleShowHide').is(':checked') $('#status').text('Status: ' + isChecked) var specialParagraph = $('#showText') if (isChecked) { specialParagraph.show() } else { specialParagraph.hide() } } $(‘#toggleShowHide’).change( function() { toggle() }) toggle() }) ANGULAR VS JQUERY -
// DOM <body ng-init="showText = false"> <input ng-model="showText" type="checkbox" >
<div>Status: {{showText}}</div> <div ng-show="showText"> Hello Angular! </div> <body> ANGULAR VS JQUERY -
WORKWAVE GPS Grunt based project’s automation Component based Architecture Component
based routing Reactive data model (Rx.js) -
angular.module('wwLoaderLayer') .component('wwLoaderLayer', { template: ‘ww-loader-layer.html’, bindings: { showAtLoading: '@' },
controller($document, toggleLoaderLayer) { let modal let toggleLoaderLayerSubscriber const toggleLoaderLayerSignalReceived = (status) => { const action = status ? undefined : 'hide' modal.modal(action) } this.$onInit = () => { toggleLoaderLayerSubscriber = toggleLoaderLayer.subscribe(toggleLoaderLayerSignalReceived) } this.$postLink = () => { modal = $document.find('#loader-layer') } this.$onDestroy = () => { toggleLoaderLayerSubscriber.unsubscribe() } } }) ANGULAR COMPONENT -
RX.JS “An API for asynchronous programming with observable streams” [reactivex.io]
Can be used to implement Unilateral data flow architectures Offers powerful operators to create really complex async workflows Very steep learning curve -
– reactivex.io “ReactiveX is a combination of the best ideas
from the Observer pattern, the Iterator pattern, and functional programming” -
View User Interactions User Store A Store B Actions Web
API Web Socket Screen Stream Updated Data Pass Data To Store Store -
ANGULAR TIMELINE AngularJS was originally developed in 2009 by Misko
Hevery and Adam Abrons Misko Hevery started to work for Google in 2009 1st release of AngularJS: 1 developer, 3 weeks, 1000 loc AngularJS version 1.0 was released in 2012 by Google Angular version 2 was released in September 2016 after 2 years development -
ANGULAR FEATURES Optimized for both desktop and mobile Ahead of
Time (AoT) compilation Incredible performances Native Reactive support (Rx.js) -
import { Injectable } from `angular2/core`; @Injectable() export class MyService
{ constructor(private loadData:LoadData) {} getData() { return this.loadData.load(); } } @INJECTABLE -
import { Component } from '@angular/core'; @Component({ selector: 'hello', template:
'<p>Hello, {{name}}</p>' }) export class Hello { name: string; constructor() { this.name = 'World'; } } @COMPONENT -
import { Directive, HostListener } from '@angular/core'; @Directive({ selector: `[confirm]`
}) export class ConfirmDirective { @HostListener(`click`, [`$event`]) confirmFirst(event: Event) { return window.confirm( `Are you sure you want to do this?` ); } } // Usage <button type="button" (click)="visitOtherPage()" confirm>Visit another page</button> @DIRECTIVE -
import { Component } from '@angular/core'; @Component({ selector: `product-price`, template:
`<p>Price: {{ price | currency }}</p>` }) export class ProductPrice { price: number = 99.99; } @PIPES -
import {Injectable} from '@angular/core'; import {Http, Response} from '@angular/http'; import
{Observable} from 'rxjs'; import {Hero} from './hero'; @Injectable() export class LoadDataService { constructor(private http: Http) {} search(term: string): Observable<Hero[]> { return this.http .get(`app/heroes/?name=${term}`) .map((r: Response) => { return r.json().data as Hero[] }); } } HTTP SERVICE -
ANGULAR $DIGEST CYCLE AngularJS engine is built using a dirty
checking algorithm. Application state is a single entity connected to every visual component and calculated every time a component mutates some data It’s very easy to trigger unwanted $digest cycles impacting performances Very difficult to debug -
ANGULAR 2 CHANGE DETECTION Based on ngZone Recalculate the components
tree state after every async interaction (events, timers, observables..) Every component has its own Change Detector Component’s Change Detector is generated at runtime to improve performances Developers control how and when components are recalculated -
– ngBook2 “When one of the components change, no matter
where in the tree it is, a change detection pass is triggered for the whole tree, from top to bottom.” -
CHANGE DETECTION TRAVELS TOP TO BOTTOM CD CD CD CD
CD CD CD CD Change Detection Flow -
ANGULAR 2 CHANGE DETECTION Every component gets a change detector
responsible for checking the bindings defined in its template ChangeDetectionStrategy: - default: update the component every time data changes - onPush: update the component only when its inputs change or the component requests to be updated -
CHANGE DETECTION (ONPUSH) WITH IMMUTABLE DATA CD CD CD CD
CD CD Change Detection Flow -
ANGULAR 2 CONS Typescript as preferred syntax Built upon Rx.js
Very complex syntax -
PROS —Same pros of Angular— Maintained by Facebook Minimal API
Surface Area Very easy to learn -
CONS Is not a framework Developers must have a strong
knowledge of javascript automation tools Weird template syntax(at first glance) -
const Label = (props) => <h1>{props.children}</h1> const Icon = (props)
=> { return ( <i className="fa fa-anchor"> {props.label} </i> ) } const App = () => <div> <Label>Some label</Label> <Icon label="ready to sail" /> </div> STATELESS FUNCTIONAL COMPONENTS -
class Toggle extends React.Component { constructor(props) { super(props) this.state =
{ enabled: false } this.toggle = this.toggle.bind(this) } toggle() { this.setState({ enabled: !this.state.enabled }) } render() { const cls = this.state.enabled ?'btn-success':'btn-danger' return ( <button className={‘btn ‘ + cls} onClick={this.toggle}> {this.props.label} </button> ) } } STATEFUL COMPONENTS -
class MyComponent extends React.Component { // Component Initialization constructor(props) {}
// component ready to be mounted componentWillMount() {} // Props have changed componentWillReceiveProps(nextProps) {} // prevent rendering if not required shouldComponentUpdate(nextProps, nextState) {} // Prepare before rendering componentWillUpdate(nextProps, nextState) {} } COMPONENT LIFECYCLE -
class MyComponent extends React.Component { // create/update the component render()
{} // Component DOM it’s been created componentDidMount() {} // Component DOM it’s been updated componentDidUpdate(prevProps, prevState) {} // cleanup before component destruction componentWillUnmount() {} } COMPONENT LIFECYCLE -
– Marijn Haverbeke (eloquent javascript) “Higher-order functions allow us to
abstract over actions, not just values.” -
function applyVat(vat) { return (value) => ((vat + 100) /
100) * value } const applyVat22 = applyVat(22) console.log(applyVat22(100)) // print -> 122 function maybe(condition, action) { if (condition) { action() } } const action = (msg) => () => console.log(msg) maybe(true, action(`It works!`)) maybe(false, action(`Doesn't work!`)) // print -> It works! HOF -
const Wrapped = () => <h1>Wrapped Comp</h1> const wrapper =
(Comp) => () => { return <div><Comp /></div> } const FinalComponent = wrapper(Wrapped) const App = () => { return ( <div> <FinalComponent /> </div> ) } SIMPLE HOC -
WORKWAVE UNIFIED UI NodeJS based project’s automation Production bundle created
with Webpack Unilateral data flow with redux Async sequences with redux-saga Online documentation Live styleguide -
WORKWAVE UNIFIED UI Three projects: - Components library - Services
library - Unified UI -
WORKWAVE UNIFIED UI COMPONENTS LIBRARY Reusable independent components Themed Components
Ad-hoc Theme engine CSS in JS styling (runtime generated CSS classes) -
WORKWAVE UNIFIED UI Uses both library projects Support dynamic theming
Client-server communication via WebSocket WorkWave SSO