Skip to content

Instantly share code, notes, and snippets.

@sergey-shpak
Created June 12, 2019 03:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergey-shpak/ff87e56e03dc16c8ee24dc562c6f7dff to your computer and use it in GitHub Desktop.
Save sergey-shpak/ff87e56e03dc16c8ee24dc562c6f7dff to your computer and use it in GitHub Desktop.
Hyperapp#2 Lifecycle HOC
const {h, app} = hyperapp // @jsx h
// Effect for element side-effects
const fx = a => (...b) => [a, b]
const withElement = fx((dispatch, [element, props], action) => {
Object.keys(props).map(k => props[k] && element[k]())
action && dispatch(action)
})
// Decoder to get 'event.detail'
const eventDetail = event => event.detail
// Focus action,
// returns effect, because focusing element is a side-effect
const focus = (state, element) =>
[state, withElement(element, { focus: true })]
app({
init: () => {},
view: state => <div>
<Lifecycle>
<input type='text' oncreate={[focus, eventDetail]} />
</Lifecycle>
</div>,
node: document.body
})
/* Simple helper to emulate Hyperapp#2 lifecycle events */
import { h } from 'hyperapp'
const dispatchEvent = (event, target) =>
setTimeout(()=> target.dispatchEvent(
new CustomEvent(event, { detail: target })
))
const defineElement = name => {
customElements.get(name) ||
customElements.define(name, class extends HTMLElement {
appendChild(child){
super.appendChild(child)
dispatchEvent('create', child)
return child
}
removeChild(child){
super.removeChild(child)
dispatchEvent('remove', child)
return child
}
})
}
export const Lifecycle = (props, child) =>
(defineElement('ha-lifecycle'), <ha-lifecycle>{ child }</ha-lifecycle>)
@sergey-shpak
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment