-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelt.js
More file actions
3973 lines (3961 loc) · 145 KB
/
elt.js
File metadata and controls
3973 lines (3961 loc) · 145 KB
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.elt = {}));
}(this, (function (exports) { 'use strict';
/**
* Does a naive foreach on an IndexableArray
* @param _arr the array
* @param fn the function to apply
* @internal
*/
function EACH(_arr, fn) {
for (var i = 0, arr = _arr.arr; i < arr.length; i++) {
var item = arr[i];
if (item == null)
continue;
fn(item);
}
_arr.actualize();
}
/**
* An array wrapper that infects its elements with their indexes for faster deletion.
* @internal
*/
class IndexableArray {
constructor() {
this.arr = [];
this.real_size = 0;
}
add(a) {
const arr = this.arr;
if (a.idx != null) {
// will be put to the end
arr[a.idx] = null;
}
else {
this.real_size++;
}
a.idx = arr.length;
arr.push(a);
}
actualize() {
const arr = this.arr;
if (this.real_size !== arr.length) {
var newarr = new Array(this.real_size);
for (var i = 0, j = 0, l = arr.length; i < l; i++) {
var item = arr[i];
if (item == null)
continue;
newarr[j] = item;
item.idx = j;
j++;
}
this.arr = newarr;
}
}
delete(a) {
if (a.idx != null) {
this.arr[a.idx] = null;
a.idx = null;
this.real_size--;
}
}
clear() {
const a = this.arr;
for (var i = 0; i < a.length; i++) {
var item = a[i];
if (item == null)
continue;
item.idx = null;
}
this.arr = [];
this.real_size = 0;
}
}
/**
* Make sure we have a usable observable.
* @returns The original observable if `arg` already was one, or a new
* Observable holding the value of `arg` if it wasn't.
* @category observable, toc
*/
function o(arg) {
return arg instanceof o.Observable ? arg : new o.Observable(arg);
}
(function (o_1) {
/**
* A constant symbol representing the fact that there is no value.
*
* Used in Observers and combined observables to know when a value has been set for the first time.
*/
o_1.NoValue = Symbol('NoValue');
function isReadonlyObservable(_) {
return _ instanceof Observable;
}
o_1.isReadonlyObservable = isReadonlyObservable;
/**
* An `Observer` observes an [[o.Observable]]. `Observable`s maintain a list of **active**
* observers that are observing it. Whenever their value change, all the registered
* `Observer`s have their `refresh` method called.
*
* An `Observer` is built with a function that will be called when it is refreshed and
* the value **changed** from the previous value it knew.
*
* This behaviour has implications for memory usage ; all `Observers` keep a reference
* to the last value they were called with, since this is the value they will pass as
* the `old_value` to their wrapped function.
*
* They behave this way because an Observer can be stopped and then started again.
* In between, the observable they watch could have been changed several times. The `fn`
* function they wrap may make assumptions on what value it has seen itself. Thus,
* by keeping a reference to the last value they were called with, they can provide it
* safely to `fn`.
*
* @category observable, toc
*/
class Observer {
/**
* Build an observer that will call `fn` whenever the value contained by
* `observable` changes.
*/
constructor(fn, observable) {
this.observable = observable;
/**
* The last value they've been called with.
*/
this.old_value = o_1.NoValue;
/**
* Used to speed up access
* @internal
*/
this.idx = null;
this.fn = fn;
}
/**
* Called by the `observable` currently being watched.
*/
refresh() {
const old = this.old_value;
const new_value = this.observable._value;
if (old !== new_value) {
// only store the old_value if the observer will need it. Useful to not keep
// useless references in memory.
this.old_value = new_value;
this.fn(new_value, old);
}
}
/**
* Register on the `observable` to be `refresh`ed whenever it changes.
*/
startObserving() {
this.observable.addObserver(this);
}
/**
* Stop being notified by the observable.
*/
stopObserving() {
this.observable.removeObserver(this);
}
/**
* Debounce `this.refresh` by `ms` milliseconds, optionnally calling it
* immediately the first time around if `leading` is true.
*
* See [[o.debounce]].
*/
debounce(ms, leading) {
this.refresh = o.debounce(this.refresh.bind(this), ms, leading);
return this;
}
/**
* Throttle `this.refresh` by `ms` milliseconds, optionnally calling it
* immediately the first time around if `leading` is true.
*
* See [[o.throttle]].
*/
throttle(ms, leading) {
this.refresh = o.throttle(this.refresh.bind(this), ms, leading);
return this;
}
}
o_1.Observer = Observer;
/** @internal */
function each_recursive(obs, fn) {
var objs = [];
var stack = [];
var [children, i] = [obs._children.arr, 0];
objs.push(obs);
while (true) {
var _child = children[i];
if (_child) {
var child = _child.child;
var subchildren = child._children.arr;
objs.push(child);
if (subchildren.length) {
stack.push([children, i + 1]);
children = subchildren;
i = 0;
continue;
}
}
i++;
if (i > children.length) {
if (stack.length === 0)
break;
[children, i] = stack.pop();
continue;
}
}
for (var i = 0, l = objs.length; i < l; i++) {
fn(objs[i]);
}
}
o_1.each_recursive = each_recursive;
/** @internal */
class Queue extends IndexableArray {
constructor() {
super(...arguments);
this.transaction_count = 0;
}
schedule(obs) {
const was_empty = this.real_size === 0;
each_recursive(obs, ob => {
this.add(ob);
});
if (this.transaction_count === 0 && was_empty) {
this.flush();
}
}
unschedule(obs) {
each_recursive(obs, ob => this.delete(ob));
}
transaction(fn) {
this.transaction_count++;
fn();
this.transaction_count--;
if (this.transaction_count === 0) {
this.flush();
}
}
flush() {
for (var i = 0, arr = this.arr; i < arr.length; i++) {
var obs = arr[i];
if (obs == null)
continue;
if (obs instanceof CombinedObservable) {
obs._value = obs.getter(obs._parents_values);
}
EACH(obs._children, ch => {
ch.child._parents_values[ch.child_idx] = ch.parent._value;
});
EACH(obs._observers, o => o.refresh());
obs.idx = null;
arr[i] = null; // just in case...
}
this.real_size = 0;
// this.arr = []
this.arr.length = 0;
this.transaction_count = 0;
}
}
o_1.Queue = Queue;
/** @internal */
const queue = new Queue();
/**
* Start an observable transaction, where the observers of all the observables being
* set or assigned to during the callback are only called at the end.
*
* Use it when you know you will modify two or more observables that trigger the same transforms
* to avoid calling the observers each time one of the observable is modified.
*
* ```tsx
* @include ../examples/o.transaction.tsx
* ```
*
* @category observable, toc
*/
function transaction(fn) {
queue.transaction(fn);
}
o_1.transaction = transaction;
/** @internal */
class ChildObservableLink {
constructor(parent, child, child_idx) {
this.parent = parent;
this.child = child;
this.child_idx = child_idx;
this.idx = null;
}
refresh() {
this.child._parents_values[this.child_idx] = this.parent._value;
}
}
o_1.ChildObservableLink = ChildObservableLink;
/**
* The "writable" version of an Observable, counter-part to the `#o.ReadonlyObservable`.
*
* Comes with the `.set()` and `.assign()` methods.
*
* @category observable, toc
*/
class Observable {
/**
* Build an observable from a value. For readability purposes, use the [[o]] function instead.
*/
constructor(_value) {
this._value = _value;
/** @internal */
this._observers = new IndexableArray();
/** @internal */
this._children = new IndexableArray();
/** @internal */
this._watched = false;
/** The index of this Observable in the notify queue. If null, means that it's not scheduled.
* @internal
*/
this.idx = null;
// (this as any).debug = new Error
}
/**
* Stop this Observable from observing other observables and stop
* all observers currently watching this Observable.
*/
stopObservers() {
each_recursive(this, ob => {
if (ob.idx)
queue.delete(ob);
ob._observers.clear();
if (ob._watched) {
ob._watched = false;
ob.unwatched();
}
ob._children.clear();
});
}
/**
* Return the underlying value of this Observable
*
* NOTE: treat this value as being entirely readonly !
*/
get() {
return this._value;
}
/**
* Set the value of the observable and notify the observers listening
* to this object of this new value.
*/
set(value) {
const old = this._value;
this._value = value;
if (old !== value)
queue.schedule(this);
}
/**
* Convenience function to set the value of this observable depending on its
* current value.
*
* The result of `fn` **must** be absolutely different from the current value. Arrays
* should be `slice`d first and objects copied, otherwise the observable will not
* trigger its observers since to it the object didn't change. For convenience, you can
* use [[o.clone]] or the great [immer.js](https://github.com/immerjs/immer).
*
* If the return value of `fn` is [[o.NoValue]] then the observable is untouched.
*/
mutate(fn) {
const n = fn(this._value);
if (n !== o_1.NoValue) {
this.set(n);
}
}
assign(partial) {
this.set(o.assign(this.get(), partial));
}
/**
* Create an observer bound to this observable, but do not start it.
* For it to start observing, one needs to call its `startObserving()` method.
*
* > **Note**: This method should rarely be used. Prefer using [[$observe]], [[node_observe]], [`Mixin#observe`](#o.ObserverHolder#observe) or [`App.Service#observe`](#o.ObserverHolder#observe) for observing values.
*/
createObserver(fn) {
return new Observer(fn, this);
}
addObserver(_ob) {
if (typeof _ob === 'function') {
_ob = this.createObserver(_ob);
}
const ob = _ob;
this._observers.add(_ob);
this.checkWatch();
if (this.idx == null)
ob.refresh();
return ob;
}
/**
* Add a child observable to this observable that will depend on it to build its own value.
* @internal
*/
addChild(ch) {
if (ch.idx != null)
return;
this._children.add(ch);
if (this.idx != null)
queue.add(ch.child);
this.checkWatch();
}
/**
* @internal
*/
removeChild(ch) {
if (ch.idx == null)
return;
this._children.delete(ch);
this.checkWatch();
}
/**
* Remove an observer from this observable. This means the Observer will not
* be called anymore when this Observable changes.
*
* If there are no more observers watching this Observable, then it will stop
* watching other Observables in turn if it did.
*
*/
removeObserver(ob) {
this._observers.delete(ob);
this.checkWatch();
}
/**
* Check if this `Observable` is being watched or not. If it stopped being observed but is in the notification
* queue, remove it from there as no one is expecting its value.
*
* @internal
*/
checkWatch() {
if (this._watched && this._observers.real_size === 0 && this._children.real_size === 0) {
this._watched = false;
if (this.idx != null)
queue.delete(this);
this.unwatched();
}
else if (!this._watched && this._observers.real_size + this._children.real_size > 0) {
this._watched = true;
this.watched();
}
}
/**
* @internal
*/
unwatched() { }
/**
* @internal
*/
watched() { }
tf(transform) {
var old = o_1.NoValue;
var old_transform = o_1.NoValue;
var curval = o_1.NoValue;
return combine([this, transform], ([v, fnget]) => {
if (old !== o_1.NoValue && old_transform !== o_1.NoValue && curval !== o_1.NoValue && old === v && old_transform === fnget)
return curval;
curval = (typeof fnget === 'function' ? fnget(v, old, curval) : fnget.transform(v, old, curval));
old = v;
old_transform = fnget;
return curval;
}, (newv, old, [curr, conv]) => {
if (typeof conv === 'function')
return tuple(o_1.NoValue, o_1.NoValue);
var new_orig = conv.revert(newv, old, curr);
return tuple(new_orig, o.NoValue);
});
}
/**
* Create an observable that will hold the value of the property specified with `key`.
* The resulting observable is completely bi-directional.
*
* The `key` can itself be an observable, in which case the resulting observable will
* change whenever either `key` or the original observable change.
*
* ```tsx
* @include ../examples/o.observable.p.tsx
* ```
*/
p(key) {
return prop(this, key);
}
key(key, def, delete_on_undefined = true) {
return combine([this, key, def, delete_on_undefined], ([map, key, def]) => {
var res = map.get(key);
if (res === undefined && def) {
res = def(key, map);
}
return res;
}, (ret, _, [omap, okey, _2, delete_on_undefined]) => {
var result = new Map(omap); //.set(okey, ret)
// Is this correct ? should I **delete** when I encounter undefined ?
if (ret !== undefined || !delete_on_undefined)
result.set(okey, ret);
else
result.delete(okey);
return tuple(result, o_1.NoValue, o_1.NoValue, o_1.NoValue);
});
}
}
o_1.Observable = Observable;
/**
* An observable that does not its own value, but that depends
* from outside getters and setters. The `#o.virtual` helper makes creating them easier.
*
* @internal
*/
class CombinedObservable extends Observable {
constructor(deps) {
super(o_1.NoValue);
/** @internal */
this._links = [];
/** @internal */
this._parents_values = [];
this.dependsOn(deps);
}
getter(values) {
return values.slice();
}
setter(nval, oval, last) {
return nval; // by default, just forward the type
}
watched() {
const p = this._parents_values;
for (var i = 0, l = this._links; i < l.length; i++) {
var link = l[i];
link.parent.addChild(link);
p[link.child_idx] = link.parent._value;
}
this._value = this.getter(p);
}
unwatched() {
for (var i = 0, l = this._links; i < l.length; i++) {
var link = l[i];
link.parent.removeChild(link);
}
}
refreshParentValues() {
var changed = false;
for (var i = 0, l = this._links, p = this._parents_values; i < l.length; i++) {
var link = l[i];
var idx = link.child_idx;
var old = p[idx];
var n = link.parent.get();
if (old !== n) {
changed = true;
p[idx] = n;
}
}
return changed;
}
get() {
if (!this._watched) {
if (this.refreshParentValues() || this._value === o_1.NoValue) {
this._value = this.getter(this._parents_values);
}
}
return this._value;
}
set(value) {
// Do not trigger the set chain if the value did not change.
if (!this._watched)
this._value = this.getter(this._parents_values);
if (value === this._value)
return;
const old_value = this._value;
if (!this._watched)
this.refreshParentValues();
const res = this.setter(value, old_value, this._parents_values);
if (res == undefined)
return;
for (var i = 0, l = this._links, len = l.length; i < len; i++) {
var link = l[i];
var newval = res[link.child_idx];
if (newval !== o_1.NoValue && newval !== link.parent._value) {
link.parent.set(newval);
}
}
}
dependsOn(obs) {
var p = new Array(obs.length);
var ch = [];
for (var l = obs.length, i = 0; i < l; i++) {
var ob = obs[i];
if (ob instanceof Observable) {
p[i] = ob._value;
ch.push(new ChildObservableLink(ob, this, ch.length));
}
else {
p[i] = ob;
}
}
this._links = ch;
this._parents_values = p;
return this;
}
}
o_1.CombinedObservable = CombinedObservable;
function combine(deps, get, set) {
var virt = new CombinedObservable(deps);
virt.getter = get;
virt.setter = set; // force undefined to trigger errors for readonly observables.
return virt;
}
o_1.combine = combine;
function merge(obj) {
const keys = Object.keys(obj);
const parents = keys.map(k => obj[k]);
return combine(parents, args => {
var res = {};
for (var i = 0; i < keys.length; i++) {
res[keys[i]] = args[i];
}
return res;
}, back => keys.map(k => back[k]));
}
o_1.merge = merge;
/**
* Create an observable that watches a `prop` from `obj`, giving returning the result
* of `def` if the value was `undefined`.
* @category observable, toc
*/
function prop(obj, prop, def) {
return combine(tuple(obj, prop, def), ([obj, prop, def]) => {
var res = obj[prop];
if (res === undefined && def)
res = def(prop, obj);
return res;
}, (nval, _, [orig, prop]) => {
const newo = o.clone(orig);
newo[prop] = nval;
return tuple(newo, o_1.NoValue, o_1.NoValue);
});
}
o_1.prop = prop;
/**
* Get a MaybeObservable's value
* @returns `arg.get()` if it was an Observable or `arg` itself if it was not.
* @category observable, toc
*/
function get(arg) {
return arg instanceof Observable ? arg.get() : arg;
}
o_1.get = get;
/**
* Do a transform of the provided argument and return a tranformed observable
* only if it was itself observable.
* This function is meant to be used when building components to avoid creating
* Observable objects for values that were not.
* @category observable, toc
*/
function tf(arg, fn) {
if (arg instanceof Observable) {
if (typeof fn === 'function') {
return arg.tf(fn);
}
else
return arg.tf(fn);
}
else {
if (typeof fn === 'function')
return fn(arg, o_1.NoValue, o_1.NoValue);
else
return fn.transform(arg, o_1.NoValue, o_1.NoValue);
}
}
o_1.tf = tf;
function p(mobs, key) {
if (mobs instanceof Observable) {
return mobs.p(key);
}
else {
return mobs[key];
}
}
o_1.p = p;
/**
* Combine several MaybeObservables into an Observable<boolean>
* @returns A boolean Observable that is true when all of them are true, false
* otherwise.
* @category observable, toc
*/
function and(...args) {
return combine(args, (args) => {
for (var i = 0, l = args.length; i < l; i++) {
if (!args[i])
return false;
}
return true;
});
}
o_1.and = and;
/**
* Combine several MaybeObservables into an Observable<boolean>
* @returns A boolean Observable that is true when any of them is true, false
* otherwise.
* @category observable, toc
*/
function or(...args) {
return combine(args, (args) => {
for (var i = 0, l = args.length; i < l; i++) {
if (args[i])
return true;
}
return false;
});
}
o_1.or = or;
function join(...deps) {
return new CombinedObservable(deps);
}
o_1.join = join;
function assign(value, mutator) {
if (mutator == null || typeof mutator !== 'object' || Object.getPrototypeOf(mutator) !== Object.prototype)
return mutator;
if (typeof mutator === 'object') {
var clone = o.clone(value) || {}; // shallow clone
var changed = false;
for (var name in mutator) {
var old_value = clone[name];
var new_value = assign(clone[name], mutator[name]);
changed = changed || old_value !== new_value;
clone[name] = new_value;
}
if (!changed)
return value;
return clone;
}
else {
return value;
}
}
o_1.assign = assign;
function debounce(fn, ms, leading = false) {
var timer;
var prev_res;
var lead = false;
// Called as a method decorator.
if (arguments.length === 1) {
leading = ms;
ms = fn;
return function (target, key, desc) {
var original = desc.value;
desc.value = debounce(original, ms);
};
}
return function (...args) {
if (leading && !lead && !timer) {
prev_res = fn.apply(this, args);
lead = true;
}
if (timer) {
lead = false;
clearTimeout(timer);
}
timer = window.setTimeout(() => {
if (!lead) {
prev_res = fn.apply(this, args);
}
lead = false;
}, ms);
return prev_res;
};
}
o_1.debounce = debounce;
function throttle(fn, ms, leading = false) {
// Called as a method decorator.
if (typeof fn === 'number') {
leading = ms;
ms = fn;
return function (target, key, desc) {
var original = desc.value;
desc.value = throttle(original, ms, leading);
};
}
var timer;
var prev_res;
var last_call = 0;
var _args;
var self;
return function (...args) {
var now = Date.now();
// If the delay expired or if this is the first time this function is called,
// then trigger the call. Otherwise, we will have to set up the call.
if ((leading && last_call === 0) || last_call + ms <= now) {
prev_res = fn.apply(this, args);
last_call = now;
return prev_res;
}
self = this;
_args = args;
if (!timer) {
timer = window.setTimeout(function () {
prev_res = fn.apply(self, _args);
last_call = Date.now();
_args = null;
timer = null;
}, ms - (now - (last_call || now)));
}
return prev_res;
};
}
o_1.throttle = throttle;
/**
* Setup a function that takes no argument and returns a new value
* when cloning should be performed differently than just using `Object.create` and
* copying properties.
*
* ```jsx
* class MyType {
* [o.sym_clone]() {
* return new MyType() // or just anything that returns a clone
* }
* }
* ```
*
* @category observable
*/
o_1.sym_clone = Symbol('o.clone_symbol');
/**
* Returns its arguments as an array but typed as a tuple from Typescript's point of view.
*
* This only exists because there is no way to declare a tuple in Typescript other than with a plain
* array, and arrays with several types end up as an union.
*
* ```tsx
* @include ../examples/o.tuple.tsx
* ```
*
* @category observable, toc
*/
function tuple(...t) {
return t;
}
o_1.tuple = tuple;
function clone(obj) {
if (obj == null || typeof obj === 'number' || typeof obj === 'string' || typeof obj === 'boolean')
return obj;
var clone;
var key;
if (obj[o_1.sym_clone]) {
return obj[o_1.sym_clone]();
}
if (Array.isArray(obj)) {
return obj.slice();
}
if (obj instanceof Date) {
return new Date(obj.getTime()); // timezone ?
}
if (obj instanceof RegExp) {
return new RegExp(obj.source, ''
+ obj.global ? 'g' : ''
+ obj.multiline ? 'm' : ''
+ obj.unicode ? 'u' : ''
+ obj.ignoreCase ? 'i' : ''
+ obj.sticky ? 'y' : '');
}
if (obj instanceof Map) {
return new Map(obj);
}
if (obj instanceof Set) {
return new Set(obj);
}
// If we got here, then we're cloning an object
var prototype = Object.getPrototypeOf(obj);
clone = Object.create(prototype);
for (key of Object.getOwnPropertyNames(obj)) {
// should we check for writability ? enumerability ?
if (obj.propertyIsEnumerable(key))
clone[key] = obj[key];
}
for (var sym of Object.getOwnPropertySymbols(obj)) {
if (obj.propertyIsEnumerable(sym))
clone[sym] = obj[sym];
}
return clone;
}
o_1.clone = clone;
function tfpromise(obs, def) {
var last_promise;
var last_result = def === null || def === void 0 ? void 0 : def();
var res = new CombinedObservable([o(obs)]);
res.getter = ([pro]) => {
if (last_promise === pro)
return last_result;
last_promise = pro;
pro.then(val => {
if (last_promise !== pro)
return;
last_result = val;
queue.schedule(res);
});
return last_result;
};
res.setter = undefined;
return res;
}
o_1.tfpromise = tfpromise;
/**
* Returns a function that accepts a callback. While this callback is running, all subsequent
* calls to the created lock become no-op.
*
* This helper is to be used when have observables which set each other's value in observers,
* which could end up in an infinite loop, or when dealing with DOM Events.
*
* @returns a function that accepts a callback
* @category observable, toc
*/
function exclusive_lock() {
var locked = false;
return function exclusive_lock(fn) {
if (locked)
return;
locked = true;
fn();
locked = false;
};
}
o_1.exclusive_lock = exclusive_lock;
/**
* A helper class that manages a group of observers with a few handy methods
* to all start or stop them from observing.
*
* Meant to be extended by [[Mixin]] and [[App.Service]], or any class that has
* some form of life-cycle (on/off) that it wants to tie observing to.
*
* @category observable, toc
*/
class ObserverHolder {
constructor() {
/** @internal */
this._observers = [];
/** @internal */
this._callback_queue = undefined;
/**
* Boolean indicating if this object is actively observing its observers.
*/
this.is_observing = false;
}
/**
* Start all the observers on this holder
* @internal
*/
startObservers() {
var cbk = this._callback_queue;
if (cbk) {
for (var i = 0, l = cbk.length; i < l; i++) {
cbk[i]();
}
this._callback_queue = undefined;
}
for (var obss = this._observers, i = 0, l = obss.length; i < l; i++) {
obss[i].startObserving();
}
this.is_observing = true;
}
/**
* Stop all the observers on this holder from observing.
*/
stopObservers() {
for (var obss = this._observers, i = 0, l = obss.length; i < l; i++) {
obss[i].stopObserving();
}
this.is_observing = false;
}
/**
* Does pretty much what [[$observe]] does.
*/
observe(obs, fn, observer_callback) {
var _a;
if (!(obs instanceof Observable)) {
if (this.is_observing)
fn(obs, o_1.NoValue);
else
(this._callback_queue = (_a = this._callback_queue) !== null && _a !== void 0 ? _a : []).push(() => fn(obs, o_1.NoValue));
return null;
}
const observer = o(obs).createObserver(fn);
observer_callback === null || observer_callback === void 0 ? void 0 : observer_callback(observer);
return this.addObserver(observer);
}
/**
* Add an observer to the observers array.
*/
addObserver(observer) {
this._observers.push(observer);
if (this.is_observing)
observer.startObserving();
return observer;
}
/**
* Remove the observer from this holder and stop it from observing
*/
unobserve(observer) {
const idx = this._observers.indexOf(observer);
if (idx > -1) {
if (this.is_observing)
observer.stopObserving();