cyclejs/cycle-core

View on GitHub
docs/content/documentation/basic-examples.md

Summary

Maintainability
Test Coverage
# Basic examples

## Common structure

Cycle.js apps will always include at least three important components: `main()`, **drivers**, and `run()`. In `main()`, we receive messages from drivers (sources, the input to `main`) and we send messages to drivers (sinks, the output of `main`).

**You can find the source code for these examples, and others, at [cyclejs/examples](https://github.com/cyclejs/cyclejs/tree/master/examples).**

`run()` ties `main()` and drivers together, as we saw in the last chapter. In the case of the DOM Driver, our `main()` will interact with the user through the DOM. Most of our examples will use the DOM Driver, but keep in mind that Cycle.js is modular and extensible. You could build an application, targeting Web Audio or native mobile for instance, without using the DOM Driver.

```javascript
function main(driverSources) {
  const driverSinks = {
    DOM: // transform driverSources.DOM
         // through a series of stream operators
  };
  return driverSinks;
}

const drivers = {
  DOM: makeDOMDriver('#app'),
};

run(main, drivers);
```

## Toggle a checkbox

Let's start with this `index.html` file, that should have an element dedicated to contain our application.

> Inside index.html

```html
<!-- html head goes here -->

<body>
  <div id="app"></div>
</body>
```

We will point our Cycle.js app to live inside `#app`. The `checkbox-app.js` file should look like this (before it is transpiled from ES6 to ES5, if that is required).

> checkbox-app.js

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  const sinks = {DOM: null};
  return sinks;
}

run(main, {
  DOM: makeDOMDriver('#app'),
});
```

Cycle *DOM* is a package containing two drivers and some helpers to use those libraries. A DOM Driver is created with `makeDOMDriver()` and an HTML Driver (for server-side rendering) is created with `makeHTMLDriver()`. Cycle DOM also includes `div()`, `h1()`, `h2()`, `input()`, `ul()`, `li()`, `svg()`, etc. These functions output virtual elements (also known as [*Virtual Nodes*](https://github.com/paldepind/snabbdom/#virtual-node) or *VNodes*). See [`snabbdom`](https://github.com/paldepind/snabbdom) docs for details.

Our `main()`, for now, does nothing. It takes driver `sources` and outputs driver `sinks`. To make something appear on the screen, we need to output a stream of VNode in `sinks.DOM`. The name `DOM` in `sinks` must match the name we gave in the drivers object given to `run()`. This is how Cycle.js knows which drivers to match with which sink streams. This is also true for sources: we listen to DOM events by using `sources.DOM`.

We just added a stream of `false` mapped to a VNode. [`xs.of(x)`](https://github.com/staltz/xstream#of) creates a stream which just emits `x` once. Then we use [`map()`](https://github.com/staltz/xstream#map) to convert that to the virtual DOM VNode containing an `<input type="checkbox">` and a `<p>` element displaying `off` if the `toggled` boolean is `false`, and displaying `ON` otherwise.

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, input, p, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  const sinks = {
    DOM: xs.of(false)
      .map(toggled =>
        div([
          input({attrs: {type: 'checkbox'}}), 'Toggle me',
          p(toggled ? 'ON' : 'off')
        ])
      )
  };
  return sinks;
}

run(main, {
  DOM: makeDOMDriver('#app'),
});
```

<a class="jsbin-embed" href="https://jsbin.com/robiyod/embed?output">JS Bin on jsbin.com</a>

This is nice: we can see the DOM elements generated by the virtual DOM elements created with `div()`, `input()`, and `p()`. But if we click the "Toggle me" checkbox, the label "off" under it does not change to "ON". That is because we are not listening to DOM events. In essence, our `main()` isn't listening to the *user*.

We do that by using `sources.DOM`, mapping `change` events on the checkbox to the `checked` value of the element (the first `map()`) to VNodes displaying that value. However, we need a [`.startWith()`](https://github.com/staltz/xstream#startWith) to give a default value to be converted to a VNode Stream. Without this, nothing would be shown! Why? Because our `sinks` is reacting to `sources`, but `sources` is reacting to `sinks`. If no one triggers the first event, nothing will happen. It is the same effect as meeting a stranger, and not having anything to say. Someone needs to take the initiative to start the conversation. That is what `main()` is doing: kickstarting the interaction, and then letting subsequent actions be mutual reactions between `main()` and the DOM Driver.

```diff
 import xs from 'xstream';
 import {run} from '@cycle/run';
 import {div, input, p, makeDOMDriver} from '@cycle/dom';

 function main(sources) {
   const sinks = {
-    DOM: xs.of(false)
+    DOM: sources.DOM.select('input').events('change')
+      .map(ev => ev.target.checked)
+      .startWith(false)
       .map(toggled =>
         div([
           input({attrs: {type: 'checkbox'}}), 'Toggle me',
           p(toggled ? 'ON' : 'off')
         ])
       )
   };
   return sinks;
 }

 run(main, {
   DOM: makeDOMDriver('#app')
 });
```

<a class="jsbin-embed" href="https://jsbin.com/makuye/embed?output">JS Bin on jsbin.com</a>

## HTTP requests

One of the most obvious requirements web apps normally have is to fetch and render data from the server. How would we build that with Cycle.js?

Suppose we have a backend with a database containing ten users. We want to have a front-end with one button "get a random user", and to display the user's details, like name and email. This is what we want to achieve:

<a class="jsbin-embed" href="https://jsbin.com/vedote/embed?output">JS Bin on jsbin.com</a>

Essentially we just need to make a request for the endpoint `/user/:number` whenever the button is clicked. Where would this HTTP request fit in a Cycle.js app?

*Sinks* are instructions from `main()` to drivers to perform side effects, and *sources* are readable side effects. HTTP requests are sinks, and HTTP responses are sources.

The [HTTP Driver](https://github.com/cyclejs/cyclejs/tree/master/http) is similar in style to the DOM Driver: it expects a sink stream (for requests), and gives you a source stream (for responses). Instead of studying the details of how the HTTP Driver works, let's see what a basic HTTP example looks like.

If HTTP requests are sent when the button is clicked, then the HTTP request stream should depend directly on the button click stream. `getRandomUser$` is the request stream we give to the HTTP Driver, by returning it as a sink in the `main()` function.

```javascript
function main(sources) {
  // ...
  const click$ = sources.DOM.select('.get-random').events('click');

  const getRandomUser$ = click$.map(() => {
    const randomNum = Math.round(Math.random() * 9) + 1;
    return {
      url: 'https://jsonplaceholder.typicode.com/users/' + String(randomNum),
      category: 'users',
      method: 'GET'
    };
  });

  // ...

  return {
    // ...
    HTTP: getRandomUser$,
  };
}
```

We still need to display data for the current user, and this comes only when we get an HTTP response. For that purpose, we need the stream of user data to depend directly on the HTTP response stream. This is available from `main`'s input: `sources.HTTP` (the name `HTTP` needs to match the driver name you gave for the HTTP driver when calling `run()`).

```javascript
function main(sources) {
  // ...

  const user$ = sources.HTTP.select('users')
    .flatten()
    .map(res => res.body);

  // ...
}
```

`sources.HTTP` is an "HTTP Source", representing all the network responses for this app. `select(category)` is an API specific to the HTTP Source that returns a stream of all response streams that are related to the `category` given. Because that output is a stream-of-streams, we apply `flatten()`, to get a flattened stream of responses. Check above for the declaration of `getRandomUser$` where we returned a request object with a `category: users` field. This might feel like magic right now, so read the [HTTP Driver docs](https://github.com/cyclejs/cyclejs/tree/master/http) if you're curious about the details. We map each response `res` to `res.body` in order to get the JSON data from the response and ignore other fields like HTTP status.

We still haven't specified how to render our app. We should display to the DOM whatever data we have from the current user in `user$`. So the VNode stream called `vdom$` should depend directly on `user$`.

```javascript
function main(sources) {
  // ...
  const vdom$ = user$.map(user =>
    div('.users', [
      button('.get-random', 'Get random user'),
      div('.user-details', [
        h1('.user-name', user.name),
        h4('.user-email', user.email),
        a('.user-website', {href: user.website}, user.website)
      ])
    ])
  );
  // ...
}
```

However, initially, there won't be any `user$` event, because those only happen when the user clicks. This is the same "conversation initiative" problem we saw in the previous "checkbox" example. So we need to make `user$` start with a `null` user, and in case `vdom$` sees a null user, it renders just the button. Otherwise, if we have real user data, we also display their name, their email, and website.

```diff
 function main(sources) {
   // ...

   const user$ = sources.HTTP.select('users')
     .flatten()
     .map(res => res.body)
+    .startWith(null);

   const vdom$ = user$.map(user =>
     div('.users', [
       button('.get-random', 'Get random user'),
-      div('.user-details', [
+      user === null ? null : div('.user-details', [
         h1('.user-name', user.name),
         h4('.user-email', user.email),
         a('.user-website', {href: user.website}, user.website)
       ])
     ])
   );

   // ...
 }
```

We give `vdom$` to the DOM Driver, and it renders those for us.
When done, the whole code looks like this.

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, button, h1, h4, a, makeDOMDriver} from '@cycle/dom';
import {makeHTTPDriver} from '@cycle/http';

function main(sources) {
  const getRandomUser$ = sources.DOM.select('.get-random').events('click')
    .map(() => {
      const randomNum = Math.round(Math.random() * 9) + 1;
      return {
        url: 'https://jsonplaceholder.typicode.com/users/' + String(randomNum),
        category: 'users',
        method: 'GET'
      };
    });

  const user$ = sources.HTTP.select('users')
    .flatten()
    .map(res => res.body)
    .startWith(null);

  const vdom$ = user$.map(user =>
    div('.users', [
      button('.get-random', 'Get random user'),
      user === null ? null : div('.user-details', [
        h1('.user-name', user.name),
        h4('.user-email', user.email),
        a('.user-website', {attrs: {href: user.website}}, user.website)
      ])
    ])
  );

  return {
    DOM: vdom$,
    HTTP: getRandomUser$
  };
}

run(main, {
  DOM: makeDOMDriver('#app'),
  HTTP: makeHTTPDriver()
});
```

<a class="jsbin-embed" href="https://jsbin.com/vedote/embed?output">JS Bin on jsbin.com</a>

## Increment a counter

We saw how to use the *sources and sinks* pattern of building user interfaces, but our examples didn't have state: the label just reacted to the checkbox event, and the user details view just showed what came from the HTTP response. Normally applications have state in memory, so let's see how to build a Cycle.js app for that case.

If we have a counter stream (emitting events to tell the current counter value), displaying the counter is as simple as this.

```javascript
count$.map(count =>
  div([
    button('.increment', 'Increment'),
    button('.decrement', 'Decrement'),
    p('Counter: ' + count)
  ])
)
```

> ### What is the `$` convention?
>
> Notice we used the name `count$` for the stream of current counter values. The dollar sign `$` *suffixed* to a name is a soft convention to indicate that the variable is a stream. It is a naming helper to indicate types.
>
> Suppose you have a stream of VNode depending on a stream of "name" strings
>
> `const vdom$ = name$.map(name => h1(name));`
>
> Notice that the function inside `map` takes `name` as an argument, while the stream is named `name$`. The naming convention indicates that `name` is the value being emitted by `name$`. In general, `foobar$` emits `foobar`. Without this convention, if `name$` would be named simply `name`, it would confuse readers about the types involved. Also, `name$` is succinct compared to alternatives like `nameStream`, `nameObservable`, or `nameObs`. This convention can also be extended to arrays: use plurality to indicate the type is an array. Example: `vdoms` is an array of `vdom` but `vdom$` is a stream of `vdom`.

But how do we create a `count$`? Clearly it must depend on increment clicks and decrement clicks. The former should mean a "+1" operation, and the latter a "-1" operation.

```javascript
const action$ = xs.merge(
  DOM.select('.decrement').events('click').mapTo(-1),
  DOM.select('.increment').events('click').mapTo(+1)
);
```

The [`merge`](https://github.com/staltz/xstream#merge) operator allows us to get an event stream of actions, either increment or decrement actions. In this sense, `merge` has *OR* semantics. But this still isn't a `count$`. It is just an `action$`.

`count$` should begin with zero and should later be the sum of all the numbers emitted by `action$`. To join all events on a stream over time, we use the operator [`fold()`](https://github.com/staltz/xstream#fold):

```js
const count$ = action$.fold((x, y) => x + y, 0);
```

What does `fold` do? It is similar to [`reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce), allowing us to accumulate values over the sequence. Also, `fold` has some `startWith` behavior included, because it takes a `seed` argument (we gave the number `0`) and emits that initially.

![fold counter](img/fold-counter.svg)

If we put `action$` and `count$` together in our `main()`, we can implement the counter like this:

<a class="jsbin-embed" href="https://jsbin.com/husiyul/embed?output">JS Bin on jsbin.com</a>

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, button, p, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  const action$ = xs.merge(
    sources.DOM.select('.dec').events('click').mapTo(-1),
    sources.DOM.select('.inc').events('click').mapTo(+1)
  );

  const count$ = action$.fold((x, y) => x + y, 0);

  const vdom$ = count$.map(count =>
    div([
      button('.dec', 'Decrement'),
      button('.inc', 'Increment'),
      p('Counter: ' + count)
    ])
  );

  return {
    DOM: vdom$
  };
}

run(main, {
  DOM: makeDOMDriver('#app')
});
```

## Body mass index calculator

Now that we've got the hang of Cycle.js apps with state, let's tackle something a bit larger. Consider the following [BMI](https://en.wikipedia.org/wiki/Body_mass_index) calculator: it has a slider to select the weight, a slider to select the height, and the text indicates the calculated BMI from the weight and height values selected.

<a class="jsbin-embed" href="https://jsbin.com/nucepu/embed?output">JS Bin on jsbin.com</a>

In the previous example, we had the actions *decrement* and *increment*. In this example, we have "change weight" and "change height". These seem straightforward to implement.

```javascript
const changeWeight$ = sources.DOM.select('.weight')
  .events('input')
  .map(ev => ev.target.value);

const changeHeight$ = sources.DOM.select('.height')
  .events('input')
  .map(ev => ev.target.value);
```

By now we know that app state is usually initialized with `startWith` or `fold`. We need the *height* and *weight* as *values over time*, not as *change events*. In order to represent *height* as state, we just need to give an initial value prepended to `changeHeight$`.

```javascript
const weight$ = changeWeight$.startWith(70);
const height$ = changeHeight$.startWith(170);
```

To combine these two pieces of state and use their values to compute the BMI, we use the xstream [`combine`](https://github.com/staltz/xstream#combine) operator. We saw in the previous example that `merge` had *OR* semantics. `combine` has, on the other hand, *AND* semantics. For instance, to compute the BMI, we need a `weight` value *AND* a `height` value. `combine` takes **multiple** streams as input, and produces **one** stream of arrays that contain **multiple** values, one for each input stream.

```javascript
const bmi$ = xs.combine(weight$, height$)
  .map(([weight, height]) => {
    const heightMeters = height * 0.01;
    return Math.round(weight / (heightMeters * heightMeters));
  });
  ```

Now we just need a function to visualize the BMI result and the sliders. We do that by mapping `bmi$` to a stream of VNode, and giving that to the `DOM` driver.

<a class="jsbin-embed" href="https://jsbin.com/wojokof/embed?output">JS Bin on jsbin.com</a>

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, input, h2, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  const changeWeight$ = sources.DOM.select('.weight')
    .events('input')
    .map(ev => ev.target.value);

  const changeHeight$ = sources.DOM.select('.height')
    .events('input')
    .map(ev => ev.target.value);

  const weight$ = changeWeight$.startWith(70);
  const height$ = changeHeight$.startWith(170);

  const bmi$ = xs.combine(weight$, height$)
    .map(([weight, height]) => {
      const heightMeters = height * 0.01;
      return Math.round(weight / (heightMeters * heightMeters));
    });

  const vdom$ = bmi$.map(bmi =>
    div([
      div([
        'Weight ___kg',
        input('.weight', {attrs: {type: 'range', min: 40, max: 140}})
      ]),
      div([
        'Height ___cm',
        input('.height', {attrs: {type: 'range', min: 140, max: 210}})
      ]),
      h2('BMI is ' + bmi)
    ])
  );

  return {
    DOM: vdom$
  };
}

run(main, {
  DOM: makeDOMDriver('#app')
});
```

This code works. We can get the calculated BMI when we move the slider. However, maybe you noticed, the labels for weight and height do not show what the slider is selecting. Instead, they just show e.g. `Weight ___kg`, which is useless since we do not know what value we are choosing for the weight.

The problem happens because when we map on `bmi$`, we do not have the `weight` and `height` values anymore. Therefore, for the function which renders the VNode, we need to use a stream which emits a complete amount of data instead of just BMI data. We need a `state$`.

```javascript
const state$ = xs.combine(weight$, height$)
  .map(([weight, height]) => {
    const heightMeters = height * 0.01;
    const bmi = Math.round(weight / (heightMeters * heightMeters));
    return {weight, height, bmi};
  });
  ```

Below is the program that uses `state$` to render all dynamic values correctly to the DOM.

<a class="jsbin-embed" href="https://jsbin.com/nucepu/embed?output">JS Bin on jsbin.com</a>

```javascript
import xs from 'xstream';
import {run} from '@cycle/run';
import {div, input, h2, makeDOMDriver} from '@cycle/dom';

function main(sources) {
  const changeWeight$ = sources.DOM.select('.weight')
    .events('input')
    .map(ev => ev.target.value);

  const changeHeight$ = sources.DOM.select('.height')
    .events('input')
    .map(ev => ev.target.value);

  const weight$ = changeWeight$.startWith(70);
  const height$ = changeHeight$.startWith(170);

  const state$ = xs.combine(weight$, height$)
    .map(([weight, height]) => {
      const heightMeters = height * 0.01;
      const bmi = Math.round(weight / (heightMeters * heightMeters));
      return {weight, height, bmi};
    });

  const vdom$ = state$.map(({weight, height, bmi}) =>
    div([
      div([
        'Weight ' + weight + 'kg',
        input('.weight', {attrs: {type: 'range', min: 40, max: 140, value: weight}})
      ]),
      div([
        'Height ' + height + 'cm',
        input('.height', {attrs: {type: 'range', min: 140, max: 210, value: height}})
      ]),
      h2('BMI is ' + bmi)
    ])
  );

  return {
    DOM: vdom$
  };
}

run(main, {
  DOM: makeDOMDriver('#app')
});
```

Great, this program functions exactly like we want it to. Weight and height labels react to the sliders being dragged, and the BMI result gets recalculated as well.

However, we wrote all the code inside one function: `main()`. This approach doesn't scale, and even for a small app like this, it already looks too large and is doing too many things.

We need a proper architecture for user interfaces that follows the reactive, functional, and cyclic principles of Cycle.js. This is the subject of our [next chapter](model-view-intent.html).