Home

Awesome

mutant

Create observables and map them to DOM elements. Massively inspired by hyperscript and observ-*.

No virtual DOM, just direct observable bindings. Unnecessary garbage collection is avoided by using mutable objects instead of blasting immutable junk all over the place.

Current Status: Experimental / Maintained

Expect breaking changes.

Used By

Install

npm install mutant --save

Compatibility

Requires an environment that supports:

Example

var h = require('mutant/html-element')
var Struct = require('mutant/struct')
var send = require('mutant/send')
var computed = require('mutant/computed')
var when = require('mutant/when')

var state = Struct({
  text: 'Test',
  color: 'red',
  value: 0
})

var isBlue = computed([state.color], color => color === 'blue')

var element = h('div.cool', {
  classList: ['cool', state.text],
  style: {
    'background-color': state.color
  }
}, [
  h('div', [
    state.text, ' ', state.value, ' ', h('strong', 'test')
  ]),
  h('div', [
    when(isBlue,
      h('button', {
        'ev-click': send(state.color.set, 'red')
      }, 'Change color to red'),
      h('button', {
        'ev-click': send(state.color.set, 'blue')
      }, 'Change color to blue')
    )

  ])
])

setTimeout(function () {
  state.text.set('Another value')
}, 5000)

setInterval(function () {
  state.value.set(state.value() + 1)
}, 1000)

setInterval(function () {
  // bulk update state
  state.set({
    text: 'Retrieved from server (not really)',
    color: '#FFEECC',
    value: 1337
  })
}, 10000)

document.body.appendChild(element)

Types

Observables that store data

Value

The classic observable - stores a single value, updates listeners when the values changes.

var Value = require('mutant/value')

var obs = Value()
obs.set(true)
//set listener
obs(value => { 
  // called with resolved value whenever the observable changes
})

This is almost the same as observable and observ. There's only a couple of small differences: you can specify a default value (fallback when null) and it will throw if you try and add a non-function as a listener (this one always got me)

Array

An observable with additional array like methods, which update the observable. The array items can be ordinary values or observables.

Like observ-array but as with struct, emits the same object. No constant shallow cloning on every change. You can push observables (or ordinary values) and it will emit whenever any of them change. Works well with mutant/map.

There's also mutant/set which is similar but only allows values to exist once.

additional methods:

Dict

The complement to Struct - but instead of representing a fixed set of sub-observables, it's a single observable which you can add sub-keys to.

var Dict = require('mutant/dict')
var d = Dict()
d.put('key', 1)
d(function (v) {
  // => {key: 1}
})

additional methods:

Set

Represents a collection like Array except without ordering or duplicate values.

additional methods:

Struct

Take a fixed set of observables (or values) and return a single observable of the observed values, which updates whenever the inner values update. Subobservables can by any observable type.

They also have a set function which can be used to push a json object into the nested observables. Any additional set keys will be preserved if you resolve it.

Mostly the same as observ-struct except that it always emits the same object (with the properties changed). This means it violates immutability, but the trade-off is less garbage collection. The rest of the mutant helpers can handle this case pretty well.

They accept a set list of keys that specify types. For example:

var struct = MutantStruct({
  description: Value(),
  tags: MutantSet(),
  likes: Value(0, {defaultValue: 0}),
  props: MutantArray(),
  attrs: MutantDict()
})

You can use these as your primary state atoms. I often use them like classes, extending them with additional methods to help with a given role.

Another nice side effect is they work great for serializing/deserializing state. You can call them with JSON.stringify(struct()) to get their entire tree state, then call them again later with struct.set(JSON.parse(data)) to put it back. This is how state and file persistence works in Loop Drop.

MappedArray

...

MappedDict

...

TypedCollection

This is similar to MappedArray, except with key checking. You can specify a matcher option to define how to decide that two objects are the same (defaults to (rawValue) => rawValue.id), and now any time set is called, instances with the same matcher result will be updated instead of recreated even if the order has changed. This is really useful when turning a collection into DOM elements, and reordering can happen remotely and you are just syncing the entire state every time.

var state = Struct({
  models: TypedCollection(YourModel, {
    matcher: (value) => value.id
  })
})

function YourModel () {
  return Struct({
    id: Value(),
    tags: MutantSet(),
    options: Dict()
  }) 
}

The constructor is called with the rawValue of the object, however you don't need to use this to populate the object as it will also be called with .set. This is just to allow polymorphic typing checks:

var types = {
  Cat () {
    return Struct({
      id: Value(),
      age: Value(),
      ...props
    }) 
  },
  Dog () {
    return Struct({
      id: Value(),
      age: Value(),
      ...props
    }) 
  }
}

var state = Struct({
  pets: TypedCollection((value) => types[value.type](), {
    matcher: (value) => value.id,
    invalidator: (current, newValue) => current.type != newValue.type,
    onAdd: (obj) => console.log('added', resolve(obj)),
    onRemove: (obj) => console.log('removed', resolve(obj)),
  })
})

state.set({
  pets: [
    {id: 1, age: 2, type: 'Dog'},
    {id: 2, age: 9, type: 'Cat'}
  ]
})
// => added {id: 1, type: 'Dog'}
// => added {id: 2, type: 'Cat'}

state.set({
  pets: [
    {id: 2, age: 9, type: 'Cat'},
    {id: 1, age: 3, type: 'Dog'}
  ]
})
// the inner models are updated and order changed, but no new cats/dogs are created

state.set({
  pets: [
    // somehow our dog has turned into a cat!
    // even though the cat has the same ID as the dog, the original object is discarded, and a new one constructed as invalidator returns true
    {id: 1, age: 3, type: 'Cat'},
    {id: 2, age: 9, type: 'Cat'}
  ]
})
// => removed {id: 1, type: 'Dog'}
// => added {id: 1, type: 'Cat'}

ProxyType

A more advanced feature - allow you to create observable slots which allow you to hot-swap observables in/ out of.

ProxyCollection

...

ProxyDictionary

...

Proxy

...


Transforms

Take one or more observables and transform them into an observable

computed

Take an array of observables, and map them through a function that to produce a custom observable.

//observable that is true if A or B are true

var computed = require('mutant/computed')

var aOrB = computed([a, b], (a, b) => { 
  return a || b 
})

Once again, similar to the observ and observable implementations. It has a few key differences though.

map

Apply a function to the value in another observable and update whenever that observable updates. Like computed, but for only one input.

A through transform. It won't do any work and won't listen to its parents unless it has a listener. Calls your function with the original observable object (not the resolve value). You can then return an additional observable value as its result. It has methods on it that make it behave like an array.

One of the most interesting features is its maxTime option. This is a ms value that specifies the max time to spend in a tight loop before emit the changes so far. This makes rendering large datasets to DOM elements much more responsive - a lot more like how the browser does it when it parses html. Things load in little chunks down the page. This for me has made it much easier to build apps that feel responsive and leave the main thread available for more important things (like playing sound).

concat

...

dictToCollection

...

idleProxy

...

keys

...

lookup

...

merge

Merges

reverse

var reverse = require('mutant/reverse')
var reversed = reverse(collection)

Takes an input collection and reverses it. This preserves the raw observables (which is what makes it better than computed).

throttle

...

when

var when = require('mutant/when')

when(
  obs,
  A,      // if true
  B       // if false (optional)
)
// => observable

Behaves like an observable ternary.

Take an observable obs and return the second argument A if obs is truthy. An optional third argument B can be passed and will return if obs is falsey.


Sinks

Stuff that are exit hatches / sinks / make changes in the real world.

HtmlElement / h

var textAlign = Value('center')
var someText = Value('some text')
var element = h('div', {style: {'text-align': textAlign}}, [
  h('p.text', someText),
  h('p.text', [
    'Text with ', h('strong', 'formatting'), ' and a ', h('a', {href: '/url'}, 'hyperlink')
  ]),
])

A fancy wrapper around document.createElement() that allows you to create DOM elements (entire trees if needed) without setting lots of properties or writing html. It just returns plain old DOM elements that can be added directly to the DOM.

This follows hyperscript syntax: h('tagName', {...properties}, [childNodes]). The properties section is optional.

You can add observables as properties and when the observable value changes, the DOM magically updates. You can also return one or more DOM elements. Cleanup is automatic (when removed from DOM using MutationObserver). It's a lot like pull streams: the DOM acts as a sink. If an element created by mutant is not in the DOM, it doesn't listen to its observable properties. It only resolves them once it is added, and if it is removed unlistens again.

Properties

It is important to note that you are specifying properties not attributes. So you use the DOM name instead of the HTML name. For example className instead of class. Or playsInline instead of playsinline. Check out this stack overflow topic for more info: What is the difference between properties and attributes in HTML?.

Almost all of the properties work the same way they do when create DOM elements using document.createElement, but there are a few special differences:

You can also specify an intersectionBindingViewport on scrolling elements if you would like the elements to only be bound (live) when they are in the viewport. You can specify true or {rootMargin: VALUE}. See Intersection Observer API - rootMargin for details.

Events

As mentioned above, you can't use the onclick style events, instead you must add them using events or ev-click style handlers. This is equivalent to element.addEventListener.

var element = h('div', {
  events: {
    click: function (ev) {
      // this works just like the handler on addEventListener
    }
  }
})

Or using shorthand:

var element = h('div', {
  'ev-click': function (ev) {
    // this works just like the handler on addEventListener
  }
)

However this method can use a lot of memory if you are adding events to many different elements. If the event handlers are the same, but specified inline every time, this is a waste. Here's how you can optimise this with send:

var send = require('mutant/send') // or const {h, send} = require('mutant')

var element = h('div', {
  'ev-click': send(sharedHandler, {options})
)

function sharedHandler (options) {
  // handle the event here
  // send already calls `preventDefault`
  // you can access the raw event using this.event
}

Hooks

Hooks allow you to add special behaviors to elements. You can use the for data-binding, or custom components, or even merging in other view/templating libraries.

Please note that hooks are not run until the element is actually in the DOM. If the same element is added and removed, the hooks will be run multiple times.

In this example, we use hooks to bind an input element to state:

var h = require('mutant/h')
var watch = require('mutant/watch')
var Value = require('mutant/value')
var watchEvent = require('mutant/watch-event')

var value = Value('default')
var input = h('input', {type: 'text', hooks: [ValueHook(value)]})

function ValueHook (observable) {
  return function (element) {
    // this function is run when the element is added to the DOM
    var unwatch = watch(observable, function (value) {
      element.value = value
    })

    var unwatchElement = watchEvent(element, 'input', function () {
      observable.set(element.value)
    })

    return function onRemove () {
      // this function is called when the element is removed from the DOM
      // we'll use it to clean up our event handlers
      unwatch()
      unwatchElement()
    }
  }
}

SvgElement / svg

Very similar to h above, except works for svg elements.

const { svg } = require('mutant')
let element = svg('svg', { width: 400, height: 300 }, [
  svg('circle', { fill: 'lime', cx: 100, cy: 250, r: 20 }),
  svg('rect', { fill: 'red', x: 50, y: 50, width: 300, height: 100 })
])
document.body.append(element)

watch

const {Value, watch} = require('mutant')

var obs = Value('observable')

// immediately logs out the current value
var unwatch = watch(obs, (value) => {
  console.log(value)
})

// logs out again
obs.set('new value')

// stop watching
unwatch()

// this no longer logs out
obs.set('new value')

// watching a non observable object just runs once
var notObs = 'plain old value'
watch(notObs, (value) => {
  console.log(value)
})

watchAll

Just like watch, except you can provide an array of values to watch and they will all be outputted. Kind of like computed.

watchThrottle

Just like watch except has an additional `throttle' param that allows you to prevent the watcher from being called faster than the specified duration.

var value = Value()

// change the value once every 50ms
setInterval(() => {
  value.set(Date.now())
}, 50)

watchThrottle(value, 200, (v) => {
  // only called a maximum of once every 200 ms
})

Helpers

A grab bag of useful things for dealing with mutant stuff. A lot of these are used internally, but are useful more generally

channel

Creates an observable like object for broadcasting events with no permanent state.

  var channel = MutantChannel()
  var unwatch = channel.listen((value) => {
    console.log(value) // => value
  })
  channel.broadcast('value')

forEach

You can run this on ordinary or observable objects, and it will loop over every item. Mostly just a convenience function to make it easier to work with different kinds of objects (almost but not quite resolve(obj).forEach).

forEachPair

Like forEach above, except can be used on Dict / lookup objects to loop over every key and value pair.

isObservable

Returns true if the provided object is likely to be an observable. This isn't a perfect check however, as observables in mutant are defined as functions that have exactly one argument.

const {Value, isObservable} = require('mutant')
var obs = Value('observable')
var notObs = 'plain old value'

isObservable(obs) // => true
isObservable(notObs) // => true

// WATCH OUT
isObservable(isObservable) // => true (YES, THAT's RIGHT, WATCH OUT FOR THIS!!! Functions with a single argument are detected as observables -- hopefully addressed with a big mutant rewrite one day)

onceIdle

delay a function until the next idle callback without hammering the requestIdleCallback api

var onceIdle = require('mutant/once-idle')
onceIdle(function () {
  //called once, at some later point (after rendering and such)
})

resolve

A convenience function that gets the value of an observable, or just returns the value if not an observable. Handy when you don't know if the value you are dealing with is an observable or not.

const {Value, resolve} = require('mutant')

function printValue (valueOrObservable) {
  console.log(resolve(valueOrObservable))
}

// both of these print out their values
printValue('Hello')
printValue(Value('world'))

watchAnimationFrame

A convenience wrapper around window.requestAnimationFrame. Quickly set up an animation loop (listener gets called every frame), and returns a function that can be called to stop the loop. Very useful with hooks.

var watchAnimationFrame = require('mutant/watch-animation-frame') // or const {watchAnimationFrame, h} = require('mutant')
var unwatch = watchAnimationFrame(element, 'click', function (ev) {
  // this is called ~60 times a second!
})

// until you call the unwatch function, which stops the loop:
unwatch()

watchEvent

A convenience wrapper around element.addEventListener. Allows you to observe an event changing, but returns a function that can be called to remove the event handler. Very useful with hooks.

var watchEvent = require('mutant/watch-event') // or const {watchEvent, h} = require('mutant')
var element = h('div', 'Hello!')
var unwatch = watchEvent(element, 'click', function (ev) {
  // do stuff
})

// clean up event handler
unwatch()

See the hooks example above under HtmlElement for more a more realistic use case!

send

Used to create memory efficient event handlers. See Events example under HtmlElement.


License

MIT