Skip to content

Instantly share code, notes, and snippets.

@okwolf
Last active December 3, 2018 09:39
Show Gist options
  • Save okwolf/d38773ae51c0837ba73dad1e3e348b83 to your computer and use it in GitHub Desktop.
Save okwolf/d38773ae51c0837ba73dad1e3e348b83 to your computer and use it in GitHub Desktop.
import { h, app } from "hyperapp"
// higher-order app function for update powers
const withUpdateApp = nextApp => {
return (initialState, actionsTemplate, view, container) => {
let currentView = view
const enhancedActions = nextApp(
initialState,
{
...actionsTemplate,
runAction: ({ action, data }) => state => {
const result = action(data)
return typeof result === "function"
? result(state, enhancedActions)
: result
},
updateApp: ({ state = {}, actions = {}, view = currentView }) => {
Object.keys(actions).forEach(name => {
Object.assign(enhancedActions, {
[name]: data =>
enhancedActions.runAction({ action: actions[name], data })
})
})
currentView = view
return state
}
},
(state, actions) => currentView(state, actions),
container
)
return enhancedActions
}
}
// Compose with app
const main = withUpdateApp(app)(state, actions, view, document.body)
// Use with updated state, actions, and/or view
main.updateApp({
state: {
// new state values from here will be merged in
},
actions: {
// these actions will be added/overridden
},
view: {
// optional new view function to use
}
})
@infinnie
Copy link

It is awesome. Thanks for your suggestions.

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