-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
334 lines (302 loc) · 8.78 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
const ROOT = Symbol('root')
const UPDATE = Symbol('update')
const CANCEL = Symbol('cancel')
const INTERRUPT = Symbol('interrupt')
/** Pool of used children per parent */
const pool = new WeakMap()
/** Use with {@link Layer#subscribe} to listen for any store changes */
export const ANY = Symbol('any')
/** Current stack of layers being resolved */
export const stack = []
/**
* Read from store. Returns value
* @param {any} [key] Store key name, omitting key yields store object
* @param {any} [initial] Initial value if not found in store
* @returns {Array} A touple of current value and an update function
*/
export function store (key, initial) {
console.assert(stack.length, 'store used outside render cycle')
var layer = stack[0]
if (!key) return [layer.store, (next) => layer.update(next)]
if (typeof key === 'string' && key[0] === '$') {
const _key = key.substring(1)
let value
if (hasOwnProperty(layer.store[_key])) {
value = layer.store[_key]
} else if (typeof initial !== 'undefined') {
value = layer.store[_key] = initial
layer.changes.add(_key)
}
return [value, (next) => layer.update(key, next)]
}
var value = layer.store[key]
if (typeof value === 'undefined' && typeof initial !== 'undefined') {
value = layer.store[key] = initial
layer.changes.add(key)
}
return [value, (next) => layer.update(key, next)]
}
/**
* Watch store for changes
* @param {any} key store key to watch or function to call on any change
* @param {Function} [fn] Function ot call when value of key change
* @returns {void}
*/
export function watch (key, fn) {
console.assert(stack.length, 'watch used outside render cycle')
if (Array.isArray(key)) {
return key.forEach((_key) => watch(_key, function () {
var layer = stack[0]
return fn(key.map((__key) => layer.store[__key]))
}))
} else if (typeof key === 'function') {
fn = key
key = ANY
}
if (key === ANY) {
stack.forEach((layer) => layer.subscribe(key, fn))
} else {
const layer = stack.find((layer) => hasOwnProperty(layer.store, key))
if (layer) {
layer.subscribe(key, fn)
if (layer.fresh) layer.changes.add(key)
}
}
}
/**
* Creates a layer for a component
* @param {Function} fn Component render Function
* @param {Object} store Store to use for component
* @param {...any} args Arguments to forward to component
* @returns {Layer}
*/
export function use (fn, store, ...args) {
var layer = stack[0]
if (store == null) store = {}
if (!layer) return new Layer(ROOT, fn, store, args)
if (!layer.children.has(fn)) layer.children.set(fn, new Set())
if (!pool.get(layer).has(fn)) pool.get(layer).set(fn, new Set())
var child
var children = layer.children.get(fn)
var candidates = pool.get(layer).get(fn)
var key = typeof store.key === 'undefined' ? children.size + 1 : store.key
for (const candidate of candidates) {
if (candidate.key === key) {
child = candidate
child.assign(store, args)
break
}
}
if (!child) {
store = Object.assign(Object.create(layer.store), store)
child = new Layer(key, fn, store, args)
}
children.add(child)
return child
}
export class Layer {
/**
* Create a layer
* @param {any} key Unique identifier for component
* @param {Function} fn Component render Function
* @param {Object} store Store to use for Component
* @param {Array} args Arguments to forward to component
*/
constructor (key, fn, store, args) {
this.key = key
this.args = args
this.store = store
this.render = render
this.fresh = true
this.stack = [...stack]
this.changes = new Set()
this.children = new Map()
this.listeners = new Map()
pool.set(this, new WeakMap())
var queued = false
var running = false
/**
* Call component render function, recursively rerunning on every update
* @returns {any}
*/
function render () {
if (running) {
queued = true
} else {
try {
queued = false
running = true
var res = unwind(fn(...this.args))
} catch (err) {
if (err === INTERRUPT) {
queued = true
} else if (err === CANCEL) {
var cancel = true
} else {
throw err
}
} finally {
running = false
}
if (cancel) return
if (queued) res = this.render()
return res
}
}
}
/**
* Make updates to layer internals on reuse
* @param {Object} store Properties with which to extend store
* @param {Array} args Arguments to forward to component
* @returns {void}
*/
assign (store, args) {
this.args = args
Object.assign(this.store, store)
}
/**
* Resolve component
* @param {Function} callback Function to call on async updates
* @returns {any}
*/
resolve (callback) {
if (!stack.includes(this)) {
stack.unshift(this)
}
if (typeof callback === 'function') {
this.subscribe(UPDATE, function onupdate (res) {
callback(res)
return onupdate
})
}
try {
for (const key of this.changes) {
this.emit(key, this.store[key])
}
const res = this.render()
for (const key of this.changes) {
this.emit(key, this.store[key])
}
return res
} finally {
const pooled = pool.get(this)
for (const [fn, children] of this.children) {
pooled.set(fn, new Set(children))
}
this.fresh = false
this.children.clear()
this.changes.clear()
stack.shift()
}
}
/**
* Update store, issuing an async render
* @param {any} key Key of the value to update or a new store to assign
* @param {any} [value] New value to assign for key
* @returns {void}
*/
update (key, value) {
if (typeof value === 'undefined') {
Object.assign(this.store, key)
key = ANY
} else if (typeof key === 'string' && key[0] === '$') {
key = key.substring(1)
this.store[key] = value
} else {
if (hasOwnProperty(this.store, key)) {
this.store[key] = value
} else {
const parent = this.stack.find(function (parent) {
return hasOwnProperty(parent.store, key)
})
if (!parent) {
this.store[key] = value
} else {
parent.changes.add(key)
parent.emit(UPDATE, parent.resolve(), { any: false })
if (stack.includes(this)) throw CANCEL
return
}
}
}
this.changes.add(key)
if (stack.includes(this)) throw INTERRUPT
this.emit(UPDATE, this.resolve(), { any: false })
}
/**
* Subscribe to changes made to store. The listener function may return
* a callback function which will be called on next change, before render.
* @param {any} key Key to subscribe to
* @param {Function} fn Function to call on change
* @returns {void}
*/
subscribe (key, fn) {
if (!this.listeners.has(fn)) {
this.listeners.set(fn, new Set())
}
this.listeners.get(fn).add(key)
}
/**
* Emit change
* @param {any} key Emit an event to subscribed listeners
* @param {any} value New value for subscribed key
* @param {Object} [opts] Configure behavior
* @param {boolean} [opts.any=true] Trigger listerns for {@link ANY}
*/
emit (key, value, opts = {}) {
var { any = true } = opts
var listeners = []
for (const [fn, keys] of this.listeners.entries()) {
if (!keys.has(key) && (!any || !keys.has(ANY))) continue
const cleanup = keys.has(key) && key !== ANY ? fn(value) : fn()
this.listeners.delete(fn)
if (typeof cleanup === 'function') listeners.push(cleanup)
}
for (const listener of listeners) {
this.subscribe(key, listener)
}
}
}
/**
* Resolve nested generator and promises
* @param {any} obj
* @param {any} [value]
* @returns {any}
*/
function unwind (obj, value) {
if (isGenerator(obj)) {
const res = obj.next(value)
if (res.done) return res.value
if (isPromise(res.value)) {
return res.value.then(unwind).then((val) => unwind(obj, val))
}
return unwind(obj, res.value)
} else if (isPromise(obj)) {
return obj.then(unwind)
}
return obj
}
/**
* Determin if object is promise
* @param {any} obj
* @returns {boolean}
*/
function isPromise (obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'
}
/**
* Determine if object is generator
* @param {any} obj
* @return {boolean}
*/
function isGenerator (obj) {
return obj && typeof obj.next === 'function' && typeof obj.throw === 'function'
}
/**
* Check if object has key set on self
* @param {Object} obj The object to check
* @param {any} key The key to look for
*/
function hasOwnProperty (obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key)
}