Posts Tagged ‘javascript’

29
Apr
2016

London React Meetup – April 2016

by Leon Hewitt

An evening of testing workflows and dynamically built forms awaited visitors to Code Node last Wednesday when the London React Meetup was once again in town.

Tom Duncalf kicked things off by describing what he has found to be effective unit and integration testing strategies for React applications.

Tom explained his rationale for writing tests and in particular unit tests. In addition to verifying the application behaves as expected and providing a useful set of automated regression tests (allowing you to refactor with confidence), he pointed out how well written tests can act as documentation for the code and enable faster debugging with less dependency on end-to-end tests (be they automated or manual) to expose errors.

Taking this testing philosophy, Tom went on to discuss how this applies to testing applications built with React and listed the qualities he looks to test in his components (e.g. do they render correctly, can you interact with them as expected and how do the integrate with the rest of the application).

The talk was full of code examples of how Tom went about implementing his tests using his toolchain of choice: Mocha, Chai and Enzyme.

Next up was Anna Doubkova discussing her experiences with Redux Form and how useful it was in developing a CMS application she was involved in with her team here at Red Badger. One aim of the project was to deliver a CMS with less dependency on developer input to extend. Anna noted how great it would be for the customer to alter their CMS just by changing the data structure. i.e. have fields added by the CMS administrator automatically render on the page without the need to bring the development team in.

A combination of JSON SchemaRedux Form and React enabled the team to do just that. Anna took us through the journey of developing the solution and the reasons for the technical choices made.

Anna ended by listing the pros and cons of working with redux form, expressing overall how easy the team found it to use.

Rounding the evening off was Arnaud Rinquin who shared his journey of reducing the friction he was feeling around testing in the javascript ecosystem. It’s no secret that the toolchain takes a bit of setting up, leading to developers experiencing what has been politely termed Javascript Fatigue.

Inspired by Dan Abramov’s Redux tutorial,  Arnaud aimed to recreate the feel of Dan’s environment in his own workspace. That being: run the tests in the browser, have tests alongside the production code (in the same file), have the tests run automatically on a code change and have the tests execute in the shell  (to facilitate continuous integration).

He successfully achieved this through a combination of a babel plugin (to remove the test code and any dependencies from the code files) and a specially written chrome plugin (to control the test runs). This achievement has enabled Arnaud to enjoy what is for him “a proper TDD workflow”. He can now keep coding and stop worrying.

The success of these meetups (all the 300 tickets for this event were snapped up within an hour) demonstrates the popularity of React in the London software community and the quality of the talks highlights how open the React community is to exploring and embracing new techniques. Everyone’s already looking forward to what fresh insights May’s meetup will provide.

Hear about when new events are announced first by joining the meetup group here.

 

18
Apr
2016

Building Desktop Apps With Electron, Webpack and Redux

by Roman Schejbal

In March 2016, as a part my annual training budget – a perk that every badger gets – I had the opportunity to go all the way to the Fluent Conf, which was in sunny San Francisco. You can read the best bits from the conference in Alex's blog.

One of the workshops I attended was about building a basic desktop application with Electron, that’d be compiled for every major OS and I’d like to share the knowledge and the takeaways I grasped during a 3 hour long session.

We’ll take a high level look at how Electron works, but we’ll also use ES2015/16, Git, Webpack, Babel and a bit of Redux, therefore it’s good to have a clue about what those are so we can focus on our topic and it’s not too overwhelming. We’ll see how we can implement live reloading and get that fast-paced development cycle that most of today’s developers are used to.

What we’ll be building

To highlight some of the things that a desktop application excels in from a normal web app, we’ll need to build something using the native features. Electron provides many APIs above the native functionality and I’ve decided to build a simple HackerNews app or a watcher, that’ll let me know when there is a popular post (>= XXX votes), because I don’t want to miss those and it’s quite reasonable size of a project for this purpose. Well, at least I thought so when I started writing this blog. ¯_(ツ)_/¯ You can download the app (for Mac) here.

app

If we go to the Electron homepage, we’ll find quick startup instructions at the bottom of that page; so startup your terminal and let’s get on with it!

Note: make sure you have the latest node and npm installed to avoid any potential errors

# Clone the Quick Start repository
$ git clone https://github.com/atom/electron-quick-start

# Go into the repository
$ cd electron-quick-start

# Install the dependencies and run
$ npm install && npm start

After running those commands you should have a Hello World app running on your desktop.

Main Process

What you see is genuinely a browser window, in electron we call them renderers and they are created by the main process. By main process we mean the main script defined inside package.json. You can think of it like a parent of all it’s children (renderers) that is responsible for creating instances of the BrowserWindow class. This is also the place where you’d work with file system operations for example.

Renderer Process

The browser window you see is one renderer process. Electron uses Chromium for displaying pages, but it’s topped with some Node.js APIs allowing interactions on a lower level.

Now that we know the entry point, let’s have a look into it. It’s pretty well commented out of the box so should give you a good idea what’s going on in there.

main.js

'use strict';

const electron = require('electron');
// Module to control application life.
const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadURL('file://' + __dirname + '/index.html');

  // Open the DevTools.
  mainWindow.webContents.openDevTools();

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

On the application ready event we call the createWindow function that’ll instantiate a new BrowserWindow (a renderer process) and load url 'file://' + __dirname + '/index.html;' which is our main html file, from there on we are in our very known single-page application land. Also, we programmatically open the Developer Tools by calling mainWindow.webContents.openDevTools(); since Cmd+Alt+J does not do anything inside Electron.

Looking into the index.html we can see there is a usage of the global process variable and as you know this is not available in a normal browser window. It carries all the environment values that can come in handy as we’ll see in our app.

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chromium <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

I mentioned that the renderer is topped with some Node.JS APIs, the process variable is one of them. The other one worth mentioning is that you can actually use require on the client and load modules as you do in Node environment, but we’ll go a slightly different direction today.

The setup

We’ll use Webpack with it’s hot module replacement (HMR for short) for live reloading. So we need to build a little server that’ll host and reload our code while we develop.

In order to do that, we need to install a few node modules:

npm i -—save-dev express webpack webpack-dev-middleware webpack-hot-middleware webpack-target-electron-renderer

Then we create a basic webpack configuration:

webpack.config.development.js

var webpack = require('webpack');
var webpackTargetElectronRenderer = require('webpack-target-electron-renderer');

var config = {
  entry: [
    'webpack-hot-middleware/client?reload=true&path=http://localhost:9000/__webpack_hmr',
    './src/index',
  ],
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loaders: ['babel-loader'],
      exclude: /node_modules/
    }, {
      test: /\.css$/,
      loader: 'style!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader'
    }, {
      test: /\.png|\.svg$/,
      loaders: ['file-loader']
    }]
  },
  output: {
    path: __dirname + '/dist',
    publicPath: 'http://localhost:9000/dist/',
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ]
};

config.target = webpackTargetElectronRenderer(config);

module.exports = config;

Since the electron index.html page is running from the file system, we need to provide a correct path for the webpack-hot-middleware so it knows where to connect. Same goes with the output.publicPath for the webpack-dev-middleware so the reload of scripts works properly. The webpack-target-electron-renderer is needed to set all of electron built-in modules as externals plus some other bits here and there. You can find out what exactly it’s doing in the npm package itself.
Also, as you can see we’ll use babel and css-modules so we actually need to install a few more modules which you can do with this command:

npm i —-save-dev babel-cli babel-loader babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-preset-react css-loader style-loader postcss-loader

Now that we have our config, let’s write up the server and connect it to Webpack.

server.js

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';

import config from './webpack.config.development';

const compiler = webpack(config);
const app = express();

app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  stats: {
    colors: true
  }
}));

app.use(webpackHotMiddleware(compiler));

app.listen(9000);

Update the index.html to use the built javascript.

index.html

...
  <body>
    <div id="root">
      We are using node <script>document.write(process.versions.node)</script>,
      Chromium <script>document.write(process.versions.chrome)</script>,
      and Electron <script>document.write(process.versions.electron)</script>.
    </div>
    <script>
      (function() {
        const script = document.createElement('script');
        script.src = process.env.ENV === 'development' ? 'http://localhost:9000/dist/bundle.js' : './dist/bundle.js';
        document.write(script.outerHTML);
      }());
    </script>
  </body>
...

Then tweak the package.json for a babel configuration and a startup script:

package.json

{
  ...
  "main": "index.js",
  "scripts": {
    "start": "ENV=development electron .",
    "server": "babel-node server.js"
  },
  "babel": {
    "presets": [
      "es2015",
      "stage-0",
      "react"
    ]
  }
  ...
}

But now we have to run two scripts to startup the app.

npm start
npm run server

Let’s get rid of that by installing the concurrently module npm i —-save-dev concurrently, update the package.json once more and we are back to one command:
npm run dev

package.json

{
  ...
  "scripts": {
    "start": "ENV=development electron .",
    "dev": "concurrently -k 'babel-node server.js' 'npm start'"
  },
  ...
}

Engage dev

Until this point, we were setting up the development environment to have this convenient developer experience. From here we’ll actually start building our app, but I want to apologize for omitting (on purpose) quite a lot of app-specific stuff just because we want to primarily focus on the electron APIs and see the usage of it. In any case, you can find the full source code on my github.

Inside the webpack config we’ve set the entry point to ./src/index, so here is the content of it.

src/index.js

import 'babel-polyfill'; // generators
import React from 'react';
import { render as renderReact } from 'react-dom';
import debounce from 'debounce';
import configureStore from './store/configureStore';

const state = JSON.parse(localStorage.getItem('state'));
const store = configureStore(state || {});

let App = require('./components/app').default;
const render = (Component) => {
  renderReact(<Component {...store} />, document.getElementById('root'));
};

if (module.hot) {
  module.hot.accept('./components/app', function() {
    let newApp = require('./components/app').default;
    render(newApp);
  });
}

const saveState = debounce(() => {
  localStorage.setItem('state', JSON.stringify(store.getState()));
}, 1000);
store.subscribe(() => {
  saveState();
  render(App);
  if (process.env.ENV === 'development') {
    console.log('state', store.getState());
  }
});
store.dispatch({ type: 'APP_INIT', store });

Since we are using Redux and having a global state of the app on one place, we can use this minimal HMR mechanism that’s inspired by Dan Abramov’s blog.
Basically we re-render the app every time when something that’s imported under the App or even the App component itself changes. If it’s something else, we then refresh the whole page as this is set by query parameter reload=true inside our webpack config. Additionally we could write a reducer replacement mechanism so the webpack doesn’t have to refresh the page when we update actions, reducers or sagas. On any change of the state we save it into the localStorage, therefore we don’t really care about losing the state after refresh.

Moving on

src/sagas/index.js

function fetchTopStoriesApi() {
  return fetch(`https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty`)
          .then(response => response.json())
          .then(stories => stories.map(storyId => ({ id: storyId, loaded: false, loading: false })));
}

I’m using redux-saga but feel free to use anything else like redux-thunk or not redux at all! The key thing to see here is the native fetch function for collecting HackerNews stories. I want to point out that in a normal web application I wouldn’t be able to do this (at least on the client side) because of CORS. But since we are in a native-like application, there’s no restriction on CORS in Electron.

Once we have the stories inside our state, we can print them out and attach some onClick handlers. In a normal web application we’d just create the anchor tag and give it a href, but if we do this inside an electron application and then click on the link, electron would load the page inside giving us no option to go back! What we want instead is to open the story in the user’s default web broswer. That’s where the electron’s shell module comes into play.

src/components/app/index.jsx

import electron from 'eletron';
...
handleClick(story) {
    return (e) => {
      electron.shell.openExternal(story.url);
      this.props.dispatch(actions.clickedStory(story));
    };
  }

Now let’s just skip all the other components, reducers and have a look at one particular action.

src/actions/index.js

export function notifyAboutStory(story, onClick) {
  const notification = new Notification(`Hacker News ${story.score} 👍💥 votes`, {
    body: story.title
  });
  notification.onclick = onClick;
  ...
}

This is where we trigger the native notification to pop up. It follows the Web\Notification API so if you, for example, want to make it silent, you’d just add that as an option inside the options parameter within the constructor.

Communication between processes

Sometimes, depending on what we’re building we might need to communicate from the renderer process to the main process. It could be anything from a native open-file dialog that’s available only on the main process, or simply quitting the application with app.quit() as we have here.

Processes may communicate by messaging each other via ipcRenderer or ipcMain (depending on what side is being implemented) which is basically an instance of EventEmitter and we use it like this:

Event emitting:
src/components/app/index.jsx

import electron, { ipcRenderer } from 'eletron';
...
<button className={styles.quitBtn} onClick={() => ipcRenderer.send('quit')}>Quit App</button>

Listening on event and taking an action:
main.js

...
var ipcMain = electron.ipcMain;
ipcMain.on('quit', () => {
  app.quit();
});

Driving this home

From the screenshot above you can see we have the app inside the OSX menubar, we’ll use this menubar package for it’s ease of use and all we have to do is to update our main.js to implement it.

main.js

...
var menubar = require('menubar');
const mb = menubar({
  'width': 500,
  'height': 700,
  'preload-window': true,
  'resizable': false
});
mb.on('ready', function ready () {
  console.log('app is ready')
  // your app code here
});

Building the app

For building the app we have a special webpack production config, that just overrides some of the development configuration and saves the build into a dist folder.

Then we use electron-packager to get the actual executable build.

Our final scripts section inside package.json looks like this:

package.json

...
  "scripts": {
    "start": "ENV=development electron .",
    "dev": "concurrently -k 'babel-node server.js' 'npm start'",
    "build": "webpack --config webpack.config.production.js && electron-packager . HackerNews --platform=darwin --arch=all --overwrite"
  },
...

And that’s it! If you have any questions, use the comments below or get in touch on twitter.

15
Apr
2016

London React Meetup – March 2016

by Joe Paice

This month we were back at the London Facebook office for another brilliant London React Meetup. We had another full house with plenty of pizza, beer and React geekery.

react-meetup-march-1

 

For this meetup we had two presentations. Red Badger’s very own Stuart Harris gave a talk on Redux Sagas and Facebook’s Martin Konicek gave us a look under the hood of React Native.

Managing and testing side-effects in Redux with Redux Saga

Stuart Harris – Red Badger

react-meetup-march-2

 

Stu gave some great insight into how to go about incorporating Redux Saga into Redux applications. Redux Saga is a Redux middleware that handles asynchronous actions in your applications. Instead of dispatching Thunks which get handled by the redux-thunk middleware, you create Sagas to gather all your side effect logic in a central place.

Stu took us through what Sagas are, how to use them and how easy they are to test. No more crazy spies or mocks. No more manipulating time or rewiring dependencies. Just pass in actions and test the output effects.

If you are having trouble with asynchronous actions in your project perhaps Redux Saga can help.

Under the hood of React Native

Martin Konicek – Facebook

react-meetup-march-martin

Martin works on the React Native team at Facebook. He gave a great tour of React Native with a focus on Android development.

Martin delved into the porting of Facebook’s Ads Manager app from iOS to Android. He demonstrated some of the ways they were able to share code across both platforms, boasting over 85% code reuse in the Ads Manager.

Martin elaborated on the architecture and extensibility of React Native and gives some insight into the React Native Open Source process. It is pretty amazing how Facebook handles syncing their internal React Native and the public React Native on GitHub. I look forward to more tools like the Facebook Github Bot to help developers manage their open source projects.

The recordings of the talks will be available shortly, we’ll post a link here soon.  Thanks to Stu and Martin for their great talks, Facebook for hosting and the members of the community that joined us! Join the meetup group to receive updates on future events!

29
Mar
2016

O’Reilly Fluent 2016 – impressions and trends

by Alex Savin

team-badger-golden-bridge-600

Roman and Kadi and I are back from San Francisco and Fluent conference. A week-long escape into the rains and floods of California, with an extra flavour of JavaScript. This was my second Fluent conf, and it’s time to share some takeaways.

For now this is the last Fluent event in San Francisco. It was announced that next year will be in San Jose, and there is also one more Fluent this fall coming up in Amsterdam.

Worthy talks available to watch

All keynotes from day 1 and 2 are available online. To save your time, here’s my favourites:

  1. How NPM split a monolith and lived to tell the tale. Laurie Voss on making large breaking changes without anyone noticing.
  2. Quality, equality, and accessibility – Laura Palmaro on the current state of web accessibility (which has become cutely named ‘a11y’ because it takes too long to type).
  3. Complex responsive SVG animations by Sarah Drasner.

Douglas Crockford from PayPal also did an intro on The Seif project – PayPal’s own reinvention of the Internet. They are pretty early stage, and their vision is debatable to say the least. They do have good intentions.

General trends and feelings

Last year React / Node combo was something of a novelty, a curious thing to learn. Netflix was doing introductory level talks on React and why they chose it. This year React / Redux / Babel / Node is the default. Dan Abramov’s name was mentioned in every other talk. Interestingly, Facebook was pretty much absent from this conf – which is understandable since they are busy having their own React-dedicated events. Notable cool guys on the ground included Google, Netflix, New Relic, Uber, and Léonie Watson doing an epic talk on a11y.

heroku-socks-600
Notable conference swag included Heroku socks

A lot of talks were about interesting ideas or wishful thinking, less of production-ready reality. I suppose this is what webdev is about – there is no platform really, more like a herd of clients and engines somewhat held together by loose rules and standards.

Meanwhile, Brendan Eich was pushing for service workers, WebAssembly and class decorators. He was surprisingly quiet on the sensitive topic of his new browser Brave, which blocks bunches of JavaScript by default.

Two days of talks

The keynotes were followed by five tracks of talks to choose from. Sometimes it was hard. These talks are not available online and will be later published and sold by O’Reilly. I’m going to handpick some quick takeaways from the sessions I attended.

design-process-600
Design process in a nutshell

Accessibility

disability-600

Accessibility is still very important. There are lots of different disabilities, and addressing such users is more important than addressing old browsers. Different OS platforms contain different a11y APIs, but with regard to the Web, semantic HTML combined with basic ARIA markup gives a huge heads up for a11y tools to read through your page correctly.

Few personal takeaways:

  • Browser in addition to DOM tree creates separate a11y element tree based on your markup
  • aria-live=“polite” element creates live region on the page, when action on one element affect content of other element. Every time content of live region is affected, screen reader would announce that as soon as it changes. Generally screenreader is unable to jump around the page, and cannot be in two places at once.
  • role="complimentary” when content is incidental but related to the content on page (similar to aside HTML tag)
  • Use tabindex=“0” to allow keyboard focusing on otherwise unfocusable elements

Léonie Watson did a highly practical talk on semantic HTML and ARIA roles. Her screenreader for some reason failed to function when connected to the projector, and so she did the whole talk from memory, without being able to see any slides.

There was also an announcement of the upcoming Web A11y free course on Udacity.

Progressive webapps

Google did a presentation on their vision of web apps and software delivery to the end user. In a way from the user’s perspective there is no difference between web apps and native apps, as long as they behave in exactly the same way. There’s also a negative trend regarding users buying new apps from App Stores, and in general they use only three native apps 80% of the time. Google wants to address issues with web apps lagging behind native apps in terms of offline availability, home screen shortcuts, direct to full screen launching and push notifications. Some of that stuff is already solved. The biggest missing piece is probably offline access, which they claim can be resolved with service workers and an extra layer that intercepts all requests and behaves according to the network availability.

All these ideas have a common name and a site – Google’s Progressive Web Apps initiative.

NPM lifehacks

As an avid npm user I spend a good chunk of time every day typing npm into console. There was a talk with various hints and hidden features that might be pretty useful.

  • npm install when you are offline – npm contains a (huge) library of modules on your machine and can install the relevant module even when you’re offline from the local cache. To do so run npm install --cache-min 999999.
  • npm version [major, minor, patch] will bump version of your npm package and save it in package.json file. You can even auto-commit this with npm version major -m "bump to version %s”
  • npm prune – get rid of all packages in your local node_modules folder that are not explicitly specified in the package.json
  • npm outdated – quickly check for old and outdated packages in your app
  • https://tonicdev.com/ – Node sandbox that lets you require npm packages in the browser
  • NSP is great for maintaining 3rd party security in your Node app (although it is known to be down from time to time).

Monitoring

There were two somewhat orthogonal talks on aspects of monitoring your production apps.

New Relic did a presentation on NR Browser, which is a handy way of getting data about how your users actually perceive the app. It gathers everything that a normal browser would, including JS errors, and time to load pages to the client based in various locations. Server side pages usually load 10-20x faster than client side. There are also a number of most strange JS related errors that can be experienced by users and their (derelict) browsers. You can also detect bad deployments by monitoring spikes of client errors.

Shape Security did a talk on dark traffic. According to them, 92% of the global web traffic belongs to non-humans, which is sort of a pity because you still get all the monitoring alerts, but none of your human users are actually affected. Here lies an interesting question of traffic origin detection. You are likely to only care about human users, but they are a minority nowadays. Most of the bots will also try and pretend to be real humans the best they can. Bots will try to authenticate with real usernames / passwords, which are quite openly available on sites like Reddit/r/pwned, or less openly traded for money on the dark net. Since most users are using the same password everywhere, bots will often succeed in signing in, then will crawl everything they can, and move on to the next site.

Falcor by Netflix

Falcor deserves a dedicated blog post. It is Netflix’s answer to GraphQL and Relay by Facebook – central store and dynamic data fetching combined with request optimisation. Its implementation however is distinctively different from both GraphQL and Relay.

@jhusain did an impressive job to a full house explaining Falcor while live coding an app and getting things to work. We are using GraphQL in our production apps, so my angle was obviously on how Falcor is compared to what we already have. Here are a few takeouts:

  • GraphQL is a query language that allows you to request any amount of resources. With Falcor you request either a single resource or a known range. There is no way in Falcor to ask something like “give me all you have”.
  • JSONGraph for data
  • There is no schema in Falcor – as opposed to GraphQL where you must specify types. This works for Netflix since their production app has something like 6 types of resources.
  • Falcor might be more lightwave and easy to start
  • Current implementations of Falcor are in Node and Java. There is internal implementation for iOS which is not released yet.

I shall come back to this topic and write a more comprehensive blog.relevant-swag-600
Other relevant swag

Workshops day

We also attended a full day of workshops. The first half of the day was about implementing desktop apps with Electron, then we did a session on writing your first language compiler, and finally real time drawing on HTML canvas. Electron was probably most notable out of the bunch – in about three hours we ended up implementing two functional desktop apps from scratch. Roman is going to write more on this topic.

Electron provides you with tools to make native OSX / Windows / Linux desktop apps while using the familiar stack of Node and React. But unlike conventional web apps, you also get full access to the filesystem, no CORS restrictions and the ability to integrate into the system menu. If you always wanted to get your app behind the system tray icon, with Electron you finally can.

Extra activities

job-board-600
Red Badger is hiring and we have an #officedog

The general format over the conf was 30 min talks followed by 15 min breaks. After two or three talks there would be 30 min break. In the middle of the day there was an hour lunch break. Everything started at 9am and finished around 6pm.

Breaks were filled with extra activities you could choose to attend. The main attraction and largest source of swag was the exhibition hall, filled with companies presenting their products and giving out freebies. During the last two days the organisers also moved coffee and snacks to the middle of the exhibition hall.

I should probably mention – we were fed pretty well, considering the scale of the operation.

In the main foyer they also tried to get introverted software devs to talk to each other by having topical meetups, speed networking and lightning talks.

exhibition-oreilly-600 vr-signed-book-600
Being primarily a book publisher, O’Reilly brought a bunch of authors signing and giving away free books. I got a couple too.

Trip

This trip was possible thanks to Red Badger’s training budget programme. Me, Roman and Kadi had an amazing time, despite the daily dosage of rain. This time I also did daily video log episodes covering our full journey outside of the conference. Yes, we had some fun.

team-badgers-600

Team Badgers

I enjoy Fluent mostly because of the variety of topics covered. Writing compilers, programming GPU, WebVR, fending off the evil bots, deploying clusters of containers, debugging performance – there’s something for everyone. So, thanks O’Reilly for making this a reality once again!

If you like the idea of an annual training budget, trips to conferences like this and a big focus on learning, Red Badger could be the place for you. Check out of current vacancies here.

4
Mar
2016

London React Meetup February 2016

by Roman Schejbal

A week after our fancy functional meetup we had another, the popular monthly London React and I’m bringing you a short summary of how it went.

FullSizeRender

Once everyone made themselves comfortable by filling their bellies with pizza and beer from a wide selection, we all moved to the conference room and took our seats. Badger Jon grabbed the mic and after a quick intro, we had the first Reactor on stage.

Sharing React & Redux across applications

Christopher Cook – Software Engineer @ Sky

Sharing React & Redux across application

Chris talked about an interesting topic which is how to efficiently share code between different platforms like smart tv, console, how to work with styles in such a project and about practices for code reuse in general. He primarily focused on the process and the thinking behind the approach they used to tackle the problem so don’t expect any code snippets or technical details there.

I dare to mention that here in Red Badger, we actually face the same challenge on one of our projects and it is not exactly an easy task to solve. I can imagine how Redux is helping with this by embracing the idea of separating presentational and container components, however, it is not a silver bullet and you still have to think things through before you start smashing those semicolons and brackets in.

Watch the talk here:

Designing React Components

Monika Koziol – Visual Designer @ Red Badger

Designing React Components

Monika gave an insight on how we collaborate, design and build React components as cross-disciplinary teams in Red Badger. She also explained why as a designer she is so excited about component-based UIs and highlighted the similarity between React and Sketch app. Although this wasn’t a technical talk she kept us all entertained and even flavoured her speech by adding a cool real-time poll, getting everyone to vote on naming components, which was fun.

Watch the talk here:

After that, we had a quick break to grab more beer and kill the thirst. Then we moved onto our final talk.

Using Redux Everyday / Real World with Redux

Chris Pearce @ Lystable

Using Redux Everyday

We’ve already had a couple talks about Redux, but they were mostly a high-level overview and about how it differentiates from the Flux architecture. None of them, until now, dealt with the tricky parts the developer faces when building a more complex application; that’s exactly what Chris covered for us! He took us through their 7 months journey of building Lystable, an app for companies to manage their external workflows.

Chris also touched on Redux-reselect and selectors. When your app gets more complex you’ll want to normalise the data in your at the reducer level to minimise data redundancy across your application. Once you have that handling relations between models can get tricky and this is when, Chris explained, that redux-reselect or selectors should come into play.

Watch the talk here:

 

Thanks to all the speakers for such great and educational talks, Sky & Red Badger for the pizza and beers, Alex for recording and also thanks to Skills Matter for hosting! Don’t forget to follow us on twitter for future events!

19
Jan
2016

London React Meetup – January 2016

by Jon Yardley

 IMG_0114

Christmas is over and New Years resolutions have been made (and/or already broken?) but regardless of the sub zero temperatures, 250 developers flocked to Facebook’s London HQ for the first London React Meetup of 2016. This month’s topics covered React Native, Redux, testing with React & declarative coding with React.

With pizza consumed (110 in total) and beers in hand, our very own CTO took to the stage to kick things off. 

Jani Eväkallio, Futurice

Actually Building Things In React Native

IMG_0106

Jani took us through his personal experience at using React Native to build production apps for clients. In a nutshell, Jani informs us that React Native is in a good place and although there are still a few issues you might hit upon is ready for production. Sixty frames/second is apparently easy achieve however more complex transitions might need some tweaking.

He also tells us that it is pretty simple to implement an unsupported native API of 3rd party component even with little to no knowledge of Objective-C. This talk most certainly made me want to kick off my own React Native project! Check out the talk here:

 

Oliver Woodings, Qubit 

Are you suffering from Selenium-itis? 

IMG_0126

Oliver’s talk covered the ways in which we currently test UIs with React and offered an alternative approach to implement end-to-end testing using Qubit’s open sourced react-driver.

React driver aims to eliminate flaky service timeouts by hooking into your React application using selectors and allows you to use whatever test framework you prefer. As a nice addition it will ‘automagically’ install selenium-standalone for you so you don’t have to go through the pain of trying to do it yourself.

Check out the talk here:


 

Jonas Ohlsson, State  

Using Redux – a case study

IMG_0147

Redux is the next evolution of Flux and comes with dramatic productivity benefits. Jonas covered the Redux way of doing things, demonstrated how he’s using it on criticalcss.com, a product he built recently and explained what he’s learned along the way.

Check out his talk here:


 

Michael Jackson

Lightning Talk – react-stdio

IMG_0155

With Ryan unable to make the event Michael took to the stage to deliver an engaging talk on how to write (or re-write) components so that they are way easier to reason about. This uses a really simple app that generates simple and more complex sound waves.

Interestingly he creates components that didn’t render any visual UI but generated sound using the WebAudio API. As he pointed out, for internet users who are blind or partially sighted, audio is their main or only UI when using a browser. In addition, these audio components allowed him to quickly iterate on the application during his live demo.

Check it out here:


Thanks to all the speakers for an engaging and educational evening. Also thanks to Facebook for hosting and Alex Savin for the great snaps. In my opinion it was one of the best meetups so far!

The next meetup will be happening in February so keep you’re eye on twitter @londonreact for updates as I am sure you’re well aware they go super quick.

18
Jun
2015

Arch framework – update

by Alex Savin

arch-3d-16x9

Arch framework official logo by Sari Griffiths, Clementine Brown and Blanca Tortajada

Arch is an isomorphic single page app framework built on top of React and Immutable.js. It was announced and open sourced at the  React London meetup in April by Viktor and Tiago. Many of us at Red Badger are really excited about Arch, its performance, flexibility and openness. Last week we had a first of its kind Arch hackathon at the HQ, and here are a few updates we’d like to share with you.

Official Twitter handle is reserved – it’s ArchFW. Follow it to get quick updates on development and future events (especially if you’re in London!). It is also one of the quick ways to contact team, ask questions and get feedback.

New dedicated organisation is now available on Github – Arch-js. It contains all Arch -related repositories, including Core of the framework, command line client and example apps from the original announcement talk.

We invite you to join the discussion under the core repository. Post issues you encounter, or comment ongoing topics. If you have an idea on missing example app that would enable you to try the framework, feel free to add it here.

Crash course into Arch and functional web programming is now fixed and available for brave new users. You’ll find even more chapters on Arch internals, concept of immutables, cursors and isomorphism in the docs folder. We also have reserved domain archjs.org for the upcoming webpages.

And don’t forget the talk from London React meetup by Viktor and Tiago with introduction to Arch and apps with centralised state.

What’s next? Few things:

  • More sample apps, in ES6 and Livescript
  • Designing more powerful routing DSL
  • Default support for unit tests
  • Improving command line client

Arch is now properly open sourced with BSD 3 license. We hope you’ll like it.

15
May
2015

Join me as a new voice in the tech community

by Winna Bridgewater

wb_workshop_cropped

A glimpse at the weekend workshop I led. Photo by Alessia D’Urso, Girls In Tech UK Board Member.


London has a staggering number of events for coders. It’s awesome.

The only thing is, I’ve gone to a lot of events, and I can count on one hand the number of times a technical discussion—about a tool, an industry standard, or the craft of code—was led by a female. For the majority of the events I attend, I am one of only two or three females in attendance.

I decided that this year, if I want to see more women presenters, I need to step up. I need to talk at an event.

Getting Inspiration

As if the universe was listening, two events came up this spring that got me more excited and less nervous about going for it.

First, Ladies Who Code London ran a workshop on public speaking, and it was hosted here at Red Badger. Trisha Gee and Mazz Mosley were wonderful. Their message was simple: it gets easier each time you do it, and there are ways to work through nervousness. They also emphasized that the audience is rooting for you–everyone in the room wants to see you succeed. Pretty nice, right?

Then I had the chance to attend the Women Techmakers Summit, an evening celebrating International Women’s Day that was organized by Google Women Techmakers and Women Who Code London. There was a series of speakers and panelists, and every presenter had a powerful message. The speaker whose message stayed with me most was the keynote, Margaret Hollendoner

Margaret said she sometimes makes her career sound like it was all “right place at the right time” luck. But she told us it wasn’t that simple. Every opportunity was lucky in one sense, but the opportunity wouldn’t be there without her hard work. She also emphasized that deciding to say “yes”  required confidence and bravery.

Margaret’s presentation gave me another nudge: get past my fear and present at an event.

Saying Yes

wb_teaching

Only two days after the Summit, I got an email from Lora Schellenberg about Spring Into Code, a weekend workshop on Web Development offered by
GeekGirlMeetup
and Girls In Tech. Lora asked if I was available to teach–the original instructor had to back out, and they were looking for a replacement.

It sounded like my lucky chance, so I agreed.

Then I got all the details. I was going to be the only teacher for 12 hours of instruction over two days. I’d be teaching at Twitter headquarters to an audience of 100 people.

I felt pretty panicked, so I knew it was time to make some lists.

Why I should not do the workshop
  1. I’m not an expert in web development.
  2. I’ve only been doing this stuff professionally for a year and a half.
  3. I won’t be able to answer all their questions.
  4. 12 hours is a long time.
  5. 100 people is a lot of people.
Why I should do the workshop
  1. I’m not an expert in web development. I still spend most days learning new things. I know what it’s like to feel confused and lost. And I know how to recognize and celebrate small triumphs.
  2. I did set that personal goal.
  3. Those nice ladies did tell me the audience will root for me.
  4. That other nice lady did say you need to take advantage of luck that comes your way.
  5. If I’m going to teach 100 people for 12 hours, this is the ideal audience. Eager learners who, by choice, agree to a weekend in front of a computer taking in as much as possible.

I decided to go for it—butterflies, sweaty palms and all.

There are so many things I could focus on under the umbrella of Introduction to Web Development. I decided my main goals would be:

  • Make techy code stuff seem less scary.
  • Make people feel ok about asking questions.

Saturday morning arrived, and I had a rough start. I spent the first session working out how to use the mic and the two screens floating on either side of me. My notes weren’t loading like I hoped. The Internet was down. My demo wasn’t working even though it worked mere hours before. I was shaking.

After the first demo fell flat on its face, I knew I needed to stop. I took a few minutes to get everything running properly. I got water. I took some deep breaths. Those minutes felt like ages, but it was worth it. When I started up again, stuff finally started working.

The first day flew by. A few folks came by during breaks to say they were enjoying themselves. At the end of the day, lots of people came by to say thanks. Were my silly jokes working? Did my missteps when typing—forgetting a closing bracket, leaving off a semicolon, incorrectly specifying a source path—help people understand that breaking and fixing things is what this job is all about? During the second day, people from all over the room were asking questions. Tables were helping each other debug and understand what was going on. Breaks came and went with people staying at their seats to try things out. I couldn’t have hoped for more.

Reflections

I have so many ideas about what I’d change if I could do it again. I missed some concepts. I glossed over others. But I did it, and I had an amazing time.

If you’re tempted to give a talk or run a workshop, please go for it. It’s scary but great, and you have a wonderful community rooting for you.

Red Badger is always looking for ways to connect to the tech community. Like that sound of that? Then come join us.

4
Mar
2015

React Native – The Killer Feature that Nobody Talks About

by Robbie McCorkell

React Native logo
 
At the end of January I was lucky enough to go to React conf at Facebook HQ in Menlo Park. This was my first tech conference, and it was a great and inspiring experience for me. The talks were excellent and I recommend everybody check out the videos, but the talks that really stole the show were the ones on React Native.
 
React Native allows developers to build real native applications using javascript and react, but not web wrapper applications as we too commonly see. React simply takes charge of the view controllers and programatically generates native views using javascript. This means you can have all the speed and power of a native application, with the ease of development that comes with React. 

Playing with React Native

This is a really exciting development for the native app world, and gives a new perspective on what native app development could be. I’d previously tried to learn iOS development a couple of times, first with Objective-C, and later with the introduction of Swift. Whilst I think Swift is a massive improvement in iOS development, I still ended up getting bored and life got in the way of learning this new system. So initially, the idea of using my current skill set in React web development to build truly native apps was extremely enticing (and still is).
 
I generally believe that as a developer you should pull your finger out and learn the language that suits the job, but in this instance React Native seemed to offer more than just an easy way into iOS development. It offered a simple and fast way to build interfaces and to manage application logic, and the live reloading of an application in the simulator without recompiling blew my mind.

Luckily for me, conference attendees were given access to a private repo with React Native source code inside, so I began playing as soon as I got back to my hotel room. Within 5 minutes I was modifying one the provided examples with ease without any extra iOS development knowledge, and I was hooked.

An addendum

Since then I’ve been leveraging my early access to talk publicly about React Native to some great reception. It’s been fascinating discussing this with people in the community because I hear very little scepticism and a lot of excitement from web developers and native developers alike (at least those that come to a React meetup).

However the more I talked about it the more I realised the message I was conveying in my presentations was not quite right. One of the major themes I focused on was the fact javascript developers like myself can now easily get into the native world, and that companies only need to hire for one skill set to build and maintain their entire suite of applications. 

This is still a hugely important advantage, but it isn’t the major benefit and doesn’t highlight what React Native offers over competing frameworks. It also doesn’t perfectly align with my view that looking for a tool or framework just to reduce the need for learning another language is lazy thinking. There’s more to React Native than this.

React Native’s advantage

React Native’s biggest feature is React.

This may seem a bit obvious (the clue is in the title) but let me explain. When I first looked at React I thought it was insane like most people. It takes such a different approach to web development that it gives many people an immediate repulsive reaction. But of course the more I used it the more I realised I could never go back to building web applications (or any front-end app for that matter) any other way. The patterns react provides are an extremely powerful way of building applications.

If you haven’t used React much it might help to know that React lets you declaratively define what your view should look like given some input data. A react component is passed some properties that it requires to render a view, and as a programmer you simply define the structure of the view and where that data should sit. In doing this you’ve already done half of the work in building your application, because if a component or any of its parents changes their data (in the form of state), React will simply re-render the affected components given the new data.

No specific data binding. No event management. No micro managing the view. Just change the data and watch React recalculate what your view should look like. React will then use its diffing algorithm to calculate the minimum possible DOM manipulations it can do to achieve the desired result.

The second half of your application structure is of course user interaction. Patterns and tools like Facebook’s Flux and Relay help with this, but essentially these are just ways in which you can modify the data in your application in a neat and scalable manner. The application still simply recalculates the structure of the view once the data has changed.

React really shines when you start to scale an application, because the complexity of your application doesn't have to increase too much. This is of course quite hard to demonstrate in a blog post, but I can give you an example of a simple little app written in angular and react that I adapted from Pete Hunt, one of React's creators.

Angular:

See the Pen RNBVZz by Robbie (@robbiemccorkell) on CodePen.

React:

See the Pen VYBbyN by Robbie (@robbiemccorkell) on CodePen.

You can see in the code above that the React implementation is pretty short, even with the markup defined in javascript. This is mostly because of the lack of linking functions connecting the code to the markup. React will just figure this out by itself. With all of this re-rendering of the markup every time something changes, you would think React would be quite slow, but it's not. For a demonstration of how React performs in comparison to other frameworks check out Ryan Florence's presentation from React conf.

This is an extremely simple and powerful way to build front-end applications. It combines the best of both worlds in a simple and easy interface for the programmer, and a performant experience for the user. It’s for this reason more than any other that React Native is an exciting new tool in native app development. It changes the way a programmer thinks in building the front-end of their app.

A sample React Native app

Tappy Button screenshotIn the talk I mentioned above I demonstrated some of my ground breaking research in video game technology with a game I created that I call Tappy Button. The objective of this game is to tap the button in the middle to increase your score.

The sample code below defines the full application seen in the screenshot including view structure, styling and application logic. What you should notice here is that the code is extremely unremarkable. It’s the same kind of React we know and love simply applied to a native app context, and that is what’s so remarkable about it. The only differences to traditional React web development are the element names1 and the inline styling2.

Building the same application in Xcode using Swift requires a similarly small amount of code, but it does require the developer to perform a process of clicking and dragging to create elements, constraints and method stubs in the code which quickly becomes tedious. As the application becomes more complex, the developer must manage collections of view controllers that manually update the view when required. But in React the view is declared once and all the developer must do is make sure the data inside each component changes when necessary. 

Other frameworks have crossed the JS-native divide in a similar way to React. NativeScript neatly gives developers direct access to native APIs in javascript3, and the creators of Titanium have been very vocal about the fact that they have provided similar javascript bridging and CSS styling for native apps for years. But all of the articles I’ve read that compare these frameworks are missing the biggest differentiator between React Native and the others, and that is React itself.

When discussing React Native, the ability to write native apps in javascript only really deserves a cursory mention in the discussion. What's really important here is that we can build native applications using the power of React.

React as the view engine

The important things in the future of React won't be more features, add-ons or utility libraries. Yes some improvements, optimisations and structural changes will be built in down the road, but I don't think Facebook want to overcomplicate something that works so brilliantly and simply already. 

We already have React being applied to different areas with React Native, and at React conf Netflix announced they were taking a similar approach, even applying React to embedded devices like TVs using their own custom built rendering engine. We've also heard that Flipboard have swapped out the DOM in favour of canvas elements in their latest web app to impressive results.

In the future we are going to see React applied to many different areas of front-end development by simply swapping the DOM and browser out for another view structure and rendering engine, whether that be mobile and desktop native elements, canvas, embedded devices, or who knows what. This will allow developers to use the power of React and its development patterns in any environment.  

Writing native applications for our phones is just the beginning, and it’s a direction I can stand behind. The biggest benefit of react native isn’t javascript. It’s React.

 

  1. The two base elements we can work with are 'View' and 'Text' and which act as block and inline elements respectively. Coming from the world of the DOM, we can simply translate 'div' to 'View' and 'span' to 'Text' and we’re basically good to go. Any other elements like 'TouchableHighlight' are utility components provided to us by React Native’s component library.

  2. Facebook have provided their own CSS based styling interpretation including their own clever implementation of Flexbox. We now write our styles as javascript objects and apply them inline to our view elements. Currently styles don’t seem to cascade, which is both an advantage and disadvantage depending on your use case. But the interesting thing about applying styles in this way is you have the full power of javascript at your fingertips. With a bit of forethought you could conceivably come up with clever systems to share global styles, and apply them to elements automatically in your application.

  3. I think NativeScript could be an interesting way to build react native bridges to native APIs, and we'll be experimenting with this in the future. However I’m still sceptical as to whether the overhead is worth it, and maybe if we want to build native bridges we should just learn the bloody language!

Red Badger are hiring. Come join us

23
Oct
2014

Badger Academy Week 8 – Frontend testing using WebdriverIO, Stubby and CucumberJS

by Tiago Azevedo

Over the past few weeks on Badger Time, we’ve had a steady workflow for the API where we followed TDD principles of writing feature tests first and code later. It wasn’t an issue to set that up in Rails as the various gems already out there for Ruby (RSpec/FactoryGirl specifically) made it a breeze.

The frontend was a different beast altogether and required quite a lot more thought which we finally decided to give over the past week.

The problems and their eventual solutions.

There were several problems which we struggled to solve initially. Firstly, we had to run a GhostDriver instance which would allow our testing suite to communicate with PhantomJS. We’d also have to run a Node server simultaneously which would serve the app in a test environment to the PhantomJS browser.

Doing this was a bit tricky; Gulp’s asynchronous nature meant that running those background processes from within Gulp was a no-go. Depending on how quickly or how slowly it launched, some tests would pass or fail as the server might not be up before the tests ran.

It was probably more effort than it was worth to find a workaround for it so we simply added the processes as a part of the container’s boot sequence. As our containers were based on Phusion BaseImage it was a case of adding simple init scripts to BaseImage’s custom init process.

start-stop-daemon --start --background --quiet --exec /bin/bash -- -c "/usr/bin/phantomjs --webdriver=8080 --remote-debugger-port=8081 --ignore-ssl-errors=true > /tmp/phantom.log"
start-stop-daemon --start --background --quiet --exec /bin/bash -- -c "node /data/server.js"

That was one catch out of the way. The next issue we faced was actually running the tests. Previously we took advantage of gulp-run to pipe our compiled spec files (we wrote the tests in LiveScript!) to the CucumberJS executable.

This was a bit overkill and we ended up just using Node’s script system to run the compile task then run the CucumberJS task on the appropriate files. As a side-effect, we got really nice formatting on the tests so we could see exactly what went wrong (if it failed).

Screen Shot 2014-10-20 at 11.16.47

Nice!

We had these tests running with the API endpoint set as a local Stubby mock API. Stubby’s Node implementation gave us a programmatic API which meant we could start, stop and modify the API as our tests were running.

This allowed us to feed data using Gherkin (Cucumber language) data tables to a function which would simply modify an endpoint with the supplied data. It removed our dependency on the real API to have the frontend tests working, which reduced our CircleCI build times from a staggering 15-20 minutes down to 2-3.

A look at WebdriverIO

Selenium WebDriver is somewhat of an elephant in the office at Red Badger. We all dislike it – even you Pete, you just don’t know it yet – but we put up with it. The API is just a bit rubbish and documentation is quite difficult to find. As somebody working out its usage from scratch, I can say my options were quite limited; spend hours sifting through Java documentation and hope it works the same in the JavaScript implementation or go through endless amounts of user issues trying to find a solution which matches my own problem.

That’s where WebdriverIO helped tremendously. It’s a JavaScript wrapper to Selenium’s confusing API and offers quite a few helpful additions of its own. Just having documentation – however incomplete it might be – was a godsend. At least the functions which weren’t documented have a link to their source so we can see what’s going on and extrapolate from that.

How LiveScript facilitates the callback-based nature of CucumberJS

If you’re familiar with the term ‘callback hell’ then you know how asynchronous code can be a real pain deal with, as you end up with nested logic inside nested logic inside a browser action, all ending with a callback to the top level to pass (or fail) the test. Take this simple example of a browser action which would type a phrase into an input on the screen. In JavaScript, we can immediately see why it quickly grows into something that isn’t nice to deal with.

We take advantage of LiveScript’s unnested callbacks to offer code which is functionally the same as the example above, but reads and writes like synchronous code (much easier to handle).

Writing our tests is inherently easy due to the way Cucumber works and in most cases we don’t even need to write any code for new features as we recycle logic from the more generic step definitions. 

We’re excited to finally be able to adhere to BDD principles on our frontend. After all, the whole premise of Badger Academy isn’t to ship a finished product, but to bring our code quality and knowledge to a higher level.