Created
June 12, 2019 03:26
-
-
Save sergey-shpak/ff87e56e03dc16c8ee24dc562c6f7dff to your computer and use it in GitHub Desktop.
Hyperapp#2 Lifecycle HOC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Working example https://codepen.io/sergey-shpak/pen/pXvwod