-
Notifications
You must be signed in to change notification settings - Fork 5
/
statebus.js
2360 lines (2075 loc) · 90.3 KB
/
statebus.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// These 5 lines generate a module that can be included with CommonJS, AMD, and <script> tags.
(function(name, definition) {
if (typeof module != 'undefined') module.exports = definition()
else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
else this[name] = definition()
}('statebus', function() {statelog_indent = 0; var busses = {}, bus_count = 0, executing_funk, global_funk, funks = {}, clean_timer, symbols, nodejs = typeof window === 'undefined'; function make_bus (options) {
// ****************
// Get, Set, Forget, Delete
function get (key, callback) {
if (typeof key !== 'string'
&& !(typeof key === 'object' && typeof key.key === 'string'))
throw ('Error: get(key) called with key = '
+ JSON.stringify(key))
key = key.key || key // You can pass in an object instead of key
// We should probably disable this in future
bogus_check(key)
var called_from_reactive_funk = !callback
var funk = callback || executing_funk
// Initialize callback
if (callback) {
(callback.defined = callback.defined || []
).push({as:'get callback', key:key});
callback.has_seen = callback.has_seen || function (bus, key, version) {
callback.seen_keys = callback.seen_keys || {}
var bus_key = JSON.stringify([bus.id, key])
var seen_versions =
callback.seen_keys[bus_key] = callback.seen_keys[bus_key] || []
seen_versions.push(version)
if (seen_versions.length > 50) seen_versions.shift()
}
}
// ** Subscribe the calling funk **
gets_in.add(key, funk_key(funk))
if (to_be_forgotten[key]) {
clearTimeout(to_be_forgotten[key])
delete to_be_forgotten[key]
}
bind(key, 'on_set', funk)
// ** Call getters upstream **
// TODO: checking gets_out[] doesn't count keys that we got which
// arrived nested within a bigger object, because we never explicity
// got those keys. But we don't need to get them now cause we
// already have them.
var getterters = 0
if (!gets_out[key])
getterters = bus.route(key, 'getter', key)
// Now there might be a new value pubbed onto this bus.
// Or there might be a pending get.
// ... or there weren't any getters upstream.
// ** Return a value **
// If called reactively, we always return a value.
if (called_from_reactive_funk) {
funk.has_seen(bus, key, versions[key])
backup_cache[key] = backup_cache[key] || {key: key}
return cache[key] = cache[key] || {key: key}
}
// Otherwise, we want to make sure that a pub gets called on the
// handler. If there's a pending get, then it'll get called later.
// If there was a getter, then it already got called. Otherwise,
// let's call it now.
else if (!pending_gets[key] && getterters === 0) {
// TODO: my intuition suggests that we might prefer to delay this
// .on_set getting called in a setTimeout(f,0), to be consistent
// with other calls to .on_set.
backup_cache[key] = backup_cache[key] || {key: key}
run_handler(funk, 'on_set', cache[key] = cache[key] || {key: key})
}
}
function get_once (key, cb) {
function cb2 (o) { cb(o); forget(key, cb2) }
// get(key) // This prevents key from being forgotten
get(key, cb2)
}
get.once = get_once
var pending_gets = {}
var gets_out = {} // Maps `key' to `func' iff we've got `key'
var gets_in = new One_To_Many() // Maps `key' to `pub_funcs' subscribed to our key
var currently_saving
function set (obj, t) {
// First let's handle patches. We receive them as:
//
// set("foo", {patches: [{...}, ...]})
//
// Note the `obj` will actually be a string, set to the key in this case.
//
if (typeof obj === 'string' && t && t.patches) {
if (!Array.isArray(t.patches)) t.patches = [t.patches]
// Apply the patch locally
var key = obj,
obj = bus.cache[key]
console.log('set: applying the patches!', {
key: key,
obj: obj,
patches: t.patches[0]
})
obj.val = apply_patch(obj.val, t.patches[0])
}
if (!('key' in obj) || typeof obj.key !== 'string') {
console.error('Error: set(obj) called on object without a key: ', obj)
console.trace('Bad set(obj)')
}
bogus_check(obj.key)
t = t || {}
// Make sure it has a version.
t.version = t.version || new_version()
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_changes([obj.key])
return
}
if (honking_at(obj.key))
var message = set_msg(obj, t, 'set')
// Ignore if nothing happened
if (obj.key && !changed(obj)) {
statelog(obj.key, grey, 'x', message)
return
} else
statelog(obj.key, red, 'o', message)
try {
statelog_indent++
var was_saving = currently_saving
currently_saving = obj.key
// Call the setter() handlers!
var num_handlers = bus.route(obj.key, 'setter', obj, t)
if (num_handlers === 0) {
// And fire if there weren't any!
set.fire(obj, t)
bus.route(obj.key, 'on_set_sync', obj, t)
}
}
finally {
statelog_indent--
currently_saving = was_saving
}
// TODO: Here's an alternative. Instead of counting the handlers and
// seeing if there are zero, I could just make a setter handler that
// is shadowed by other handlers if I can get later handlers to shadow
// earlier ones.
}
// set.sync() will set with the version of the current executing reaction
set.sync = function set_sync (obj, t) {
t = bus.clone(t || {})
// t.version: executing_funk?.transaction?.version
// || executing_funk?.latest_reaction_at
t.version = ((executing_funk
&& executing_funk.transaction
&& executing_funk.transaction.version)
|| (executing_funk
&& executing_funk.latest_reaction_at))
set(obj, t)
}
// We might eventually want a set.fire.sync() too, which defaults the
// version to `executing_funk?.transaction?.version`
set.fire = fire
function fire (obj, t) {
t = t || {}
// Make sure it has a version.
t.version = t.version
|| executing_funk && executing_funk.latest_reaction_at
|| new_version()
// Handle patches. We receive them as:
//
// set.fire("foo", {patches: [{...}, ...]})
//
// Note the `obj` will actually be a string, set to the key in this case.
//
if (typeof obj === 'string' && t && t.patch) {
if (!Array.isArray(t.patches)) t.patches = [t.patches]
// Apply the patches locally
var key = obj,
obj = bus.cache[key]
// console.log('set.fire: applying the patches!', {
// key: key,
// obj: obj,
// patch: t.patches[0]
// })
obj.val = apply_patch(obj.val, t.patches[0])
}
// Print a statelog entry
if (obj.key && honking_at(obj.key)) {
// Warning: Changes to *nested* objects will *not* be printed out!
// In the future, we'll remove the recursion from fire() so that
// nested objects aren't even changed.
var message = set_msg(obj, t, 'set.fire')
var color, icon
if (currently_saving === obj.key &&
!(obj.key && !changed(obj))) {
statelog_indent--
statelog(obj.key, red, '•', '↵' +
(t.version ? '\t\t\t[' + t.version + ']' : ''))
statelog_indent++
} else {
// Ignore if nothing happened
if (obj.key && !changed(obj)) {
color = grey
icon = 'x'
if (t.getter)
message = (t.m) || 'Got ' + bus + "('"+obj.key+"')"
if (t.version) message += ' [' + t.version + ']'
statelog(obj.key, color, icon, message)
return
}
color = red, icon = '•'
if (t.getter || pending_gets[obj.key]) {
color = green
icon = '^'
message = add_diff_msg((t.m)||'Got '+bus+"('"+obj.key+"')",
obj)
if (t.version) message += ' [' + t.version + ']'
}
statelog(obj.key, color, icon, message)
}
}
// Then we're gonna fire!
// Recursively add all of obj, and its sub-objects, into the cache
var modified_keys = update_cache(obj, cache)
delete pending_gets[obj.key]
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_changes(modified_keys)
} else {
// Let's publish these changes!
// These objects must replace their backups
update_cache(obj, backup_cache)
// And we mark each changed key as changed so that
// reactions happen to them
for (var i=0; i < modified_keys.length; i++) {
var key = modified_keys[i]
var parents = [versions[key]] // Not stored yet
versions[key] = t.version
mark_changed(key, t)
}
}
}
set.abort = function (obj, t) {
if (!obj) console.error('No obj', obj)
abort_changes([obj.key])
statelog(obj.key, yellow, '<', 'Aborting ' + obj.key)
mark_changed(obj.key, t)
}
var version_count = 0
function new_version () {
return (bus.label||(id+' ')) + (version_count++).toString(36)
}
// Now create the statebus object
function bus (arg1, arg2) {
// Called with a function to react to
if (typeof arg1 === 'function') {
var f = reactive(arg1)
f()
return f
}
// Called with a key to produce a subspace
else return subspace(arg1, arg2)
}
var id = 'bus-' + Math.random().toString(36).substring(7)
bus.toString = function () { return bus.label || 'bus'+this_bus_num || id }
bus.delete_bus = function () {
// // Forget all pattern handlers
// for (var i=0; i<pattern_handlers.length; i++) {
// console.log('Forgetting', funk_name(pattern_handlers[i].funk))
// pattern_handlers[i].funk.forget()
// }
// // Forget all handlers
// for (var k1 in handlers.hash)
// for (var k2 in handlers.hash[k])
// handlers.hash[k][k2].forget()
delete busses[bus.id]
}
// The Data Almighty!!
var cache = {}
var backup_cache = {}
var versions = {}
// Folds object into the cache recursively and returns the keys
// for all mutated staet
function update_cache (object, cache) {
var modified_keys = new Set()
function update_object (obj) {
// Two ways to optimize this in future:
//
// 1. Only clone objects/arrays if they are new.
//
// Right now we re-clone all internal arrays and objects on
// each pub. But we really only need to clone them the first
// time they are pubbed into the cache. After that, we can
// trust that they aren't referenced elsewhere. (We make it
// the programmer's responsibility to clone data if necessary
// on get, but not when on pub.)
//
// We'll optimize this once we have history. We can look at
// the old version to see if an object/array existed already
// before cloning it.
//
// 2. Don't go infinitely deep.
//
// Eventually, each set/pub will be limited to the scope
// underneath nested keyed objects. Right now I'm just
// recursing infinitely on the whole data structure with each
// pub.
// Clone arrays
if (Array.isArray(obj))
obj = obj.slice()
// Clone objects
else if (typeof obj === 'object'
&& obj // That aren't null
&& !(obj.key // That aren't already in cache
&& cache[obj.key] === obj)) {
var tmp = {}; for (var k in obj) tmp[k] = obj[k]; obj = tmp
}
// Inline pointers
if ((nodejs ? global : window).pointerify && obj && obj._key) {
if (Object.keys(obj).length > 1)
console.error('Got a {_key: ...} object with additional fields')
obj = bus.cache[obj._key] = bus.cache[obj._key] || {key: obj._key}
}
// Fold cacheable objects into cache
else if (obj && obj.key) {
bogus_check(obj.key)
if (cache !== backup_cache)
if (changed(obj))
modified_keys.add(obj.key)
else
log('Boring modified key', obj.key)
if (!cache[obj.key])
// This object is new. Let's store it.
cache[obj.key] = obj
else if (obj !== cache[obj.key]) {
// Else, mutate cache to match the object.
// First, add/update missing/changed fields to cache
for (var k in obj)
if (cache[obj.key][k] !== obj[k])
cache[obj.key][k] = obj[k]
// Then delete extra fields from cache
for (var k in cache[obj.key])
if (!obj.hasOwnProperty(k))
delete cache[obj.key][k]
}
obj = cache[obj.key]
}
return obj
}
deep_map(object, update_object)
return modified_keys.values()
}
function changed (object) {
return pending_gets[object.key]
|| ! cache.hasOwnProperty(object.key)
|| !backup_cache.hasOwnProperty(object.key)
|| !(deep_equals(object, backup_cache[object.key]))
}
function abort_changes (keys) {
for (var i=0; i < keys.length; i++)
update_cache(backup_cache[keys[i]], cache)
}
function forget (key, set_handler, t) {
if (arguments.length === 0) {
// Then we're forgetting the executing funk
console.assert(executing_funk !== global_funk,
'forget() with no arguments forgets the currently executing reactive function.\nHowever, there is no currently executing reactive function.')
executing_funk.forget()
return
}
bogus_check(key)
//log('forget:', key, funk_name(set_handler), funk_name(executing_funk))
set_handler = set_handler || executing_funk
var fkey = funk_key(set_handler)
//console.log('Gets in is', gets_in.hash)
if (!gets_in.has(key, fkey)) {
console.error("***\n****\nTrying to forget lost key", key,
'from', funk_name(set_handler), fkey,
"that hasn't got that key.")
console.trace()
return
// throw Error('asdfalsdkfajsdf')
}
gets_in.delete(key, fkey)
unbind(key, 'on_set', set_handler)
// If this is the last handler listening to this key, then we can
// delete the cache entry, send a forget upstream, and de-activate the
// .on_get handler.
if (!gets_in.has_any(key)) {
clearTimeout(to_be_forgotten[key])
to_be_forgotten[key] = setTimeout(function () {
// Send a forget upstream
bus.route(key, 'forgetter', key, t)
// Delete the cache entry...?
// delete cache[key]
// delete backup_cache[key]
delete gets_out[key]
delete to_be_forgotten[key]
}, 200)
}
}
function del (key, t) {
key = key.key || key // Prolly disable this in future
bogus_check(key)
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_changes([key])
return
}
statelog(key, yellow, 'v', 'Deleting ' + key)
// Call the deleter handlers
var handlers_called = bus.route(key, 'deleter', key)
if (handlers_called === 0) {
// And go ahead and delete if there aren't any!
delete cache[key]
delete backup_cache[key]
}
// Call the on_delete handlers
bus.route(key, 'on_delete', cache[key] || {key: key}, t)
// console.warn("Deleting " + key + "-- Statebus doesn't yet re-run functions subscribed to it, or update versions")
// Todos:
//
// - Add transactions, so you can check permissions, abort a delete,
// etc.
// - NOTE: I did a crappy implementation of abort just now above!
// But it doesn't work if called after the deleter handler returns.
// - Generalize the code across set and del with a "mutate"
// operation
//
// - Right now we fire the deleter handlers right here.
//
// - Do we want to batch them up and fire them later?
// e.g. we could make a mark_deleted(key) like mark_changed(key)
//
// - We might also record a new version of the state to show that
// it's been deleted, which we can use to cancel echoes from the
// sending bus.
}
var changed_keys = new Set()
var dirty_getters = {} // Maps funk_key => version dirtied at
function dirty (key, t) {
statelog(key, brown, '*', bus + ".dirty('"+key+"')")
bogus_check(key)
var version = (t && t.version) || 'dirty-' + new_version()
// Find any .getter, and mark as dirty so that it re-runs
var found = false
if (gets_out.hasOwnProperty(key))
for (var i=0; i<gets_out[key].length; i++) {
dirty_getters[funk_key(gets_out[key][i])] = version
found = true
}
clean_timer = clean_timer || setTimeout(clean)
// If none found, then just mark the key changed
if (!found && cache.hasOwnProperty(key)) mark_changed(key, t)
}
function mark_changed (key, t) {
// Marks a key as dirty, meaning that functions on it need to update
log('Marking changed', bus.toString(), key)
changed_keys.add(key)
clean_timer = clean_timer || setTimeout(clean)
}
function clean () {
// 1. Collect all functions for all keys and dirtied getters
var dirty_funks = {}
for (var b in busses) {
var fs = busses[b].rerunnable_funks()
for (var i=0; i<fs.length; i++)
dirty_funks[fs[i].funk_key] = fs[i].at_version
}
clean_timer = null
// 2. Run any priority function first (e.g. file_store's on_set)
log(bus.label, 'Cleaning up', Object.keys(dirty_funks).length, 'funks')
for (var k in dirty_funks) {
var funk = funks[k],
version = dirty_funks[k]
var p = funk.proxies_for
if (p && p.priority) {
log('Clean-early:', funk_name(funk))
if (!funk.global_funk)
funk.latest_reaction_at = version
funk.react()
delete dirty_funks[k]
}
}
// 3. Re-run the functions
for (var k in dirty_funks) {
var funk = funks[k],
version = dirty_funks[k]
log('Clean:', funk_name(funk))
if (bus.render_when_loading || !funk.loading()) {
if (!funk.global_funk)
funk.latest_reaction_at = version
funk.react()
}
}
// console.log('We just cleaned up', dirty_funks.length, 'funks!')
}
// Let's change this function to go through each key and grab the latest
// version of that key, and store that when we re-run the funk for it.
// Then we can pass this back to clean as [{version, funk} ...], and then
// clean can run it with a transaction that has that version in it.
// That'll stop a lot of echoes.
function rerunnable_funks () {
var result = []
var keys = changed_keys.values()
// console.log(bus+' Finding rerunnable funcs for', keys, 'keys, and', Object.keys(dirty_getters).length, 'dirty_getters')
for (var i=0; i<keys.length; i++) { // Collect all keys
// if (to_be_forgotten[keys[i]])
// // Ignore changes to keys that have been forgotten, but not
// // processed yet
// continue
var fs = bindings(keys[i], 'on_set')
for (var j=0; j<fs.length; j++) {
var f = fs[j].func
if (f.react) {
// Skip if it's already up to date
var v = f.getted_keys[JSON.stringify([this.id, keys[i]])]
// console.log('re-run:', keys[i], f.statebus_id, f.getted_keys)
if (v && v.indexOf(versions[keys[i]]) !== -1) {
log('skipping', funk_name(f), 'already at version', versions[keys[i]], 'proof:', v)
continue
}
} else {
// Fresh handlers are always run, but need a wrapper
f.seen_keys = f.seen_keys || {}
var v = f.seen_keys[JSON.stringify([this.id, keys[i]])]
if (v && v.indexOf(versions[keys[i]]) !== -1) {
// Note: Is this even possible? Isn't it impossible
// for a fresh handler to have seen a version already?
//log('skipping', funk_name(f), 'already at version', v)
continue
}
autodetect_args(f)
f = run_handler(f, 'on_set', cache[keys[i]], {dont_run: true,
binding: keys[i]})
}
result.push({funk_key: funk_key(f),
at_version: versions[keys[i]]})
}
}
for (var k in dirty_getters) // Collect all getters
result.push({funk_key: k,
at_version: dirty_getters[k]})
changed_keys.clear()
dirty_getters = {}
// console.log('found', result.length, 'funks to re run')
return result
}
// ****************
// Connections
function subspace (key, params) {
var methods = {getter:null, setter:null, on_set:null, on_set_sync:null,
on_delete:null, deleter:null, forgetter:null}
if (params) {
for (var method in params) {
var func = params[method]
var param_names = {get:'getter', set:'setter',
delete: 'deleter', forget: 'forgetter',
on_set:'on_set', on_set_sync:'on_set_sync'}
// Map it from the API's name to our internal name
console.assert(param_names[method],
'Method "' + method + '" is invalid')
method = param_names[method]
autodetect_args(func)
func.defined = func.defined || []
func.defined.push({bus, method, key, as: 'handler'})
func.use_linked_json = true
bind(key, method, func, 'pattern')
}
}
else {
var result = {}
for (var method in methods)
(function (method) {
Object.defineProperty(result, method, {
set: function (func) {
autodetect_args(func)
func.defined = func.defined || []
func.defined.push(
{as:'handler', bus:bus, method:method, key:key})
bind(key, method, func, 'pattern')
},
get: function () {
var result = bindings(key, method)
for (var i=0; i<result.length; i++) result[i] = result[i].func
result.delete = function (func) { unbind (key, method, func, 'pattern') }
return result
}
})
})(method)
return result
}
}
function autodetect_args (handler) {
if (handler.args) return
// Get an array of the handler's params
var comments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
params = /([^\s,]+)/g,
s = handler.toString().replace(comments, '')
params = s.slice(s.indexOf('(')+1, s.indexOf(')')).match(params) || []
handler.args = {}
for (var i=0; i<params.length; i++)
switch (params[i]) {
case 'key':
case 'k':
handler.args['key'] = i; break
case 'key_parts':
handler.args['key_parts'] = i; break
case 'json':
case 'vars':
handler.args['vars'] = i; break
case 'star':
case 'rest':
handler.args['rest'] = i; break
case 'cb':
case 't':
case 'transaction':
handler.args['t'] = i; break
case 'o':
case 'obj':
case 'val':
case 'new':
case 'New':
handler.args['obj'] = i; break
case 'old':
handler.args['old'] = i; break
case 'kson':
handler.args['kson'] = i; break
}
}
// The funks attached to each key, maps e.g. 'get /point/3' to '/30'
var handlers = new One_To_Many()
var pattern_handlers = [] // An array of {pattern, method, funk}
// A set of timers, for keys to send forgets on
var to_be_forgotten = {}
function bind (pattern, method, func, type) {
bogus_check(pattern)
function pattern_matcher (pattern) {
var param_names = []
var regex = new RegExp('^' + pattern.replace(/(?<=^|\/):[^/()]+|\*/g, match => {
// Replace * with .*
if (match === '*') return '.*'
// Replace :foo with ([^/]+), and remember the "foo" name
param_names.push(match.slice(1))
return '([^/]+)'
}) + '$')
return path => {
var match = path.match(regex)
if (!match) return null
var params = {}
match.slice(1).forEach((val, i) => params[param_names[i]] = val)
return params
}
}
// Add patterns to the list, not the hash
if (type === 'pattern' && /[:*]/.test(pattern)) // Is it a pattern?
pattern_handlers.push({pattern: pattern,
matcher: pattern_matcher(pattern),
method: method,
funk: func})
// Add simple keys to the hash
else
handlers.add(method + ' ' + pattern, funk_key(func))
// Now check if the method is a get and there's a getted
// key in this space, and if so call the handler.
}
function unbind (pattern, method, funk, type) {
bogus_check(pattern)
if (type === 'pattern' && /[:*]/.test(pattern)) // Is it a pattern?
// Delete pattern connection
for (var i=0; i < pattern_handlers.length; i++) {
var handler = pattern_handlers[i]
if (handler.pattern === pattern
&& handler.method === method
&& handler.funk === funk) {
pattern_handlers.splice(i,1) // Splice this element out of the array
i-- // And decrement the counter while we're looping
}
}
else
// Delete direct connection
handlers.delete(method + ' ' + pattern, funk_key(funk))
}
function bindings(key, method) {
bogus_check(key)
if (typeof key !== 'string') {
console.error('Error:', key, 'is not a string', method)
console.trace()
}
//console.log('bindings:', key, method)
var result = []
var seen = {}
// First get the exact key matches
var exacts = handlers.get(method + ' ' + key)
for (var i=0; i < exacts.length; i++) {
var f = funks[exacts[i]]
if (!seen[funk_key(f)]) {
f.statebus_binding = {key:key, method:method}
result.push({method:method, key:key, func:f})
seen[funk_key(f)] = true
}
}
// Now iterate through patterns
for (var i=0; i < pattern_handlers.length; i++) {
handler = pattern_handlers[i]
var matches = handler.matcher(key)
if (matches // If the pattern matches
&& method === handler.method // And it has the right method
&& !seen[funk_key(handler.funk)]) {
handler.funk.statebus_binding = {
key: handler.pattern,
method: method,
params: matches
}
result.push({method, key:handler.pattern, func:handler.funk})
seen[funk_key(handler.funk)] = true
}
}
return result
}
function run_handler(funck, method, arg, options) {
options = options || {}
var t = options.t,
just_make_it = options.dont_run,
binding = options.binding
// When we first run a handler (e.g. a get or set), we wrap it in a
// reactive() funk that calls it with its arg. Then if it gets or
// sets, it'll register a .on_set handler with this funk.
// Is it reactive already? Let's distinguish it.
var funk = funck.react && funck, // Funky! So reactive!
func = !funk && funck // Just a function, waiting for a rapper to show it the funk.
console.assert(funk || func)
if (false && !funck.global_funk) {
// \u26A1
var event = {'setter':'set','on_set':'set.fire','getter':'get',
'deleter':'delete','forgetter':'forget'}[method],
triggering = funk ? 're-running' : 'initiating'
console.log(' > a', bus+'.'+event + "('" + (arg.key||arg) + "') is " + triggering
+'\n ' + funk_name(funck))
}
if (funk) {
// Then this is an on_set event re-triggering an already-wrapped
// funk. It has its own arg internally that it's calling itself
// with. Let's tell it to re-trigger itself with that arg.
if (method !== 'on_set') {
console.error(method === 'on_set', 'Funk is being re-triggered, but isn\'t on_set. It is: "' + method + '", oh and funk: ' + funk_name(funk))
return
}
return funk.react()
// Hmm... does this do the right thing? Example:
//
// bus('foo').on_set = function (o) {...}
// set({key: 'foo'})
// set({key: 'foo'})
// set({key: 'foo'})
//
// Does this spin up 3 reactive functions? Hmm...
// Well, I think it does, but they all get forgotten once
// they run once, and then are garbage collected.
//
// bus('foo*').on_set = function (o) {...}
// set({key: 'foo1'})
// set({key: 'foo2'})
// set({key: 'foo1'})
// set({key: 'foo3'})
//
// Does this work ok? Yeah, I think so.
}
// Alright then. Let's wrap this func with some funk.
// Fresh get/set/forget/delete handlers will just be regular
// functions. We'll store their arg and transaction and let them
// re-run until they are done re-running.
function key_arg () { return ((typeof arg.key) == 'string') ? arg.key : arg }
function rest_arg () { return (key_arg()).substr(binding.length-1) }
function val_arg () {
console.assert(method === 'setter' || method === 'on_set' || method === 'on_set_sync',
'Bad method for val_arg()')
// Is there a time I am supposed to return bus.cache[arg]? It used to say:
// arg.key ? arg : bus.cache[arg]
return arg.key ? (func.use_linked_json ? arg.val : arg) : undefined
}
function vars_arg () {
var r = rest_arg()
try {
return JSON.parse(r)
} catch (e) {
return 'Bad JSON "' + r + '" for key ' + key_arg()
}
}
// Parse out query params for URLs in the style /foo/bar(param1,param2:val2).
// We're currently calling that (param1,param2:val2) part "kson", and presuming
// that it exists in the * part of the pattern like in /foo/bar*.
function kson_args () {
// This code is copied from Raphael Walker's parser.coffee
function split_once (str, char) {
var i = str.indexOf(char)
return i === -1 ? [str, ""] : [str.slice(0, i), str.slice(i + 1)]
}
// KSON = Kinda Simple Object Notation
// but it rhymes with JSON
function parse_kson (str) {
// Coffeescript doesn't have object comprehensions :(
var ret = {}
// Now process the string:
str
// Pull out the parentheses
.slice(1, -1)
// Split by commas. TODO: Allow spaces after commas?
.split(",")
// Delete empty parts (this ensures that empty strings
// will properly result in empty KSON, and allows trailing
// commas)
.filter(part => part.length)
.forEach(part => {
// If the part has a comma, its a key:value, otherwise
// it's just a singleton
var [k, v] = split_once(part, ":")
if (v.length === 0) ret[k] = true
// If the value is itself a KSON object, parse it recursively
else if (v.startsWith("(")) ret[k] = parse_kson(v)
else ret[k] = v
})
return ret
}
return parse_kson(rest_arg())
}
var f = reactive(function () {
// Initialize transaction
t = clone(t || {})
// Add .abort() method
if (method === 'setter' || method === 'deleter')
t.abort = function () {
var key = method === 'setter' ? arg.key : arg
if (f.loading()) return
bus.cache[key] = bus.cache[key] || {key: key}
bus.backup_cache[key] = bus.backup_cache[key] || {key: key}
bus.set.abort(bus.cache[key])
}
// Add .done() method
if (method !== 'forgetter')
t.done = function (o) {
var key = method === 'setter' ? arg.key : arg
if (func.use_linked_json)
o = {key, val: o}
bus.log('We are DONE()ing', method, key, o||arg)
// We use a simple (and crappy?) heuristic to know if the
// setter handler has changed the state: whether the
// programmer passed (o) to the t.done(o) handler. If
// not, we assume it hasn't changed. If so, we assume it
// *has* changed, and thus we change the version of the
// state. I imagine it would be more accurate to diff
// from before the setter handler began with when
// t.done(o) ran.
//
// Note: We will likely solve this in the future by
// preventing .setter() from changing the incoming state,
// except through an explicit .revise() function.
if (o) t.version = new_version()
if (method === 'deleter') {
delete bus.cache[key]
delete bus.backup_cache[key]
}
else if (method === 'setter') {
bus.set.fire(o || arg, t)
bus.route(key, 'on_set_sync', o || arg, t)
} else {
// Now method === 'getter'
o.key = key
bus.set.fire(o, t)
// And now reset the version cause it could get called again
delete t.version
}
}
// Alias .return() to .done(), in case that feels better to you
t.return = t.done
// Prepush Scratch:
// var prepushed = {}
// t.prepush = function (key) {
// prepushed[key] = bus.get(key)
// }
// Alias t.reget() to bus.dirty()
if (method === 'setter')
t.reget = function () { bus.dirty(arg.key) }