Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created February 22, 2018 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/0278fce25112d70297a74b5bf5d57d6b to your computer and use it in GitHub Desktop.
Save barneycarroll/0278fce25112d70297a74b5bf5d57d6b to your computer and use it in GitHub Desktop.
A collection of view components for Mithril. A view component is one where the component provides no view of its own but instead accepts a view attribute which it then provides with data.

Mithril view component sample

Blocker

Used to define the relationship between an ancestor and one or more siblings, ensuring the siblings' onbeforeremove hooks will be invoked when the ancestor is scheduled for removal, and will all resolve before the ancestor is removed. See here.

PromiseState

Consumes a promise and a view, provides promise a state data object reflecting the promise to the view, consisting of ({data, error, pending}). See here.

const callOBR = v =>
Promise.all(
['tag', 'attrs']
.map(x =>
v[x]
&& v[x].onbeforeremove
&& v[x].onbeforeremove.call(v.state, v)
)
)
const findOBR = v => {
while (v.length || !(v.tag.onbeforeremove || v.attrs && v.attrs.onbeforeremove))
v = v.instance || v.children || v[0]
return v
}
const persist = v => {
var target = findOBR(v.instance || v.children)
if (v.attrs.link)
v.attrs.link.set(target.dom, target)
}
function Blocker(){
const link = new Map
return {
view : v => (
v.attrs.view
?
v.attrs.view(link)
:
v.children
),
oncreate: persist,
onupdate: persist,
onremove: v => {
if (v.attrs.link)
v.attrs.link.delete(v.dom)
},
onbeforeremove: () =>
Promise.all(
[...link.values()].map(callOBR)
),
}
}
const PromiseState = v => {
let data, error, pending = true
v.attrs.promise.then(
x => (data = x, pending = false, m.redraw()),
x => (error = x, pending = false, m.redraw())
)
return {
view : v =>
v.attrs.view({data, error, pending}),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment