-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdaimio_composite.js
9164 lines (7624 loc) · 278 KB
/
daimio_composite.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
/*
_ _ _ _ _ _ _
/\ \ / /\ /\ \ /\_\/\_\ _ /\ \ /\ \
/ \ \____ / / \ \ \ \ / / / / //\_\ \ \ \ / \ \
/ /\ \_____\ / / /\ \ /\ \_\ /\ \/ \ \/ / / /\ \_\ / /\ \ \
/ / /\/___ // / /\ \ \ / /\/_/ / \____\__/ / / /\/_/ / / /\ \ \
/ / / / / // / / \ \ \ / / / / /\/________/ / / / / / / \ \_\
/ / / / / // / /___/ /\ \ / / / / / /\/_// / / / / / / / / / / /
/ / / / / // / /_____/ /\ \ / / / / / / / / / / / / / / / / / /
\ \ \__/ / // /_________/\ \ \ ___/ / /__ / / / / / /___/ / /__ / / /___/ / /
\ \___\/ // / /_ __\ \_\/\__\/_/___\\/_/ / / //\__\/_/___\/ / /____\/ /
\/_____/ \_\___\ /____/_/\/_________/ \/_/ \/_________/\/_________/
Hi, welcome to Daimio!
As you make your way through the code you'll often
see comments like this one. You should read them,
because they're helpful and occasionally funny!
Naming conventions:
D.import_commands <--- snake_case for functions and constants
D.SegmentTypes <--- CamelCase for built-in objects
D.SPACESEEDS <--- ALLCAPS for runtime containers
*/
D = {} // this is where the magic happens
D.BLOCKS = {}
D.DIALECTS = {}
D.SPACESEEDS = {}
D.DECORATORS = []
D.DecoratorIndices = {} // technically these should be all caps,
D.DecoratorIndices.ByType = {} // but it's just too much yelling really
D.DecoratorIndices.ByBlock = {}
D.DecoratorIndices.ByTypeBlock = {}
D.Aliases = {} // aliases are a grey area:
D.AliasMap = {} // one day they may be able to grow at runtime
D.Etc = {}
D.Types = {}
D.Parser = {}
D.Fancies = {}
D.Commands = {}
D.Terminators = {}
D.Pathfinders = [] // one of these things is not like the others
D.SegmentTypes = {}
D.PortFlavours = {}
D.Constants = {} // constants fry, constants fry, any time at all
D.Constants.command_open = '{'
D.Constants.command_closed = '}'
D.Constants.list_open = '(' // currently unused
D.Constants.list_closed = ')' // currently unused
D.Constants.quote = '"' // currently unused
D.Etc.process_counter = 1 // this is a bit silly
D.Etc.token_counter = 100000 // FIXME: make Rekey work even with overlapping keys
D.Etc.FancyRegex = "" // this is also pretty silly
D.Etc.Tglyphs = "" // and this one too
D.Etc.OptimizationMap = {} // technically allcaps here too
D.Etc.use_optimizations = 1 // you can change this in your app
/*ooo ooooo oooooooooooo ooooo ooooooooo. oooooooooooo ooooooooo. .oooooo..o
`888' `888' `888' `8 `888' `888 `Y88. `888' `8 `888 `Y88. d8P' `Y8
888 888 888 888 888 .d88' 888 888 .d88' Y88bo.
888ooooo888 888oooo8 888 888ooo88P' 888oooo8 888ooo88P' `"Y8888o.
888 888 888 " 888 888 888 " 888`88b. `"Y88b
888 888 888 o 888 o 888 888 o 888 `88b. oo .d8P
o888o o888o o888ooooood8 o888ooooood8 o888o o888ooooood8 o888o o888o 8""88888*/
D.noop = function() {}
D.identity = function(x) {return x}
D.concat = function(a,b) {return a.concat(b)}
D.set_error = function(error) {
// use this to set simple errors
return D.on_error('', error)
}
D.on_error = function(command, error) {
// use this to report errors in low-level daimio processes
console.log('error: ' + error, command)
return ""
}
D.make_nice = function(value, otherwise) {
return D.is_nice(value) ? value : (otherwise || '')
}
D.to_array = function(value) { // DATA
// this converts non-iterable items into a single-element array
if(D.is_block(value)) return []
if(Array.isArray(value)) return value
if(typeof value == 'object') return D.obj_to_array(value)
if(value === false) return [] // hmmm...
if(!D.is_nice(value)) return [] // double hmmm.
return [value]
// if(D.is_block(value)) return new D.Data([])
// if(Array.isArray(value)) return new D.Data(value)
// if(typeof value == 'object') return new D.Data(D.obj_to_array(value))
// if(value === false) return new D.Data([]) // hmmm...
// if(!D.is_nice(value)) return new D.Data([]) // double hmmm.
// return new D.Data([value])
}
D.obj_to_array = function(obj) { // DATA
var arr = []
for(var key in obj)
arr.push(obj[key])
return arr
}
D.sort_object_keys = function(obj, sorter) { // DATA
if(typeof obj != 'object')
return {}
var newobj = {}
, keys = Object.keys(obj).sort(sorter)
for(var i=0, l=keys.length; i < l; i++)
newobj[keys[i]] = obj[keys[i]]
return newobj
}
D.blockify = function(value) {
return D.Types['block'](value)
}
D.stringify = function(value) {
return D.Types['string'](value)
}
D.execute_then_stringify = function(value, prior_starter, process) {
if(D.is_block(value)) {
return D.blockify(value)(prior_starter, {}, process)
} else {
return D.stringify(value)
}
}
D.is_false = function(value) {
if(!value)
return true // '', 0, false, NaN, null, undefined
if(typeof value != 'object')
return false // THINK: is this always right?
if(Array.isArray(value))
return !value.length
if(!D.is_empty(value))
return false
return true
}
D.is_empty = function(value) {
for(var key in value)
if(value.hasOwnProperty(key))
return false
return true
}
D.is_nice = function(value) {
return value || value == false // not NaN, null, or undefined
}
D.is_segment = function(value) {
return value instanceof D.Segment
}
D.is_block = function(value) {
if(!D.is_segment(value)) // THINK: this prevents block hijacking (by making an object shaped
return false // like a block), but requires us to e.g. convert all incoming
// JSONified block segments to real segments.
return value && value.type == 'Block'
&& value.value && value.value.id // THINK: why do we need this?
}
D.is_numeric = function(value) {
return (typeof(value) === 'number' || typeof(value) === 'string') && value !== '' && !isNaN(value)
}
D.to_numeric = function(value) {
if(value === '0') return 0
if(typeof value == 'number') return value
if(typeof value == 'string') return +value ? +value : 0
return 0
}
D.is_regex = function(str) {
var regex_regex = /^\/.+?\/(g|i|gi|m|gm|im|gim)?$/
return regex_regex.test(str)
}
D.regex_escape = function(str) {
var specials = /[.*+?|()\[\]{}\\$^]/g // .*+?|()[]{}\$^
return str.replace(specials, "\\$&")
}
D.string_to_regex = function(string, global) {
if(!D.is_regex(string))
return RegExp(D.regex_escape(string), (global ? 'g' : ''))
var flags = string.slice(string.lastIndexOf('/') + 1)
string = string.slice(1, string.lastIndexOf('/'))
return RegExp(string, flags)
}
D.shallow_copy = function(value) {
if(Array.isArray(value))
return value.slice()
return JSON.parse(JSON.stringify(value)) // NOTE: only for scrubbed values!
}
D.get_unique_symbol = function() {
return D.Etc.unique_counter = ++D.Etc.unique_counter || 0
}
D.clone = function(value) {
if(value && value.toJSON) // THINK: for blocks?
return D.deep_copy(value)
try {
return JSON.parse(JSON.stringify(value))
} catch (e) {
return D.deep_copy(value)
}
}
D.deep_copy = function(value) {
// deep copy an internal variable (primitives and blocks only)
if(!value || typeof value != 'object') return value // number, string, or boolean
if(D.is_block(value)) return value // blocks are immutable, so pass-by-ref is ok.
return D.recursive_leaves_copy(value, D.deep_copy)
}
D.recursive_leaves_copy = function(values, fun, seen) {
// apply a function to every leaf of a tree, but generate a new copy of it as we go
// THINK: only used by D.deep_copy, which we maybe don't need anymore
if(!values || typeof values != 'object') return fun(values);
seen = seen || []; // only YOU can prevent infinite recursion...
if(seen.indexOf(values) !== -1) return values;
seen.push(values);
var new_values = (Array.isArray(values) ? [] : {}); // NOTE: using new_values in the parse phase (rebuilding the object each time we hit this function) causes an order-of-magnitude slowdown. zoiks, indeed.
for(var key in values) {
// try { // NOTE: accessing e.g. input.selectionDirection throws an error, which is super-duper lame
// FIXME: with 'try' this reliably crashes chrome when called in the above instance. ={
var val = values[key]
// this is only called from toPrimitive and deep_copy, which both want blocks
if(D.is_block(val)) {
new_values[key] = fun(val); // blocks are immutable
} else if(D.is_segment(val)) {
new_values[key] = new D.Segment(val.type, val.value, val)
} else if(typeof val == 'object') {
new_values[key] = D.recursive_leaves_copy(val, fun, seen);
} else {
new_values[key] = fun(val);
}
// } catch(e) {D.on_error(e)}
}
return new_values;
};
D.extend = function(base, value) {
// NOTE: this extends by reference, but also returns the new value
for(var key in value) {
if(!value.hasOwnProperty(key)) continue
base[key] = value[key]
}
return base
}
D.recursive_extend = function(base, value) {
// NOTE: this extends by reference, but also returns the new value
for(var key in value) {
if(!value.hasOwnProperty(key)) continue
if(typeof base[key] == 'undefined') {
base[key] = value[key]
continue
}
if(typeof base[key] != 'object') continue // ignore scalars in base
if(typeof value[key] != 'object') continue // can't recurse into scalar
if(Array.isArray(base) && Array.isArray(value)) {
if(base[key] == value[key]) continue
base.push(value[key])
continue // THINK: this bit is pretty specialized for my use case -- can we make it more general?
}
D.recursive_extend(base[key], value[key])
}
return base
}
D.scrub_var = function(value) {
// copy and scrub a variable from the outside world
try {
// FIREFOX DOESN'T THROW ON DOM OBJECTS
// THINK: this is getting really sloppy. how can we simplify?
if(value instanceof Event || value instanceof Node || value instanceof HTMLElement) {
value = D.mean_defunctionize(value);
if(value === null) value = false;
return value;
}
return JSON.parse(JSON.stringify(value)); // this style of copying is A) the fastest deep copy on most platforms and B) gets rid of functions, which in this case is good (because we're importing from the outside world) and C) ignores prototypes (also good). // DATA
} catch (e) {
// D.on_error('Your object has circular references'); // this might get thrown a lot... need lower priority warnings
value = D.mean_defunctionize(value);
if(value === null) value = false;
return value;
}
};
D.mean_defunctionize = function(values, seen) {
// this trashes funs and snips circular refs
if(!D.is_nice(values)) return false;
if(!values) return values;
if(typeof values == 'function') return null;
if(typeof values != 'object') return values; // number, string, or boolean
var type = values.constructor.toString().split(' ')[1]
if(type) {
var sig = type.slice(0,3) // prevents DOM yuckyucks. details here:
if ( sig == "Nod" // https://github.com/dxnn/daimio/issues/1
|| sig == "HTM" // THINK: can this still leak too much info?
|| sig == "win"
|| sig == "Win"
|| sig == "Mim"
|| sig == "DOM" )
return null
}
seen = seen || [];
if(seen.indexOf(values) !== -1) return null; // only YOU can prevent infinite recursion
seen.push(values);
var new_values = (Array.isArray(values) ? [] : {});
for(var key in values) { // list or hash: lish. lash. hist? hast? grumble.
var new_value, value = values[key];
new_value = D.mean_defunctionize(value, seen);
if(new_value === null) continue;
new_values[key] = new_value;
}
return new_values;
};
D.get_block = function(ablock_or_segment) {
// this is only used in D.Space.prototype.execute
if(!ablock_or_segment)
return new D.Block()
if(ablock_or_segment.segments)
return ablock_or_segment
else if(ablock_or_segment.value && ablock_or_segment.value.id && D.BLOCKS[ablock_or_segment.value.id])
return D.BLOCKS[ablock_or_segment.value.id]
else
return new D.Block()
}
D.data_trampoline = function(data, processfun, joinerfun, prior_starter, finalfun) {
/*
This *either* returns a value or calls prior_starter and returns NaN.
It *always* calls finalfun if it is provided.
Used in small doses it makes your possibly-async command logic much simpler.
*/
var keys = Object.keys(data)
, size = keys.length
, index = -1
, result = joinerfun()
, asynced = false
, value, key
// if(typeof finalfun != 'function') {
// finalfun = function(x) {return x}
// }
finalfun = finalfun || D.identity
// THINK: can we add a simple short-circuit to this? undefined, maybe? for things like 'first' and 'every' it'll help a lot over big data
var inner = function() {
while(++index < size) {
key = keys[index]
value = processfun(data[key], my_starter, key, result)
if(value !== value) {
asynced = true // we'll need to call prior_starter when we finish up
return NaN // send stack killer up the chain
// [unleash the NaNobots|NaNites]
}
result = joinerfun(result, value, key)
}
if(asynced)
return prior_starter(finalfun(result))
return finalfun(result)
}
var my_starter = function(value) {
result = joinerfun(result, value, key)
inner()
}
// might need a fun for sorting object properties...
return inner()
}
D.string_concat = function(total, value) {
total = D.make_nice(total)
value = D.make_nice(value)
return D.stringify(total) + D.stringify(value)
}
D.list_push = function(total, value) { // DATA
if(!Array.isArray(total)) return [] // THINK: is this always ok?
value = D.make_nice(value)
total.push(value)
return total
}
D.list_set = function(total, value, key) { // DATA
if(typeof total != 'object') return {}
if(!key) key = Object.keys(total).length
value = D.make_nice(value)
total[key] = value
return total
}
D.scrub_list = function(list) {
var keys = Object.keys(list)
if(keys.reduce(function(acc, val) {if(acc == val) return acc+1; else return -1}, 0) == -1)
return list
return D.to_array(list)
}
D.mungeLR = function(items, fun) {
// give each item its time in the sun. also, allow other items to be added, removed, reordered or generally mangled
var L = []
, R = items
, item = {}
, result = []
if(!items.length) return items
do {
item = R.shift() // OPT: shift is slow
result = fun(L, item, R)
L = result[0]
R = result[1]
} while(R.length)
return L
}
D.nicify = function(list, state) {
var result = []
for(var i=0, l=list.length; i < l; i++) {
var item = state[list[i]]
result.push( D.is_nice(item) ? item : null ) // THINK: why null?
}
return result
}
D.filter_ports = function(ports, station, name) {
for(var i=0, l=ports.length; i < l; i++) {
var port = ports[i]
if( port.station === station // triple so undefined !== 0
&& port.name === name )
return port
}
}
D.run = function(daimio, space, scope, ultimate_callback) {
// This is *always* async, so provide a callback.
if(!daimio) return ""
daimio = "" + daimio // TODO: ensure this is a string in a nicer fashion...
if(typeof ultimate_callback != 'function') {
if(!space)
space = ultimate_callback
ultimate_callback = null
}
if(!space) {
space = D.ExecutionSpace
}
if(!ultimate_callback) {
ultimate_callback = function(result) {
// THINK: what should we do here?
console.log(result)
}
}
// THINK: can we refactor this into a different type of space.execute? can we convert this whole thing into a temporary channel on the space? with a 'log' type gateway or something?
var prior_starter = function(value) {
var result = D.execute_then_stringify(value, ultimate_callback)
if(result === result)
ultimate_callback(result)
}
var result = space.execute(D.Parser.string_to_block_segment(daimio), scope, prior_starter)
if(result === result)
prior_starter(result)
return ""
}
if (typeof exports !== 'undefined') {
// TODO: make this work!
// var murmurhash = require('murmurhash3')
if (typeof module !== 'undefined' && module.exports)
exports = module.exports = D
exports.D = D
}
/*ooo ooo ooooo ooooooooo. .oooooo. ooooooooo. ooooooooooooo .oooooo..o
`888' `88. .888' `888 `Y88. d8P' `Y8b `888 `Y88. 8' 888 `8 d8P' `Y8
888 888b d'888 888 .d88' 888 888 888 .d88' 888 Y88bo.
888 8 Y88. .P 888 888ooo88P' 888 888 888ooo88P' 888 `"Y8888o.
888 8 `888' 888 888 888 888 888`88b. 888 `"Y88b
888 8 Y 888 888 `88b d88' 888 `88b. 888 oo .d8P
o888o o8o o888o o888o `Y8bood8P' o888o o888o o888o 8""88888*/
// ______ _______ _______ _____ ______ _______ _______ _____ ______ _______
// | \ |______ | | | |_____/ |_____| | | | |_____/ |______
// |_____/ |______ |_____ |_____| | \_ | | | |_____| | \_ ______|
//
D.add_decorator = function(block_id, type, value, unique) {
var decorator = { block: block_id
, type: type
, value: value }
, existing_decorators
if(unique) {
existing_decorators = D.get_decorators(block_id, type)
if(existing_decorators && existing_decorators.length) {
return existing_decorators[0]
}
}
if(!D.DecoratorIndices.ByType[type]) {
D.DecoratorIndices.ByType[type] = []
}
if(!D.DecoratorIndices.ByBlock[block_id]) {
D.DecoratorIndices.ByBlock[block_id] = []
}
if(!D.DecoratorIndices.ByTypeBlock[type + '-' + block_id]) {
D.DecoratorIndices.ByTypeBlock[type + '-' + block_id] = []
}
D.DECORATORS.push(decorator)
D.DecoratorIndices.ByType[type].push(decorator)
D.DecoratorIndices.ByBlock[block_id].push(decorator)
D.DecoratorIndices.ByTypeBlock[type + '-' + block_id].push(decorator)
return decorator
}
D.get_decorators = function(by_block, by_type) {
var decorators = D.DECORATORS
if(!by_block) {
if(by_type) {
decorators = D.DecoratorIndices.ByType[by_type]
}
}
else {
if(by_type) {
decorators = D.DecoratorIndices.ByTypeBlock[by_type + '-' + by_block]
} else {
decorators = D.DecoratorIndices.ByBlock[by_block]
}
}
return decorators
}
// _____ _____ ______ _______ _______
// |_____] | | |_____/ | |______
// | |_____| | \_ | ______|
//
// A port flavour has a dir [in, out, out/in, in/out (inback outback? up down?)], and dock and add functions
D.track_event = function(type, selector, parent, callback, options) {
// options contains:
// 'scrub' -- a callback to be used instead of the standard value detector
// 'nochain' -- a boolean flag that prevents walking the parent chain [YAGNI]
// 'passthru' -- a boolean flag which causes events to keep their default behavior
/*
changes:
- allow 'document' itself as a valid selector
- allow a 'parent' element (and set the listener on the parent instead of on document)
- a passthru param that pushes the event back in to the stream and marks it so it isn't caught again
- a 'scrub' callback to be used instead of the standard value detector
TODO:
- test value selector and scrubber
- test parent setting
- test passthru
*/
options = options || {}
D.Etc.events = D.Etc.events || {}
if(!D.Etc.events[type]) {
D.Etc.events[type] = {by_class: {}, by_id: {}}
parent = parent ? document.getElementById(parent) : document
parent.addEventListener(type, function(event) {
var target = event.target
var particulars
var cname
if(event.passthru) return true
// walk the target.parentNode chain up to null, checking each item along the way until you find one
// OPT: make walking the parent chain optional (use a port param to ask for it)
while(!particulars && target) {
particulars = tracked.by_id[target.id]
if(particulars) break
cname = target.className
if(cname) {
cname = cname.hasOwnProperty('baseVal') ? cname.baseVal : cname
cname.split(/\s+/).forEach(function(name) {
particulars = particulars || tracked.by_class[name] // TODO: take all matches instead of just first
})
}
if(particulars) break
target = target.parentNode
}
if(!particulars) return true
if(particulars.passthru) {
event.passthru = true
} else {
event.stopPropagation()
event.preventDefault()
}
var value =
particulars.scrub
? particulars.scrub(event, target)
: D.default_scrub(event, target)
particulars.callback(value, event)
}, false)
}
var tracked = D.Etc.events[type]
var particulars = {callback: callback, scrub: options.scrub, passthru: options.passthru}
if(selector[0] == '.') {
tracked.by_class[selector.slice(1)] = particulars
} else {
tracked.by_id[selector] = particulars
}
}
D.untrack_event = function(type, target, parent, callback) {
if(!D.Etc.events) return false
if(!D.Etc.events[type]) return false
var tracked = D.Etc.events[type]
var obj = target[0] == '.' ? tracked.by_class : tracked.by_id
if(!obj || !obj[target]) return false
if(callback && obj[target] != callback) return false
delete obj[target]
}
D.default_scrub = function(event, target) {
return target.attributes['data-value'] // it's easy to read if you think of
? target.attributes['data-value'].value // this like a quasi-cond statement.
: target.value != undefined
? target.value
: target.attributes.value
&& target.attributes.value.value
|| target.text
|| D.scrub_var(event)
|| true
}
D.send_value_to_js_port = function(space, port_name, value, port_flavour) {
port_flavour = port_flavour || 'from-js'
for ( var i=0, l=space.ports.length; i < l; i++)
if( space.ports[i].name == port_name
&& space.ports[i].flavour == port_flavour )
{ space.ports[i].pair.enter(value)
return true }
return false
}
D.port_standard_exit = function(ship) {
var self = this
, outs = this.outs
// THINK: this makes the interface feel more responsive on big pages, but is it the right thing to do?
if(this.space)
// D.setImmediate(this.outs, ship) // OPT
D.setImmediate(function() {
for(var i=0, l=outs.length; i < l; i++) {
outs[i].enter(ship)
}
// outs.forEach(function(port) { port.enter(ship) })
})
else
this.outside_exit(ship) // ORLY? No delay?
}
D.port_standard_pairup = function(port) {
this.pair = port
port.pair = this
}
D.port_standard_enter = function(ship, process) {
if(process && process.state && process.state.secret) { // for exec ports
process.state.secret.result = ship
ship = D.clone(process.state.secret)
}
if(this.pair)
return this.pair.exit(ship)
if(!this.station)
return D.set_error('Every port must have a pair or a station')
this.space.dock(ship, this.station) // THINK: always async...?
}
D.port_standard_sync = function(ship, callback) {
var out = this.outs[0]
, pair = this.pair
D.setImmediate(function() {
if(!pair) // station port
return out ? out.sync(ship, callback) : ''
if(!pair.space) // outside port
return pair.outside_exit(ship, callback)
return pair.sync(ship, callback) // space port
})
return NaN
}
D.import_port_flavour = function(flavourname, pflav) {
if(D.PortFlavours[flavourname])
return D.set_error('That port flavour has already been im-port-ed')
// TODO: just use Port or something as a proto for pflav, then the fall-through is automatic
if(!pflav)
return D.set_error('That flavour is not desirable')
if(!pflav.settings) // settings are params for port construction
pflav.settings = [] // THINK: error if no settings?
if(typeof pflav.add != 'function')
pflav.add = D.noop // noop, so we can call w/o checking
if(typeof pflav.exit != 'function')
pflav.exit = D.port_standard_exit
if(typeof pflav.outside_add != 'function')
pflav.outside_add = D.noop
if(typeof pflav.outside_exit != 'function')
pflav.outside_exit = D.noop
if(typeof pflav.pairup != 'function')
pflav.pairup = D.port_standard_pairup
if(typeof pflav.enter != 'function')
pflav.enter = D.port_standard_enter
if(typeof pflav.sync != 'function' && pflav.dir == 'down')
pflav.sync = D.port_standard_sync
// if([pflav.enter, pflav.add].every(function(v) {return typeof v == 'function'}))
// return D.set_error("That port flavour's properties are invalid")
D.PortFlavours[flavourname] = pflav
return true
}
// _______ _______ __ _ _______ _____ _______ _______
// |______ |_____| | \ | | | |______ |______
// | | | | \_| |_____ __|__ |______ ______|
//
D.import_fancy = function(ch, obj) {
if(typeof ch != 'string') return D.on_error('Fancy character must be a string')
// ch = ch[0] // only first char matters
if(!D.Fancies[ch]) {
// TODO: check obj.eat
D.Fancies[ch] = obj
} else {
D.set_error('Your fancies are more borken')
}
D.Etc.FancyRegex = RegExp(Object.keys(D.Fancies)
.sort(function(a, b) {return a.length - b.length})
.map(function(str) {return '^' + D.regex_escape(str) + '\\w'})
.join('|'))
}
D.import_fancy(':', {
eat: function(token) {
token.type = 'String'
token.value = token.value.slice(1)
return [token] // reuse the existing token to retain the inputs and key and whatnot
}
})
D.import_fancy('>@', {
eat: function(token) {
// TODO: throw a runtime error if it's not a valid port
token.type = 'PortSend'
token.value = {to: token.value.slice(2)}
return [token]
}
})
D.import_fancy('>$', {
eat: function(token) {
// TODO: change path to name, make >$foo set foo, make >$foo.baz.baa -> list poke path (:baz :baa) data $foo value __ | >$foo
var pieces = D.Parser.split_on(token.value, '.')
, name = pieces.shift().slice(2)
, poke_tokens = []
token.type = 'VariableSet'
token.value = {type: 'space', name: name}
if(pieces.length) {
pieces = pieces.map(function(item) {
return item[0] != '{'
? '"' + item + '"'
: item
})
var path = new D.Token('List', pieces.join(' '))
, poker = new D.Token('Command', 'list poke data $' + name)
poker.names = ['path', 'value']
poker.inputs = [path.key, token.prevkey]
token.names = ['value']
token.inputs = [poker.key]
poke_tokens = [path, poker]
}
return poke_tokens.concat(token)
}
})
D.import_fancy('>', {
eat: function(token) {
// TODO: THROW AN ERROR IF IT ALREADY EXISTS IN THE PROCESS
// NOTE: this doesn't need {list poke} because you can only set it once
token.type = 'VariableSet'
token.value = {type: 'pipeline', name: token.value.slice(1)}
return [token]
}
})
D.import_fancy('__', {
eat: function(token) {
token.type = 'PipeVar'
// if(token.value == '__') // regular magic pipe
// return [token]
// token.value = '__' // TODO: this probably isn't right
// token.value = token.value.slice(1)
var pieces = D.Parser.split_on(token.value, '.')
token.value = pieces.shift()
if(token.value != '__' && token.value != '__in') {
D.set_error('Only __ and __in are allow to start with __')
return []
}
return [token].concat(D.eat_fancy_var_pieces(pieces, token))
}
})
D.import_fancy('_', {
eat: function(token) {
return D.eat_fancy_var(token, 'pipeline')
}
})
D.import_fancy('$', {
eat: function(token) {
return D.eat_fancy_var(token, 'space')
}
})
D.eat_fancy_var = function(token, type) {
var pieces = D.Parser.split_on(token.value, '.')
var name = pieces.shift().slice(1)
token.type = 'Variable'
token.value = {type: type, name: name}
return [token].concat(D.eat_fancy_var_pieces(pieces, token))
}
D.eat_fancy_var_pieces = function(pieces, token) {
if(!pieces.length)
return []
// inline peek filtering