These are my notes from the workshops and sessions I attended while at Connect.Tech.

Progressive Web Apps from Scratch

by @JoubranJad

I decided to attend this as I thought this workshop will not require me to install additional tooling. Boy, was I wrong! The first slide shown had this instructions:

npm install -g surge preact-cli

Surge is a quick way to deploy static web apps while Preact claims to be an alternative to React that’s closer to the metal. While these tools sounds awesome, I don’t foresee myself using them! I wish I had setup my ubuntu box and did all the workshop material there. sigh

(btw, I like how the instructor gave away red stickies so you could place them in front of your laptop if you need assistance while going thru the exercises. Then he could easily scan the room and approach those that need help… how clever!)

Web App Manifest

Web app manifest is a JSON file that provides information about an application (such as name, author, icons and description). It could be linked at the head of a page as follows:

<head>
<link rel="manifest" href="manifest.json">
</head>

Here is a sample of a page manifest:

{
  "name": "libsgarcia.rocks",
  "short_name": "libsgarcia.rocks",
  "start_url": ".",
  "display": "standalone",
  "background_color": "#fff",
  "description": "a log of my learnings and goals",
  "icons": [{
    "src": "images/touch/homescreen48.png",
    "sizes": "48x48",
    "type": "image/png"
  }]
}

tip: Use realfavicongenerator.net in generating favicons to maximize browser support!

First Paint

  • inline critical css
  • unblock critical js, by use of async keyword. This does not guarantee load order, so if you need a script to be executed after doc has been parsed but before firing DOMContentLoaded, set defer execution.
<script async src="app.js"></script>

Service Worker

  • Code Splitting

Performance for PWA

  • Source Map Explorer - analyze and debug javascript bloat
  • Bundle Visualizer - from webpack
  • Chrome devtools
    • show coverage
    • performance tab: CPU throttling
  • Lighthouse - comes with Chrome DevTools now (Audits tab)

Javascript Fundamentals For ReactJS

by Chris Aquino

What’s great about Connect.Tech is that they have tracks by Framework and this year React has two tracks (1) for beginner and (2) for advanced. I might as well stay at Room 105 and learn about React all through out the conference.

Wordpress divorcing from React over Facebook patent issues

Inferno Vue Preact

demystify

  • Functional, declarative views
  • Virtual DOM
  • One-way data flow
  • Component Architecture
  • Immutable data structures

Learn once, write anywhere - Javascript for the web and server

Five buckets

Functions - main unit of abstraction.

f(d) = v

View should render the same given the same data. - Tyler McGinnis

  • Arrow functions could be assigned to Constants
  • If only one statement and its only a return statement, you can omit {} curly braces. If return statement is long, then it could be in () parenthesis.
  • Interpolated strings (templating) by using a backticks `. Supply default values instead of urnary operator.
const Readout = (value = 0) => (
  `${value.toFixed(2)} degrees F`;
);
  • Ternary operators are really popular in React
const Readout = (formatterFn, value = 0) => (
   typeof formatterFn === 'function' ? formatterFn(value) : value;
);

JSX is not HTML; it gets transformed into JS

const TemperaturePanel = ({data}) => (
	<div className='panel'>
		<Readout>
        </Readout>
    </div>
)

Not required to use JSX but it is declarative and easier to understand. Knowing what the UI is going to look like is more productive.

  • XML description of nested function calls
  • Transformed by the React Library into functional calls
  • Declarative - resembles the resulting UI/HTML
  • Can be HTML elements or custom components
  • JSX looks like XML but jsut functions
  • functions provide UI components
  • Get used to ternary (if/else)
  • default values are your best friend
  • const + arrow functions are idiomatic - more protection/safety so it cant be reassigned.

Object

JSX produces a huge JSON object called element trees, description of how HTML should be presented in the browser. If a value is the same, JSX will only update the affected

  • type
  • props

JSX renders to an Object

  • JSX gets converted to React.createElement
  • React.createElement returns a plain JS object
  • That object is descirption of the UI inclduing the data
  • The UI only shows data that is passed down as a prop starting at the top of the element tree. One way data flow Virtual DOM - state of the DOM
  • plain object that represents the state of the DOM
  • results from nested calls to react.createElement
  • Data can only come from props (arguments to react.createElement)
  • new data (new args) cause new version of virtual dom to be calculated. React chooses the most optimized way of refreshing data.

react dev tools - extension in Chrome.

Classes

  • callback pattern - return to Sender

Synthetic events

  • Handlers for events are received as props
  • Have names like onClick, onChange, etc
  • Could be inline anonymous, or another function. React takes care of proper native handler by element.

components can be extended, with constructor and render

  • Controlled components
  • Values come only from props udpates their values direclty are passed callback functions as props When you need to save state between rendes Define state change methods, pass methods as props State change methods
  • extending react component: mounting, updating, unmount, misc (setState, foceUpdate)
  • used sparingly

Modules

export default

import {Component} from React - a way to pluck out components from a module * keep components organized * one js per component * keep assorted

Immutables

  • Immutable.js - prevents you from updating data
  • componentShouldUpdate
  • safer
  • performances

Use object.assign similar to jQuery returns single object with properties of multiple objects rightmost object takes precedence.

Array.concat - combine two arrays creating a new array

Object spread {….object Array spread […array,

Funational array method map reduce filter

Pitmaster - Dashboard for RealTime barbeque cooking

slides

Strategies for learning React

Why React? It’s mostly Javascript! It’s true that learning React can be overwhelming. In fact Learning ANYTHING can be overwhelming, so a few tips:

  1. Start small with clear goals
  2. Obtain feedback quickly
  3. Have fun

Learn the terminology

npm install -g create-react-app
npm start

Components - reusable parts of an application JSX - syntax extension to javascript, looks lke a template language with full power of js.

setState - can also take a function (react batches function calls and optimizes if duplicated)

setState((prevState, props)=>{
	count: prevState + 1
})

Separation of Concerns

Presentational vs Container Presentational - style Container - responsible for logic and state

example: EmployeeContainer vs EmployeeView

NPM vs Yarn

both target the same npm registries

Redux

Redux is a state management library that helps you push state out of your components. When to add? When yo need o share a lot of state between componets and using container

Babel

allows use of modern JS / ES features

WebPack

a module bundler that creates a dependency graph overkill for Hello World app

Flow/Typescript

  • provides types to JS
  • Flow is written by Facebook
  • not require for react but provides safety
  • replaces Babel

Immutable

  • one way data flow

GraphQL

a query language to interact with an API

Testing

  • Jest - test runner
  • Enzyme - test React components

StoryBook

a UI development environment for UI components

React Router

provides routing capabilities

What about CSS

@ryanlancioux

Get Started with Redux

by Jeremy Fairbank @elpapapollo github:jfairbank

hi@testdouble.com - software is broken, we are here to fix it.

Problem of managing state

MVC spreads state in the models, two way data binding. State is everywhere and anyone can change it

How does it work?

Redux - predictable state cotainer. It consolidates state management so it’s predictable.

reducer - a function that defines how state can change in our app. state changes in one place, well defined, changes are serialized.

FLOW: State => View => Actions => Reducer

State - data View - React, Angular, Kendo UI Action - dispatched by View Reducer - operations that can be performed on a state and responsible for changing state.

import { createStore } from 'redux';
const store = createStore (reducer, 0);

store.dispatch({ type: 'DECREMENT' });
store.subscribe(() => { counter.innerText = store.getState(); });

Problems:

  • Creating actions are cumbersome. create functions that wraps dispatch
  • Requires direct access to store. automatically dispatched when invoked. Bound action creators with two arguments.

How does this fit into React

Redux + React Library - React Bindings for Redux

State => reactRedux => React => Actions => Reducer

props will be used for binding action creators

Immutability

create new object out of old before changing object spread object.assign

const initialState = {
	counter: 0, 
	car: {
		color: 'red'
	}
}

What to do if Reducer becomes very huge?

Reducer composition - create modular reducer for better organization of reducer (a root reducer that points to smaller reducers)

combineReducers from redux;

Middleware

sits between actions and reducer

Enhance Redux applications Logging Debugging API interaction

  • Redux Saga - uses ES6 generators functions, writes async
  • redux observables - RxJs Observables - writes async code with declarative observable chains
  • plenty other options: redux logic, redux ship, redux promise, redux-api-middleware

Testing

  • easy reducer unit testers
  • you can test action creators but not necessary
  • you should test async action creators
  • use mocks (plug for testdouble)

Resources

slides

Energizing your Development Flow with CLI

by Abraham Williams and Pearl Latteier

  • Terminal
  • Chatbot
  • IoT button

Familiar CLI’s such as git init, ng new, gulp watch

  • repetitive
  • time-consuming
  • error prone
  • complex

Levels of CLIness

  1. Run third party CLIs (e.g. firebase deploy, ionic generate)
  2. custom npm scripts
  3. custom npm scripts to run js files
  4. custom namespaced CLI

CLI’s should have a few primary commands

4 ubiquitious commands/tasks

  • setup - this can be time consuming (i.e. new developer on-boarding should be complete in one hour). instead of reading a README, create a CLI
    • validate environmet
    • install dependencies
    • install app
    • configure
npm run <script>

{
  "scripts": {
     "setup": "brew ...",
     "build": "webpack", 
     "watch": "npm run build --watch", 
     "serve": "npm run build & npm run"
  }
}

&& - sequential & - background / parallel

define strings to be run on command line, saves keystrokes, indicate purpose, encourage consistency

  • serve -

    • build
    • watch
    • serve
  • test - new devs should have green test in one hour. Unit, E2E, Linting make use of pre and post prefixes pre* ( prepublish, preinstall, pretest ) post* ( postpublish, postinstall, posttest )

  • deploy - anytime you have a checklist, turn it into a command. New developer should deploy on day one. Process should be as easy and painless as possible. No special knowledge is required. build will generate a distribution build for the app, upload will load distribute ready app to a server somewhere, and start will run commands so that app is available to use.

IoT - use a serverless cloud thing

Take-aways

A few primary commands that build up from smaller commands New developers can onboard in an hour New developer can deploy in day one

Resources

[slides](http://slides.today]

React and GraphQL with Apollo

by Patrick Eisenmann @peisenmann

GraphQL

  • Single endpoint
  • Discoverable quearies and mutations - not endpoints
  • self- documenting
  • basic testing can be automated
  • regressions due to schema changes are easily detectable.
  • introspectable

Terminologies:

  • Schema Query - comparable to GET Mutation - comaprable to PUT/POST/etc. Resolver - extracts data for a given GraphQL property fronm an entity.

Basics of GraphQL

  • Query (you can see operations, parameters, return values)
  • Mutation
  • Subscription (specific to Apollo)

Tooling

  • GraphiQL app
  • GraphiQL component
  • Webstorm has an extension for GraphQL
  • Apollo dev tools (Chrome dev tools)

Boilerplate: githunt

Queries and Mutations

  • .graphql file or gql tagged template strings
  • http://graphql.org/learn
  • REST GET => GraphQL queries
  • REST POST/PUT/DELETE => GraphQL mutations
query CurrentUserForLayout {
  currentUser {
    name,
    url
  }
}

tip: inline GraphQL using gql and backtick

use fragments to reuse a query

GraphQL Higher Order Component

  • Takes a query or mutation
  • as either: ftunction that wraps the component or decorator???

Role of Redux *still useful for shared app state * used internally b applo * Components reredner when he apollo cace chanes just like norma redux

*** Use proper ids for caching - check properties of record to return

optimistic updates

  • pretend you received success instantly

Introspection

  • Programmatically inspect the API
  • Possible to automatically test
  • Ability to augment queries

Lessons / Caveats

  • avoid multiple mutations on a component as it leads to annoying DOM bloat.
  • multi-query chaining: sometimes its needed to power a component. BUT order might be important. (i.e second query needs data from first)

Data Modelling Best Practices

  • favor normalized data to reduce redundant network traffic & work on the server but this can increase UI effort to create relationships
  • strong unique IDs (guid)
  • properly marked required fields
  • craft mutation response queries to update the cache

take-aways

  • GraphQL is so much easier to consume
  • typed and self documenting
  • solid tooling

Non-trivial Pursuits Learning Machines and forgetful humans

by Chris Heilmann (@codepo8)

aka.ms/connect-tech

Overwhelming

Given the pace of technology, I propose we leave math to the machines and go play outside

Ethic of Machine Learning - Big brother is watching you??

We live in a post-data leak world. We have been recorded and categorised.

How do we remember and learn?

How does learning get easier?

  • Repetition
  • Comparison
  • Explanation
  • Association

Humans are weird creatures, we are capable of complex and erratic leaps of understanding. But we are terrible at repetition - as we get bored. We are also rubbish at additions explanations and naming things. As it is boring.

We are easily overwhelmed looking at large tasks and big amounts of data.

Computers excel at repetitio and plough through in ms through oodles of data.

Our job is to make sure that the data is understood correctly.

That the returned data is fit for human consumption

Where do i find a nice restaurant around that is open tomorrow around lunch time?

computers are great at Repetition and Comparison, while humans are great at explanation and association.

Visual Recognition - automatic tagging

Test-Driven Development with React

by Van Wilson @vanwilson

Process

  • Write a test for the next bit of functionality you want to add
  • write the functional code until the test passes
  • Refactor both new and old code to make it well structured

This is one of the principles of Agile Software development: Make it work , Make it right, Make it fast

Testing Pyramid

  • Unit Tests - should have lots of these [class, interface, etc]
  • Integration Test - Component level testing [UI, database, API, class]
  • Functional Test - (written in conjunction with QA team)

Anatomy of a Test

  • Given - setup the environment
  • When - act on the system under test (SUT) in that environment
  • Then - test what happens

**Getting started with any testing really is the hardest part. **

Jest

Jest

  • Based on Jasmine
  • Built-in asertions
  • Built-in spies
  • Built for React

Learning and Using RxJs

by @ladyleet

  • How to create an observable - Observable.fromEvent,Observable.to, Observable.from
  • Subjects are observables and observers
  • $ denotes an observable Dont import the entire library
import { Subject } from 'rxjs/Subject';

her slide animations are dizzying!!!

  • reactivex.io/rxjs

Extending Cloud Intelligence to IoT evices with Node.js

by Kristin Ottofy @kristinottofy kristin.ottofy@microsoft.com

Azure red shirt tour coming to atlanta Scott Guthrie - October 18th, Center Stage Theater 8am-2pm

Cross-Platform Desktop Apps with Electron

by David Neal

Pros:

  • HTML + CSS + JS
  • Node.Js + Chromium
  • Not your Dad’s javascript

Cons: * HTML + CSS + JS

Created by Github for Atom Formerly Atom Shell Active since 12014 1.0 release May 2016 Current version 1.7.6 August 9th

Features

  • Rapid Development
  • Themes
  • Shared UI/code
  • Deployment + ‘silent’ updates - built in with Electron framework
  • Native UX (usability extensions)

Why Deskop Apps

  • Offline
  • Printers, devices and ther local hardware
  • On-premises
  • Internal, Line of Business Apps
  • Edit Local files
  • App Store
  • Kiosk
  • Desktop > Intranet app
  • Sometimes it just feels right - sometimes a desktop app is the right way

Disconnected data entry, editor, time management, media player, email client, messaging, collaboration, kiosk, mapping, route planner,

Example: Atom, Slack, Visual Studio Code, Postman (Chrome Web Extensions), Nylas Mail (mail client), Jibo (Alexa type robot)

Get Started

npm install electron
touch main.js
touch index.html

main process, renderer { home.html, editor.html, etc. }

const electron = require ("electron");
const app = electron.app;

app.on('ready', () => {
	mainWindow = new BrowserWindow();
	mainWindow.loadURL('file://${ __dirName }/index.html');
});

> electron main.js

use ES2015, latest version of V8. And since this is Chromium, we can use Chrome Dev Tools.

Hard Problems

  • Cache Invalidation
  • Naming Things
  • off by one errors
  • Choosing the perfect animated gifs - check his github repo

Process Modules

  • app (app lifecycle events, system path)
  • ipc (interprocess communications, pub-sub)
  • dialog (native UI for prompts save, printer dialog)
  • menu, menu-item
  • power-monitor - determine whether on battery, or on power - interrupts events [i.e prevent screensaver]
  • tray (bubble popups)

Render modules

  • ipc (sending messages back to main process
  • remote (invoking functions in the mainframe
  • web-frame (hosting external content)

Modules available to both

  • clipboard
  • crash reporter
  • native-image (retina dsiplay)
  • screen (dimensions, dpi, enumerate all displays [multi-monitor support])
  • shell (run scripts)

Deploying Electron

  • Phase 1: Copy files
  • Phase 2: Compile to App
  • Phase 3: Build installer (MSI, dmg, debian package)
  • Phase 4: Package updates
  • electron-debug
  • electron-reload : similar to hot code fix!!!
  • electron-packager : building compiled apps
  • electron-builder
  • electron-updater : silent updates
  • electron-mocha : TDD, BDD
  • Devtron, Spectron
  • Boilerplate projects: electron-boilerplate
  • photonkit.com - makes a beautiful mac app

Tips

  • use CSS default cursor
-webkit-user-drag: none;
-webkit-user-drag: text;
  • keep windows open
  • offload work to main over ipc

Local Storage

  • Configuration files (listen for close event and store position and size to restore when reopened)
    • fs-jetpack
    • nedb
    • pouchdb

Relational DB

use any of the popular relational sql tools such as seriate, postgress, mysql, oracledb

Closing remarks:

https://github.com/sindresorhus/awesome-electron

Pluralsight: Electron Fundamentals by Jake Trent

http://electron.atom.io/

http://atom-slack.herokuapp.com/

You dont need permission to be awesome!!!

Fun with Fabric.js

by: @miyasudokoro K. Devin McIntyre

HTML 5 canvas library

Runs on node as well as the browser

Stop Javascripting like its 1999

@hunterluftis

hunter@heroku.com

There’s always something new in Javascript, new thing we can’t ignore. What does Modern JS look like? Looks a lot like Python

How can you start writing it? Three rules:

  1. Whenever you think about writing a callback, use async/await instead.
console.log (await someAction());
  1. Throw and catch errors or allow them to bubble
async function double(n) {
	if (isNaN(n)) throw new Error('invalid number');
	return (n * 2);
}
  1. Instead of chaining Promises, use await + simple assignment
const diff = await diffService.compare(last.blob, new.blob);
doSomethingWith(diff);

But is this still Javascript?

  • no more callbacks
  • no more ‘if (err)’
  • no more Promises

Three Objections

I still dont understand async/await (which means i still understand promises)

Promises is a specialized form of callback resolve goes to then reject goes to catch

so async functions can have try and catch handlers.

Lots of modules still use callbacks (like node’s core APIs)

util.promisify a callback function

const { promisify } = require ('util');

or use pify

I work on a huge codebase! (and rewrites are terrible)

What does a modern foo look like?

reads like python

The decentralized web

Keith Grant

Whats wrong with Social Networks:

  • Litle control
  • Dont own your data
  • requires account on each network
  • virtually no cross compatbility
  • neglect of personal & corporate websites

IndieWeb

Return to the original vision of the web

  • Grassroots movement
  • Formalized standards
  • W3C speciications

Multiple pieces to the puzzle

  • Microformats
  • Webmentions
  • IndieAuth
  • Micropub
  • Syndication

it can be adopted incrementally

indieweb.org - indieweb wiki/documentation

  1. register your domain name
  2. one central location for your broader presentation
  3. Put all your content in your site ( articles, notes, replies, likes, reposts )

What is a microformats - annotations (machine parsable) (microformats.org)

Webmentions: Tracking the conversation! Simplification of older ‘pingback https://webmention.io - works with static pages!

<link rel='webmention' href='yoursite.com/article' />