Wednesday, October 21, 2015

HTML5DevConf

I went to HTML5DevConf. Here are my notes:

ES6 for Everyone

JavaScript started in 1995.

ECMAScript version 3 came out in 1999. It was in IE6. It's what most people are used to.

for (var state in states) {
if (states.hasOwnProperty(state)) {
...
}
}

There were 10 years of sadness after that during which not much happened.

ECMAScript 5 came out in 2009. It was a minor improvement.

Object.keys()
Object.create()
Array.forEach()

Then, HTML5 started happening.

Object.keys(states).forEach(function(state) {
...
});

Babel is a tool that compiles ES6 code to ES5 code.

Only 10 people in the room were using it in production.

Here is some ES6 code:

let states = {...};
Object.keys(states)
.forEach(state => console.log(state));

ES6 is mostly syntactic sugar.

To use it, you must have Chrome, Edge, or Babel.

Default parameters:

... = function(height = 50) {
....
}

Previously, you had to do:

... = function(height) {
height = height || 50;
...
}

Template literals (back ticks):

var name = `${first} ${last}`;

var x = `
I have a wonderful
block of text here
`;

Destructuring:

Grab the house and mouse properties from the thing on the right:

var { house, mouse } = $('body').data();

If those properties aren't defined, you just get undefined.

He's not covering let and const.

Grab the middleware property from the my-module module:

var { middleware } = require('my-module');

It works with arrays too:

var [column1, column2] = $('.column');

Skip a column using multiple commas:

var [line1, line2, line3,, line5] = contents;

How do you get started with ES6?

  • Babel converts ES6 to ES5.
  • Webpack takes your JS modules and combines them into a single file.

Arrow functions.

Old way:

var greetings = people.filter(function(person) {
return person.age > 18;
}).map(function(person) {
return "Hello " + person.name;
});

New way:

var greetings = people
.filter(person => person.age > 18)
.map(person => "Hello " + person.name);

If you have more than one line, you can add brackets, but that gets rid of the implicit return statement.

Arrow functions deal with "this" better.

You don't have to do things like:

var self = this;

Arrow functions implicitly bind "this".

$.get("/awesome/api", data => {
this.doSomethingWith(data);
});

Be careful of jQuery because jQuery will hijack "this".

Use parenthesis if you have more than one argument.

() => console.log("hi");

(person) => person.name;

person => person.name;

(one, two) => {
return three * four;
};

An IEFE:

(x => console.log(x))("hey");

All of the above are the simplest, most useful features of ES6.

He's not going to cover classes today. He thinks that they don't add enough value.

Promises:

$.get(`/people/`${id}`).then((person) => {
...
}).catch(function() {
console.log(...);
})

This standardizes promises because everyone had their own version.

Only two things are important:

  1. .then
  2. .catch

Errors in the "then" also end up in the catch which is really helpful.

Use Promise.resolve to convert jQuery promises to ES6 promises.

The history of modules in JavaScript:

First, we used closures.

var module = (function($) {
...
return ...;
})(jQuery);

Then, AMD:

define(['jquery'], function($) {
...
});

Then CommonJS (which is a good place to start):

var $ = require('jquery');

var x, y, z;
module.exports = $.doSomething();

ES6 modules:

import $ from 'jquery';

var x, y, z;
export default $.doSomething();

// More examples:
export var age= 32;

export function printName() {
...
};

// In another file:
import { age, printName } from 'my-module';

He still didn't cover a ton of stuff. Babel has a nice tutorial on all the new features.

Reusable Dataviz with React and D3.js

@swizec

http://swizec.com/html5devconf

He showed how to implement a Space Invaders game using React and D3. Very clever!

The problem: Spreadsheets don't scale. Simple libs aren't customizable. D3 is hard.

React principles:

  • Components
  • Immutability
  • Just re-render

Solution: change the data and redraw. This is how a video game works.

Flux is an architecture, not a library.

Only 1 person in the audience admitted to using Emacs. Crazy.

You can use React to build SVG, not just HTML.

Just update the model and let React deal with it.

React gives you hot reloading.

Use D3 more for the math and less for the SVG.

He thinks that React may be better than Angular because of the diffing algorithm (and virtual DOM). Angular also makes it harder to move things around because of the nesting and scopes.

He strongly recommends using Flux with React.

React--Not Just Hype!

@mjackson

@ReactJSTraining

He is the primary author of react-router.

He also works on Redux.

He gave many compelling arguments and examples of how React has an advantage over Angular and Ember.

React has historically had better performance than Ember and Angular.

"It's amazing what you can do with the right abstraction."

He wrote the JS implementation of MustacheJS.

In Angular, you can put things in scope in the controller, rootScope, directive, somewhere else in the view, etc. If you see a variable in the template, it's hard to know where it's coming from.

He showed a nice side-by-side example of Angular and React.

It's easier to drive things from the JS (in React) than from the template (in Angular).

<div ng-repeat="model in collection">
{{model.name}}
</div>

vs.

collection.map(model => (
React.createElement('div', null, model.name)
))

or:

collection.map(model => (
<div>{model.name}</div>
))

Angular has to keep inventing new DSL syntax for the templating language to implement new features. In React, you just have JavaScript.

He's done a lot of work in both models. He just thinks the React model is better.

Scoping in Angular is complex. Scoping in React is just JavaScript scoping.

In general, it's better to be in JavaScript than to keep on adding stuff to Angular's templating DSL.

MDN's docs are pretty good for JavaScript documentation.

React lets you "describe UI". It doesn't have to render to just HTML. It can render to other things as well, for instance SVG, Canvas, three.js (WebGL), Blessed (terminal), etc.

Netflix uses React to render to TVs.

Decouple from the DOM. Describe the UI and render wherever it makes sense.

This is the same thinking that underlies React Native.

He poked at Ember a bit.

With Ember, it's complex to understand the side effects of setting a property on an object.

If you're setting two properties, it might end up executing the same block of code twice. You can't batch the changes.

He doesn't like Object.observe. He says it makes it hard to know what's going to happen when you make changes to state.

Two important questions:

  1. What state is there?
  2. When does it change?

He likes setState more than the KVO paradigm (i.e. Object.observe).

setState:

  • One object contains state.
  • Imperative, intent is obvious.
  • Easy to grep.

React inserts a virtual DOM between the view logic and the DOM.

This lets you delegate a lot of responsibilities to the framework. The framework can handle a lot of optimizations. You can also introduce new render targets.

Most tech companies have web, iOS, and Android teams that are all mostly separate.

He recommends structuring teams around feature verticals instead of technologies.

He gave a plus for React Native.

Architecting Modern JavaScript Applications

He's one of the Meteor developers.

Meteor is a full stack framework. In encompasses both the frontend and the backend. It's really quite impressive what it can do and how far ahead of other stacks it really is.

He wants to talk about the "connected client" architecture.

He used UBER as an example. You can look at a map and watch all the cars move around in realtime.

Move from websites to apps.

The main driver for this is mobile.

Apps:

  • Stateful: There's a stateful server with a connection to the client (WebSockets or XHRs)
  • Publish / subscribe
  • Data: What goes over the wire is data, not presentation

He has mentioned multiple times that the server needs to be able to push data to the client.

The architecture for these modern apps is really different.

We've seen major shifts in how software is built before:

Mainframe => PC => Web => Connected client

Connected client:

  • Stateful clients and servers with a persistent network connections (WebSockets) and data cached on the client.
  • Reactive architecture where data is pushed to clients in real time.
  • There's code running on the client and in the cloud. The app spans the network.

You need to cache things on the client in order to get any kind of performance. Hence, the server needs to know what's on the clients.

You have to be able to push code changes.

We have to move away from stateless, share nothing, horizontally scalable architectures.

Each part should "reactively" react to changes in state.

You have to have the same team working on a feature on the client and on the server.

However, you can still have separate teams for separate microservices.

"JavaScript is the only reasonable language for cross-platform app development."

That's because it runs everywhere you need it to run.

He says JavaScript is better than cross-compiling from languages like Java.

He gave a plug for ES 2015.

You can transition to ES 2015 gradually.

He likes ES 2015 classes.

He showed how ES 2015 code made the code much nicer and shorter.

Sass seems to be more popular than Less.

He talked about Reactivity.

He wants more than what Angular or React can provide. He wants reactivity across the whole stack.

With Meteor, you can be notified of changes in your datastore so that you can update your UI. (That's impressive. I've seen the Android guys do that, and the Firebase guys do that, but I haven't seen many other people do it.)

He's very pro-WebSockets. Use an XHR if they're not available.

He doesn't use REST. You publish/subscribe with live data.

He talked about Facebook's Relay Store, GraphQL, etc.

DevOps is different when you have connected clients.

He talked about something called Galaxy.

You need stable sessions. I.e. when a client reconnects, they must reconnect to the same server.

He talked about reactive architectures for container orchestration.

He plugged Kubernetes and Marathon (Mesos).

You have to update the version of the software on the client and the server at the same time.

He showed how he dealt with deploying new versions of the software. It's complicated.

Meteor is an open-source connected client platform. It simplifies a ton of stuff.

Building Web Sites that Work Everywhere

Doris Chen @doristchen from Microsoft.

She is going to talk about polyfills and Modernizer.

Edge is the default browser in Windows 10.

Edge removes as much IE-specific code as possible and implements as much support for cross-browser stuff as possible.

Testing tools:

  • Site Scan: Free
  • Browser screenshots: Free
  • Windows virtual machines: dev.modern.ie/tools/vms/windows
  • BrowserStack: Paid

http://dev.modern.ie/tools is Edge's developer site. It's pretty neat. It gives you a bunch of warnings for when you're doing things that don't have cross-browser support.

She keeps skipping Chrome in a lot of her slides ;)

I think she said stuff for CSS3 needs prefixing.

Autoprefixer is a postprocessor that automatically adds CSS prefixes as necessary.

You can integrate this using Grunt.

Browser detection (using the version string to decide what your code should do) just doesn't work.

All the browsers have User Agent strings that mimic each other. They embed substrings of the other browsers.

Instead use feature detection.

IE browser detection is going to be broken in Edge since it doesn't support the older IE ways of doing things.

Modernizr is the best tool to use for feature detection.

It also has polyfills to keep older browsers supported.

Edge's dev tools are called F12 Tools.

She talked about polyfills.

MP3 is supported in all the browsers.

H.264 (MPEG-4) is supported in all the browsers.

Browsers won't render elements they don't understand (such as video tags), but they will fallback to rendering the stuff inside the tag.

She called Silverlight "legacy", and said people should move away from using any plugins.

She disables Flash as well as all other plugins.

She talked about using Fiddler to modify requests and responses.

She used it to manually change some Flash video to HTML5 video by looking at the MP4 the Flash code was playing (it was an argument to the Flash player).

Edge has an emulation mode to emulate older versions of IE.

Evolution of JavaScript

The story of how the "glue of the internet" became the world's most popular programming language.

His view of the history of JavaScript was, unfortunately, somewhat flawed...Actually, it was very, very flawed.

I left early along with some other people.

WebGL: The Next Generation

Tony Parisi.

http://tonyparisi.com

WebGL is everywhere. It runs generally the same everywhere.

It started in 2006 at Mozilla.

It's OpenGL but built to work the way the web works.

It has very low-level drawing primitives.

No file format, no markup language, no DOM.

Libraries and frameworks are key to ramping up quickly and being productive.

If you use the base API, it takes a 300 line program to make a cube that spins in space with an image on each face.

three.js is the most popular WebGL library. It's very well done.

WebGL 2 is a major upgrade based on OpenGL ES 3.0. It was introduced earlier this year.

Unity can cross-compile from C++ to JavaScript using Emscripten.

WebGL 2 has lots of features that allow you to get low-level efficiency gains.

It has deferred rendering. It enables you to have tons of light sources.

WebVR is virtual reality in the browser.

The world of VR is moving very quickly.

Firefox and Chrome have VR working in the browser.

Head tracking is part of VR.

So is stereo view mode.

Firefox and Chrome can attach to VR devices.

You have to update the head tracking position at 70-90 Hz to avoid motion sickness.

HMD = head mounted display

He talked about Google Cardboard. It's not as good as the professional stuff, but it's still pretty neat.

Browsers have an accelerometer API.

glTF is a web-friendly 3D file format for use with WebGL. It's a "JPEG for 3D".

He wrote the glTF loader for three.js.

FBX is a fairly standard proprietary format. There's an FBX to glTF converter.

He wrote "Learning Virtual Reality" along with two other O'Reilly books related to WebGL, etc.

He has an Oculus Rift DK2 headset. You can buy it on their website.

Firebase: Makes IoT Prototyping Fun

This was one of my favorite talks because it was so simple and yet so inspiring.

Jenny Tong @MimmingCodes

She gave a brief intro to some simple EE topics.

0V = ground

PWM = pulse width modulation

10k ohm resistors are the only resistors you need to worry about right now.

The longer foot of an LED goes to high voltage, and the other foot goes to ground.

She's working with voltages in the range of 0 to 5.

Arduino Unos are simple, durable, and inexpensive. Keep in mind there is no OS. Your code runs directly on the metal.

A Raspberry Pi is a tiny computer. It usually runs Linux.

Instead of doing things mostly in hardware or in C, she tries to make it so you can do things in JavaScript.

Her standard recipe is:

  • Arduino Uno
  • Johnny-Five: a NodeJS library for interacting with hardware stuff
  • Raspberry Pi (or laptop): for talking to the internet
  • Firebase (she's a developer advocate for Google Cloud)

Johnny-Five is very versatile and has great documentation. It has images that walk you through various projects.

Firebase has a realtime database. You can think of it as a giant ball of JSON in the sky. You can create a listener in your JavaScript code to listen for changes to the database.

http://wherebus.firebaseapp.com is a cool example.

The "hello world" of IoT is creating a button that changes something on the Internet. During her talk, she created a button that controlled a real light. The light responded to changes in the data in her Firebase database.

Arduino has a bridge called Firmata that can be used to connect Johnny-Five to your Arduino.

She started wiring things together using a breadboard:

Red = high
Brown = low

She started with some JavaScript to make an LED blink.

A pull down resister (10k ohm) connected to ground gives the electrons a place to go when the circuit would otherwise be open (i.e. not connected).

She integrated Firebase really quickly.

You can use APPNAME.firebaseio-demo.com/TABLE as a Firebase DB without even signing up. However, keep in mind that so can everyone else.

You can go to the Firebase URL to get a web view of the data. Change the data there, and it gets pushed into the JavaScript code, which controls the board.

It's really easy to prototype cool things with real hardware, JavaScript, and Internet connectivity.

When you are learning how to build this stuff, these things will catch on fire sometimes. That's okay. Keep a fire extinguisher on hand ;)

mimming.com/presos/internet-of-nodebots
github.com/mimming/snippets

You can buy a bunch of cool hardware from Adafruit.

Upgrade your JavaScript to ES2015

David Greenspan (Meteor Development Group).

The speaker takes a very conservative approach to new browser features. In the talk, he gave an overview of whether using ECMAScript5 features via transpiling with Babel is a prudent thing to do.

He started in 2007 with IE 6 (Firefox 1.5, Safari 2, no Chrome).

Meteor dropped IE 6 in 2013.

IE 7 still couldn't garbage-collect cycles between JavaScript and the DOM. [I remember that. I sure am glad they fixed that!]

You can enjoy ECMAScript 2015 because of Babel which is a transpiler.

ECMAScript3 -- 1999 -- IE 8-9
ECMAScript4 -- cancelled in 2008
ECMAScript5 -- 2009 -- IE 9, "modern" browsers -- just a minor update
ECMAScript6 -- 2015 -- being implemented now (aka ECMAScript 2015)

They're going to start rolling new versions annually.

Features will appear quickly in new browsers.

In 0-2 years, we'll stop caring about IE 8.

When people say "ES", they're just using it as an abbreviation for "EcmaScript".

Start using ES 2015 and transpile to ES 5 using Babel.

Babel targets ES 5. You can even get it to transpile to ES 3 if you build the right plugins.

Babel can get you a lot of the newer syntax features.

However, it can't provide all of the "engine-level" features such as efficient typed arrays, Proxy, Reflect, WeakMap, WeakSet, and proper tail call optimization.

Babel can do generators, but it's a tricky transform.

All sophisticated JS apps have a build step of some sort these days, so requiring a build step is nothing new.

Readability / debuggability of generated code isn't bad, especially with source maps.

Even just a year ago, the transpilers weren't that great. Babel has kind of won the war.

Babel is ready for production. However, you do have to follow some guidelines:

  • Use "loose" mode. It's the fastest, and it makes the best trade-offs.
  • Avoid "high-compliancy" mode.
  • Don't go nuts with experimental (ES7+) transforms.
  • Whitelist your transforms.
  • Use external helpers.
  • If you need IE 8 support, you'll need custom helpers.
Here's an ES6 class:

class TextView extends View {
constructor(text) {
super();
this.text = text;
}

render() {
return super.renderText('foo');
}
}

It's just nice syntactic sugar for what you'd do anyway.

Classes are very controversial in JavaScript. However, he said that there is no significant reason not to use classes.

Arrow functions:

[1, 2, 3].map(x => x*x)

['a', 'b', 'c'].forEach((letter, i) => {
this.put(i, letter);
});

setTimeout(() => {
this.foo();
}, 1000);

"this" refers to the same thing inside and outside the function. It's not broken for nested functions.

Use arrow functions.

Block-scoped variable declarations: let and const

The difference between let and var is that var is function scoped, but let is block scoped.

const is like final. It just says that the variable can't be reassigned. That doesn't mean that the thing the const points to isn't mutable.

Switch from var to let and const. Default to using const.

Imports:

import {foo, bar} from "mymodule";

export function logFoo() {
...
}

It transpiles to CommonJS.

By using transpilers, we'll always be able to try out new features before they're completely set in stone. We get the features early, and the standards bodies get some feedback on their designs. It's a win win.

Use Babel and ECMAScript 2015 today.

However, don't use engine-level features like generators, Proxy, Reflect, etc. yet.

The latest Chrome supports a lot (but not all of) ES 2015.

Proper tail call optimization is not implemented in any of the browsers yet.

ES7 and Beyond!

Jeremy Fairbank @elpapapollo

TC39 is the group responsible for the standard.

He uses React a lot.

ES6 was only standardized this year, and there's already more stuff coming down the pipeline.

Some proposed features might be coming after ES7. They call this "ES.later".

You can use those features now using Babel.

He went over what features were at what level of standardization. I didn't get a chance to write down the exact meaning of each of the stages, but the smaller the stage number, the closer it is to being in the standard.

Remember, nothing in this talk has been fully standardized yet.

At stage 1:

Decorators:

class Person {
@enumerable
get fullName() {
...
}
}

function enumerable(target, name, descriptor) {
descriptor.enumerable = true;
return descriptor;
}

Decorators can take arguments.

Decorators can work on classes as well. You can use this to create a mixin @decorator.

At stage 2:

Object rest and spread.

// Rest
const obj = { a: 42, b: 'foo', c: 5, d: 'bar' };

// Save the "a" and "b" attributes into the variables named
// "a" and "b", and save the rest of the attributes into an
// object named "rest".
const { a, b, ...rest } = obj;

// Spread
const obj = { x: 42, y: 100 };

// Add all of the attributes from obj inline into the current
// object. In "obj" has a "z" attribute, it'll override the
// earlier "z".
const newObj = { z: 5, ...obj };

// If "obj" has an "x" attribute, it'll be overriden by the
// "x" that comes after it.
const otherObj = { ...obj, x: 13 };

These are both just transpiled to Object.assign.

Here's a nice example of their use:

function createDog(options) {
const defaults = { a: "Some default", b: "Some default" };

return { ...defaults, ...options };
}

Be careful, this is not a deep clone.

At stage 3:

Async functions. These provide synchronous-like syntax for asynchronous code.

Prepend the function with "async". Use the "await" operator on a promise to obtain a fulfilled promise value.

async function fetchCustomerNameForOrder(orderId) {
let order, customer;

try {
order = await fetchOrder(orderId);

} catch(err) {
logError(err);
throw err;
}

try {
customer = await fetchCustomer(order.customerId);
return customer.name;
} catch(err) {
logError(err);
throw err;
}
}

Await awaits a promise and obtains the fulfilled value. It's non-blocking under the covers.

It takes a lot of work to transpile async / await code into ES5 code.

Babel has a REPL that you can use to see how it transpiles things.

Here's how to make requests in parallel:

const orders = await Promise.all(
orderIds.map(id => fetchOrder(id))
);

You should prefer making a bunch of requests in parallel rather than making them sequentially.

Sometimes you have to do things sequentially because of the business logic. You have to get one thing before you know what the next thing you need is.

Async functions let you use the language's native flow control constructs like for...of, try/catch. The problem with promises is that you can't easily use things like try/catch.

There are many other upcoming features in various stages:

SIMD: single instruction, multiple data.

Array.prototype.includes

Object.observe

See: https://github.com/tc39/ecma262

To get every possible crazy feature, use babel --stage 0 myAwesomeES7code.js. However, keep in mind that if the standard goes in a different direction, your code is going to break.

http://speakerdeck.com/jfairbank/html5devconf-es7-and-beyond

No comments: