-
Notifications
You must be signed in to change notification settings - Fork 12
/
compose.js
87 lines (77 loc) · 1.79 KB
/
compose.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const { html, pull } = require('../')
const many = require('pull-many')
// apps as groupoid
module.exports = compose
function compose (apps, template = defaultTemplate) {
return {
init () {
return composeStates(
apps.map((app) => app.init())
)
},
update (models, actions) {
return composeStates(
apps.map((app, i) => {
const m = models[i]
const a = actions[i]
return a ? app.update(m, a) : { model: m }
})
)
},
view (models, dispatch) {
const dispatchByApp = i =>
action => dispatch(item(action, i))
return template(
apps.map((app, i) => {
const m = models[i]
return app.view(m, dispatchByApp(i))
})
)
},
run (effects, sources) {
const nextActions = apps.map((app, i) => {
const eff = effects[i]
return eff
? pull(
app.run(eff, {
actions: () => pull(
sources.actions(),
pull.map(value => value[i]),
pull.filter(isNotNil)
)
}) || pull.empty(),
pull.map(action => item(action, i))
)
: pull.empty()
})
return many(nextActions)
}
}
}
function composeStates (states) {
console.log('compose state', states)
return {
model: states.map(s => s.model),
effect: states.some(s => s.effect)
? states.map(s => s.effect) : null
}
}
function defaultTemplate (views) {
return html`
<div>
${
views.map((view, i) => html`
<div class=${`app-${i}`}>
${view}
</div>`
)
}
</div>
`
}
function isNotNil (x) { return x != null }
function item (value, i) {
var arr = []
arr[i] = value
return arr
}