-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (65 loc) · 1.83 KB
/
index.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
var Preact = require('preact')
var h = Preact.h
var Component = Preact.Component
var xtend = require('xtend')
var S = require('pull-stream/pull')
var Drain = require('pull-stream/sinks/drain')
var Notify = require('pull-notify')
var Pushable = require('pull-pushable')
var Abortable = require('pull-abortable')
function PreactStream (view, initState) {
// @TODO should probably get rid of this and make a simple
// pub/sub thing
var pushable = Pushable()
var abortable$ = Abortable()
var notify = Notify()
// memoize these emitter functions
var emitFns = {}
function emit (type, data) {
if (data === undefined) {
emitFns[type] = emitFns[type] || function (data) {
notify([type, data])
}
return emitFns[type]
}
notify([type, data])
}
class ViewStream extends Component {
constructor() {
super()
this.state = initState
}
componentDidMount() {
var self = this
S(
pushable,
abortable$,
Drain(function onUpdate (state) {
self.setState(state)
}, function onEnd (err) {
if (err) throw err
})
)
}
componentWillUnmount() {
abortable$.abort()
}
render(props, state) {
return h(
view,
xtend(props, state, {
emit: emit,
}),
props.children
)
}
}
ViewStream.createSource = notify.listen
ViewStream.sink = Drain(function onEvent (ev) {
pushable.push(ev)
}, function onEnd (err) {
if (err) throw err
})
return ViewStream
}
module.exports = PreactStream