snabbdom-view

Infuse your snabbdom components with state

Usage no npm install needed!

<script type="module">
  import snabbdomView from 'https://cdn.skypack.dev/snabbdom-view';
</script>

README

snabbdom-view

Tests Stability Dependencies

Infuse your snabbdom components with "global" state.

Usage

So first lets assume we have this setup:

import xstream from "xstream"

function application (state) {
  return p({
    inner: `Hello, world! My name is ${state.author.name}`
  })
}

function cycle (sources) {
  const state = xstream.periodic(1000).of({author: {name: "Kurtis Rainbolt-Greene"}})

  return {
    DOM: state.map(application)
  }
}
const drivers = {
  DOM: makeDOMDriver("body")
}

run(cycle, drivers)

We'd see this rendered:

<body>
  <p>
    Hello, world! My name is Kurtis Rainbolt-Greene!
  </p>
</body>

But what if we want to get more complicated?. This is where snabbdom-view comes into play, it gives your components a "global" state that it can opt-into:

import {broadView} from "snabbdom-view"

function application () {
  return broadView((state) => p({
    inner: `Hello, world! My name is ${state.author.name}`
  }))
}

And now we make sure our state is passed correctly:

import {infuse} from "snabbdom-view"

function cycle (sources) {
  const state = xstream.periodic(1000).of({author: {name: "Kurtis Rainbolt-Greene"}})

  return {
    DOM: state.map(infuse(application()))
  }
}

Of course it's not great to receive all of state, so instead lets try getting only what we need:

import {specificView} from "snabbdom-view"

function application () {
  return specificView(
    {email: state => state.author.email}
  )(
    ({email}) => p({
      inner: `Hello, world! My name is ${email}`
    })
  )
}