mithril-cc

An opinionated library for writing Mithril components

Usage no npm install needed!

<script type="module">
  import mithrilCc from 'https://cdn.skypack.dev/mithril-cc';
</script>

README

mithril-cc

An opinionated library for writing Mithril.js components.

Motivation

Mithril is the leader and forerunner of declarative HTML views in plain old JavaScript. However, its flourishing flexibility can leave one uneasy on the "right" way to do things. The wide array of available options all have different pros and cons that depend on the type of component you're writing.

To cure, CC compresses these options into a pleasant, one-size-fits-all approach, allowing you to trade discouraging decision fatigue for simple peace and tranquility.

In other words: Closure components are the epitome of userland Mithril, and CC brings out the best in them.

Getting Started

yarn add mithril-cc
# or
npm install mithril-cc

In your component files:

import {cc} from 'mithril-cc'

Using a CDN

If you use a CDN, mithril-cc will be available via m.cc, m.ccs, etc.

<script src="https://unpkg.com/mithril/mithril.js"></script>
<script src="https://unpkg.com/mithril/stream/stream.js"></script>
<script src="https://unpkg.com/mithril-cc"></script>

TypeScript

For type inference, simply parameterize your cc calls:

type Attrs = {
  initialCount: number
}
const Counter = cc<Attrs>(/* ... */)

Learn by Example

Simple Counter

State in a cc closure component is as simple as you could ever hope for. Set some variables, return a view thunk, and you're ready to go.

import m from 'mithril'
import {cc} from 'mithril-cc'

const Counter = cc(function(){
  let n = 0
  return () => [
    m('p', 'Count: ', n),
    m('button', { onclick: () => n++ }, 'Inc')
  ]
})

Live demo

View Attrs

For convenience, Mithril's vnode.attrs are made available directly as the first parameter to your view thunk.

const Greeter = cc(function(){
  return (attrs) => (
    m('p', `Hello, ${attrs.name}!`)
  )
})

Live demo

In case you need it, vnode is provided as a second parameter.

Component Setup

Sometimes you need to set up state when your component gets initalized. CC provides your component with attrs as a stream. Note how this is different from your view thunk, which receives attrs directly (as a non-stream).

Because it's a stream, your setup callbacks always have access to the latest value of you component's attrs.

const Counter = cc(function($attrs){
  let n = $attrs().initialCount
  return () => [
    m('p', 'Count: ', n),
    m('button', { onclick: () => n++ }, 'Inc')
  ]
})

Live demo

Reacting to Attrs Changes

Because top-level attrs is a stream, you can easily react to changes using .map.

Note also the this.unsub = in this example. This will clean up your stream listener when the component unmounts. You can assign it as many times as you like; CC will remember everything.

import {cc, uniques} from 'mithril-cc'

const Greeter = cc(function($attrs){
  let rank = 0
  let renderCount = -1
  this.unsub = $attrs.map(a => a.name).map(uniques()).map(n => rank++)
  this.unsub = $attrs.map(() => renderCount++)

  return (attrs) => (
    m('p', `Hello, ${attrs.name}! You are person #${rank} (renderCount ${renderCount})`)
  )
})

Live demo

Implementation detail: Because the $attrs stream gets updated before the view thunk, your view thunk will see the latest and correct version of your closure variables.

Unsubscribe

If CC doesn't cover your cleanup use case, you can assign this.unsub = to any function. CC will run the function when the component unmounts.

const UnmountExample = cc(function(){
  this.unsub = () => console.log("unmount")
  return () => m('div', 'UnmountExample')
})

Live demo

Lifecycle Methods

Even though you're using view thunks, you still have access to all of Mithril's lifecycles via this. You can even call oncreate and onupdate multiple times, which can be useful for creating React Hooks-like abstractions.

const HeightExample = cc(function(){
  let height = 0
  this.oncreate(vnode => {
    height = vnode.dom.offsetHeight
    m.redraw()
  })
  return () => m('p', `The height of this tag is ${ height || '...' }px`)
})

Live demo

addEventListener

Often times you need to listen for DOM events. With this.addEventListener, CC will automatically clean up your listener when the component unmounts. It will also call m.redraw() for you.

const MouseCoords = cc(function(){
  let x = 0, y = 0

  this.addEventListener(window, 'mousemove', event => {
    x = event.offsetX, y = event.offsetY
  })
  return () => m('p', `Mouse is at ${x}, ${y}`)
})

Live demo

setTimeout and setInterval

Just like this.addEventListener, you can use this.setTimeout and this.setInterval to get auto cleanup and redraw for free.

const Delayed = cc(function(){
  let show = false
  this.setTimeout(() => {
    show = true
  }, 1000)
  return () => m('p', `Show? ${show}`)
})

Live demo

const Ticker = cc(function(){
  let tick = 0
  this.setInterval(() => tick++, 1000)
  return () => m('p', `Tick: ${tick}`)
})

Live demo

React Hooks-like Abstractions

Because CC's this has everything you need to manage a component, you can abstract setup and teardown behavior like you would using React hooks.

For example, we can refactor the MouseEvents example into its own function:

import {cc} from 'mithril-cc'
import Stream from 'mithril/stream'

const MouseCoords = cc(function(){
  let [$x, $y] = useMouseCoords(this)
  return () => m('p', `Mouse is at ${$x()}, ${$y()}`)
})

function useMouseCoords(ccx) {
  const $x = Stream(0), $y = Stream(0)

  ccx.addEventListener(window, 'mousemove', event => {
    $x(event.offsetX); $y(event.offsetY)
  })

  return [$x, $y]
}

Live demo

Shorthand Components

If you only need attrs and nothing else, you can use ccs.

import {ccs} from 'mithril-cc'

const Greeter = ccs(attrs => (
  m('p', `Hello, ${attrs.name}!`)
)