-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbraid.js
2444 lines (2163 loc) · 92.5 KB
/
braid.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()
}('braid', function() {statelog_indent = 0; var busses = {}, executing_funk, global_funk, funks = {}, clean_timer, symbols, nodejs = typeof window === 'undefined'; function make_bus (options) {
// ****************
// Get, Set, Forget, Delete
function get (key, callback) {
key = key.key || key // You can pass in an object instead of key
// We should probably disable this in future
if (typeof key !== 'string')
throw ('Error: get(key) called with a non-string key: '+key)
bogus_check(key)
var called_from_reactive_funk = !callback
var funck = callback || executing_funk
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 (versions.length > 50) versions.shift()
}
}
// ** Subscribe the calling funck **
if (called_from_reactive_funk)
funck.has_seen(bus, key, versions[key]) // Maybe this line should go below, in the existing "if (called_from_reactive_funk) {" ??
subscriptions_to_us.add(key, funk_key(funck))
if (to_be_forgotten[key]) {
clearTimeout(to_be_forgotten[key])
delete to_be_forgotten[key]
}
bind(key, funck.to_getter ? 'on_set_sync' : 'on_set', funck)
// ** Call getters upstream **
// TODO: checking subscriptions_from_us[] 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 to_getters = 0
if (!subscriptions_from_us[key])
to_getters = bus.route(key, 'to_get', 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) {
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 to_get, then it already got called. Otherwise,
// let's call it now.
else if (!pending_gets[key] && to_getters === 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(funck, '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_in = new One_To_Many() // Maps `key' to `pub_funcs' subscribed to our key
var gets_out = {} // Maps `key' to `func' iff we've got `key'
var subscriptions_to_us = new One_To_Many() // Maps `key' to `pub_funcs' subscribed to our key
var subscriptions_from_us = {} // Maps `key' to `func' iff we've got `key'
var currently_saving
function set (obj, t) {
// First let's handle diffs
if (typeof obj === 'string' && t && t.patch) {
if (typeof t.patch == 'string') t.patch = [t.patch]
// Apply the patch locally
obj = apply_patch(bus.cache[obj] || {key: obj}, t.patch[0])
}
if (!('key' in obj) || typeof obj.key !== 'string')
console.error('Error: set(obj) called on object without a key: ', obj)
bogus_check(obj.key)
t = t || {}
// Make sure it has a version.
t.version = t.version
|| (executing_funk && executing_funk.reacting_at)
|| new_version()
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_change(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 to_set() handlers!
var num_handlers = bus.route(obj.key, 'to_set', obj, t)
if (num_handlers === 0) {
// And fire if there weren't any!
// ... hmmm... should this just be moved into route() itself?
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 to_set handler that
// is shadowed by other handlers if I can get later handlers to shadow
// earlier ones.
}
set.r = function set_r (obj, t) {
// We don't actually need a map that returns the whole tree here, just
// a deep_each that applies set to every object with a key.
deep_map(obj, function (o) {
if (o && typeof o === 'object' && o.key)
set(o, t)
return o
})
}
fire.r = function fire_r (obj, t) {
deep_map(obj, function (o) {
if (o && typeof o === 'object' && o.key)
fire(o, t)
return o
})
}
set.fire = fire
// Fire is called once a change is *valid* and it's time to make it
// official, and broadcast post it to everyone. This function:
// - Prints a statelog entry
// - Updates the cache
// - Marks it changed so that everyone updates
function fire (obj, t) {
// Here's a stupid hack to make it backwards compatible with state
// that puts fields directly on the {key: ...} object itself:
if (// If obj is like {key: ...}
obj.key && Object.keys(obj).length === 1
// And replacing something like {key: .., val: ..}
&& cache[obj.key] && cache[obj.key].val !== undefined
&& Object.keys(cache[obj.key]).length == 2)
// Then do nothing
return
t = t || {}
// Make sure it has a version.
t.version = t.version || new_version()
// 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.to_get)
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.to_get || 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)
}
}
// Now let's get ready to fire!
if (!changed(obj)) { // Unless nothing has actually changed
log('Boring modified key', obj.key)
delete pending_gets[obj.key]
return
}
// Ok now, set the cache!
update_cache(obj, cache)
delete pending_gets[obj.key]
// Now that we've figured that out, we might abort
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_change(obj.key)
return
}
// Ok, we haven't aborted. Let's cement the backup.
update_cache(obj, backup_cache)
// And mark the key as changed so that reactions happen to it
var parents = [versions[obj.key]] // Not stored yet
versions[obj.key] = t.version
mark_changed(obj.key, t)
}
set.abort = function (obj, t) {
if (!obj) console.error('No obj', obj)
abort_change(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 braid object
function bus (arg) {
// Called with a function to react to
if (typeof arg === 'function') {
var f = reactive(arg)
f()
return f
}
// Called with a key to produce a subspace
else return subspace(arg)
}
var id = 'bus ' + Math.random().toString(36).substring(7)
bus.toString = function () { return bus.label || id }
bus.delete_bus = function () {
// // Forget all wildcard handlers
// for (var i=0; i<wildcard_handlers.length; i++) {
// console.log('Forgetting', funk_name(wildcard_handlers[i].funk))
// wildcard_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 = {}
function update_cache (obj, cache) {
// Go through each field (which will eventually only be 'val')
// And delete stuff that's gone, and clone stuff that's new
function replace_link (item) {
return (typeof item === "object") && item !== null &&
item.hasOwnProperty('key') &&
(cache[item.key] = cache[item.key] || {key: item.key})
}
console.assert(obj && obj.key)
bogus_check(obj.key)
if (!cache.hasOwnProperty([obj.key]))
// This object is new.
cache[obj.key] = {key: obj.key}
if (obj !== cache[obj.key]) {
// Mutate cache to match the object.
// TODO:
//
// Now that the entire value of objects is within the 'val'
// field, the following code can just replace the old 'val' with
// the new 'val', instead of bothering doing any looping.
// First, add/update missing/changed fields to cache
for (var k in obj)
cache[obj.key][k] = clone(obj[k], replace_link)
// Then delete extra fields from cache
for (var k in cache[obj.key])
if (!obj.hasOwnProperty(k))
delete cache[obj.key][k]
}
}
function update_cache_old (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_change (key) {
update_cache(backup_cache[key] || {key:key}, cache)
}
function forget (key, set_handler) {
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', subscriptions_to_us.hash)
if (!subscriptions_to_us.has(key, fkey)) {
console.error("***\n****\nTrying to forget lost key", key,
'from', funk_name(set_handler), fkey,
"that hasn't got that key.",
funks[subscriptions_to_us.get(key)[0]],
funks[subscriptions_to_us.get(key)[0]] && funks[subscriptions_to_us.get(key)[0]].braid_id
)
console.trace()
return
}
subscriptions_to_us.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
// .to_get handler.
if (!subscriptions_to_us.has_any(key)) {
clearTimeout(to_be_forgotten[key])
to_be_forgotten[key] = setTimeout(function () {
// Send a forget upstream
bus.route(key, 'to_forget', key)
delete cache[key]
delete subscriptions_from_us[key]
delete to_be_forgotten[key]
}, 200)
}
}
function del (key) {
key = key.key || key // Prolly disable this in future
bogus_check(key)
if ((executing_funk !== global_funk) && executing_funk.loading()) {
abort_change(key)
return
}
statelog(key, yellow, 'v', 'Deleting ' + key)
// Call the to_delete handlers
var handlers_called = bus.route(key, 'to_delete', key)
if (handlers_called === 0)
// And go ahead and delete if there aren't any!
delete cache[key]
// console.warn("Deleting " + key + "-- Braid 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 to_delete handler returns.
// - Generalize the code across set and del with a "mutate"
// operation
//
// - Right now we fire the to_delete 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 = new Set()
function dirty (key, t) {
statelog(key, brown, '*', bus + ".dirty('"+key+"')")
bogus_check(key)
// Find any .to_get, and mark as dirty so that it re-runs
var found = false
if (subscriptions_from_us.hasOwnProperty(key))
for (var i=0; i<subscriptions_from_us[key].length; i++) {
dirty_getters.add(funk_key(subscriptions_from_us[key][i]))
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)
}
var touch = dirty
function mark_changed (key, t) {
// Marks a key as dirty, meaning that functions on it need to update
log('Marking changed', bus, 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 = new Set()
for (var b in busses) {
var fs = busses[b].rerunnable_funks()
for (var i=0; i<fs.length; i++)
dirty_funks.add(fs[i])
}
clean_timer = null
// 2. Run any priority function first (e.g. file_store's on_set)
dirty_funks = dirty_funks.values()
log('Cleaning up', dirty_funks.length, 'funks')
for (var i=0; i<dirty_funks.length; i++) {
// console.log(funks[dirty_funks[i]].proxies_for)
var p = funks[dirty_funks[i]].proxies_for
if (p && p.priority) {
log('Clean-early:', funk_name(funks[dirty_funks[i]]))
funks[dirty_funks[i]].react()
dirty_funks.splice(i,1)
i--
}
}
// 3. Re-run the functions
for (var i=0; i<dirty_funks.length; i++) {
log('Clean:', funk_name(funks[dirty_funks[i]]))
if (bus.render_when_loading || !funks[dirty_funks[i]].loading())
funks[dirty_funks[i]].react()
}
// log('We just cleaned up', dirty_funks.length, 'funks!')
}
function rerunnable_funks () {
var result = []
var keys = changed_keys.values()
var getters = dirty_getters.values()
//log(bus+' Cleaning up!', keys, 'keys, and', getters.length, '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.subscribed_to_keys[JSON.stringify([this.id, keys[i]])]
//log('re-run:', keys[i], f.braid_id, f.subscribed_to_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) {
//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(f))
}
}
for (var i=0; i<getters.length; i++) // Collect all getters
result.push(getters[i])
changed_keys.clear()
dirty_getters.clear()
//log('found', result.length, 'funks to re run')
return result
}
// ****************
// Connections
function subspace (key) {
var result = {}
for (var method in {to_get:null, to_set:null, on_set:null, on_set_sync:null,
to_delete:null, to_forget:null})
(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, 'allow_wildcards')
},
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, 'allow_wildcards') }
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 'json':
case 'vars':
handler.args['vars'] = i; break
case 'star':
case 'rest':
handler.args['rest'] = i; break
case 't':
case 'transaction':
handler.args['t'] = i; break
case 'o':
case 'obj':
case 'new':
case 'New':
handler.args['obj'] = i; break
case 'val':
handler.args['val'] = i; break
case 'old':
handler.args['old'] = i; break
}
}
// The funks attached to each key, maps e.g. 'get /point/3' to '/30'
var handlers = new One_To_Many()
var wildcard_handlers = [] // An array of {prefix, method, funk}
// A set of timers, for keys to send forgets on
var to_be_forgotten = {}
function bind (key, method, func, allow_wildcards) {
bogus_check(key)
if (allow_wildcards && key[key.length-1] === '*')
wildcard_handlers.push({prefix: key,
method: method,
funk: func})
else
handlers.add(method + ' ' + key, funk_key(func))
// Now check if the method is a get and there's a gotton
// key in this space, and if so call the handler.
}
function unbind (key, method, funk, allow_wildcards) {
bogus_check(key)
if (allow_wildcards && key[key.length-1] === '*')
// Delete wildcard connection
for (var i=0; i<wildcard_handlers.length; i++) {
var handler = wildcard_handlers[i]
if (handler.prefix === key
&& handler.method === method
&& handler.funk === funk) {
wildcard_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 + ' ' + key, 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.braid_binding = {key:key, method:method}
result.push({method:method, key:key, func:f})
seen[funk_key(f)] = true
}
}
// Now iterate through prefixes
for (var i=0; i < wildcard_handlers.length; i++) {
handler = wildcard_handlers[i]
var prefix = handler.prefix.slice(0, -1) // Cut off the *
if (prefix === key.substr(0,prefix.length) // If the prefix matches
&& method === handler.method // And it has the right method
&& !seen[funk_key(handler.funk)]) {
handler.funk.braid_binding = {key:handler.prefix, method:method}
result.push({method:method, key:handler.prefix, 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 = {'to_set':'set','on_set':'set.fire','to_get':'get',
'to_delete':'delete','to_forget':'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()
// This might not work that great.
// Ex:
//
// bus('foo').on_set = function (o) {...}
// set({key: 'foo'})
// set({key: 'foo'})
// set({key: 'foo'})
//
// Does this spin up 3 reactive functions? I think so.
// No, 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 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 vars_arg () {
var r = rest_arg()
try {
return JSON.parse(r)
} catch (e) {
return 'Bad JSON "' + r + '" for key ' + key_arg()
}
}
var f = reactive(function () {
// Initialize transaction
t = clone(t || {})
if (!(method in {to_get:1, to_forget:1}))
t.abort = function () {
var key = method === 'to_set' ? 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])
}
// Install the t.done() function
if (method !== 'to_forget')
t.done = function (o) {
var key = method === 'to_set' ? arg.key : arg
bus.log('We are DONE()ing', method, key, o||arg)
// We use a simple (and crappy?) heuristic to know if to
// to_set 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 o
// from before the to_set handler began with when
// t.done(o) ran.
if (o) t.version = new_version()
if (method === 'to_delete')
delete bus.cache[key]
else if (method === 'to_set') {
bus.set.fire(o || arg, t)
bus.route(key, 'on_set_sync', o||arg, t)
} else if (method === 'to_get') {
o.key = key
bus.set.fire(o, t)
// And now reset the version cause it could get called again
delete t.version
} else if (method === 'on_set_sync') {}
else throw "Just kidding. This can't happen. There aren't any other methods."
}
t.return = t.done
if (method === 'to_set')
t.dirty = function () { bus.dirty(arg.key) }
// Then in run_handler, we'll call it with:
var args = []
args[0] = arg
args[1] = t
//console.log('This funcs args are', func.args)
for (var k in (func.args||{})) {
switch (k) {
case 'key':
args[func.args[k]] = key_arg(); break
case 'rest':
args[func.args[k]] = rest_arg(); break
case 'vars':
args[func.args[k]] = vars_arg();
//console.log('We just made an arg', args[func.args[k]], 'in slot', func.args[k], 'for', k)
break
case 't':
args[func.args[k]] = t; break
case 'obj':
args[func.args[k]] = arg.key ? arg : bus.cache[arg]; break
case 'val':
args[func.args[k]] = arg.key ? arg.val : bus.cache[arg].val; break
case 'old':
var key = key_arg()
args[func.args[k]] = bus.cache[key] || (bus.cache[key] = {key:key})
break
}
//console.log('processed', k, 'at slot', func.args[k], 'to make', args[func.args[k]])
}
//console.log('args is', args)
// Call the raw function here!
var result = func.apply(null, args)
// We will wanna add in the fancy arg stuff here, with:
// arr = []
// for (var k of func.args || {})
// arr[func.args[k]] = <compute_blah(k)>
// Trigger done() or abort() by return value
console.assert(!(result === 'to_get' &&
(result === 'done' || result === 'abort')),
'Returning "done" or "abort" is not allowed from to_get handlers')
if (result === 'done') t.done()
if (result === 'abort') t.abort()
// For get
if (method === 'to_get' && result instanceof Object
&& !f.loading() // Experimental.
) {
result.key = arg
var new_t = clone(t || {})
new_t.to_get = true
set.fire(result, new_t)
return result
}
// Set, forget and delete handlers stop re-running once they've
// completed without anything loading.
// ... with f.forget()
if (method !== 'to_get' && !f.loading())
f.forget()
})
f.proxies_for = func
f.arg = arg
// to_get handlers stop re-running when the key is forgotten
if (method === 'to_get') {
var key = arg
function handler_done () {
f.forget()
unbind(key, 'to_forget', handler_done)
}
bind(key, 'to_forget', handler_done)
// // Check if it's doubled-up
// if (subscriptions_from_us[key])
// console.error('Two .to_get functions are running on the same key',
// key+'!', funk_name(funck), funk_name(subscriptions_from_us[key]))
subscriptions_from_us[key] = subscriptions_from_us[key] || []
subscriptions_from_us[key].push(f) // Record active to_get handler
pending_gets[key] = f // Record that the get is pending
// Last, let's mark this function as a to_getter, so that we treat
// it special inside get()
f.to_getter = true
}
if (just_make_it)
return f
return f()
}
// route() can be overridden
bus.route = function (key, method, arg, t) {
var handlers = bus.bindings(key, method)
if (handlers.length)
log('route:', bus+'("'+key+'").'+method+'['+handlers.length+'](key:"'+(arg.key||arg)+'")')
// log('route: got bindings',
// funcs.map(function (f) {return funk_key(f)+':'+funk_keyr(f)}))
for (var i=0; i<handlers.length; i++)
bus.run_handler(handlers[i].func, method, arg, {t: t, binding: handlers[i].key})
// if (method === 'to_get')
// console.assert(handlers.length<2,
// 'Two to_get functions are registered for the same key '+key,
// handlers)
return handlers.length
}
// ****************
// Reactive functions
//
// We wrap any function with a reactive wrapper that re-calls it whenever
// state it's gotton changes.
if (!global_funk) {
global_funk = reactive(function global_funk () {})
global_funk.global_funk = true
executing_funk = global_funk
funks[global_funk.braid_id = 'global funk'] = global_funk