/
index.ts
5487 lines (5032 loc) · 183 KB
/
index.ts
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
// Bobril.Core
export type IBobrilChild = boolean | number | string | IBobrilNode | null | undefined;
export type IBobrilChildren = IBobrilChild | IBobrilChildArray | null | undefined;
export interface IBobrilChildArray extends Array<IBobrilChildren> { };
export type IBobrilCacheChildren = string | IBobrilCacheNode[] | undefined;
export type IBobrilShimStyleMapping = { [name: string]: null | ((style: any, value: any, oldName: string) => void) };
export interface IDisposable {
dispose(): void;
}
export type IDisposeFunction = (ctx?: any) => void;
export type IDisposableLike = IDisposable | IDisposeFunction;
export interface IBobrilRoot {
// Factory function
f: (rootData: IBobrilRoot) => IBobrilChildren;
// Root element
e: HTMLElement | undefined;
// Virtual Dom Cache - just for backwards compatibility true cache is in n
c: IBobrilCacheChildren;
// Optional Logical parent
p: IBobrilCacheNode | undefined;
// Virtual Dom Cache Node
n: IBobrilCacheNode | undefined;
}
export type ICtxClass = { new(data?: any, me?: IBobrilCacheNode): BobrilCtx<any>; };
export type IBobrilRoots = { [id: string]: IBobrilRoot };
export interface IBobrilAttributes {
id?: string;
href?: string;
value?: boolean | string | string[] | IProp<boolean | string | string[]>;
tabindex?: number;
[name: string]: any;
}
export interface IBobrilComponent {
// parent component of derived/overriding component
super?: IBobrilComponent;
// if id of old node is different from new node it is considered completely different so init will be called before render directly
// it does prevent calling render method twice on same node
id?: string;
ctxClass?: ICtxClass;
// called before new node in virtual dom should be created, me members (tag, attrs, children, ...) could be modified, ctx is initialized to { data: me.data||{}, me: me, cfg: fromParent }
init?(ctx: IBobrilCtx, me: IBobrilCacheNode): void;
// in case of update after shouldChange returns true, you can do any update/init tasks, ctx.data is updated to me.data and oldMe.component updated to me.component before calling this
// in case of init this is called after init method, oldMe is equal to undefined in that case
render?(ctx: IBobrilCtx, me: IBobrilNode, oldMe?: IBobrilCacheNode): void;
// called after all children are rendered, but before updating own attrs
// so this is useful for kind of layout in JS features
postRender?(ctx: IBobrilCtx, me: IBobrilNode, oldMe?: IBobrilCacheNode): void;
// return false when whole subtree should not be changed from last time, you can still update any me members except key, default implementation always return true
shouldChange?(ctx: IBobrilCtx, me: IBobrilNode, oldMe: IBobrilCacheNode): boolean;
// called from children to parents order for new nodes
postInitDom?(ctx: IBobrilCtx, me: IBobrilCacheNode, element: HTMLElement): void;
// called from children to parents order for updated nodes
postUpdateDom?(ctx: IBobrilCtx, me: IBobrilCacheNode, element: HTMLElement): void;
// called from children to parents order for updated nodes but in every frame even when render was not run
postUpdateDomEverytime?(ctx: IBobrilCtx, me: IBobrilCacheNode, element: HTMLElement): void;
// called just before removing node from dom
destroy?(ctx: IBobrilCtx, me: IBobrilNode, element: HTMLElement): void;
// called when bubbling event to parent so you could stop bubbling without preventing default handling
shouldStopBubble?(ctx: IBobrilCtx, name: string, param: Object): boolean;
// called when broadcast wants to dive in this node so you could silence broadcast for you and your children
shouldStopBroadcast?(ctx: IBobrilCtx, name: string, param: Object): boolean;
// called on input element after any change with new value (string|boolean)
onChange?(ctx: IBobrilCtx, value: any): void;
// called on string input element when selection or caret position changes
onSelectionChange?(ctx: IBobrilCtx, event: ISelectionChangeEvent): void;
onKeyDown?(ctx: IBobrilCtx, event: IKeyDownUpEvent): boolean;
onKeyUp?(ctx: IBobrilCtx, event: IKeyDownUpEvent): boolean;
onKeyPress?(ctx: IBobrilCtx, event: IKeyPressEvent): boolean;
// called on input element after click/tap
onClick?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onDoubleClick?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onContextMenu?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onMouseDown?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onMouseUp?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onMouseOver?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onMouseEnter?(ctx: IBobrilCtx, event: IBobrilMouseEvent): void;
onMouseLeave?(ctx: IBobrilCtx, event: IBobrilMouseEvent): void;
onMouseIn?(ctx: IBobrilCtx, event: IBobrilMouseEvent): void;
onMouseOut?(ctx: IBobrilCtx, event: IBobrilMouseEvent): void;
onMouseMove?(ctx: IBobrilCtx, event: IBobrilMouseEvent): boolean;
onMouseWheel?(ctx: IBobrilCtx, event: IBobrilMouseWheelEvent): boolean;
onPointerDown?(ctx: IBobrilCtx, event: IBobrilPointerEvent): boolean;
onPointerMove?(ctx: IBobrilCtx, event: IBobrilPointerEvent): boolean;
onPointerUp?(ctx: IBobrilCtx, event: IBobrilPointerEvent): boolean;
onPointerCancel?(ctx: IBobrilCtx, event: IBobrilPointerEvent): boolean;
// this component gained focus
onFocus?(ctx: IBobrilCtx): void;
// this component lost focus
onBlur?(ctx: IBobrilCtx): void;
// focus moved from outside of this element to some child of this element
onFocusIn?(ctx: IBobrilCtx): void;
// focus moved from inside of this element to some outside element
onFocusOut?(ctx: IBobrilCtx): void;
// if drag should start, bubbled
onDragStart?(ctx: IBobrilCtx, dndCtx: IDndStartCtx): boolean;
// broadcasted after drag started/moved/changed
onDrag?(ctx: IBobrilCtx, dndCtx: IDndCtx): boolean;
// broadcasted after drag ended even if without any action
onDragEnd?(ctx: IBobrilCtx, dndCtx: IDndCtx): boolean;
// Do you want to allow to drop here? bubbled
onDragOver?(ctx: IBobrilCtx, dndCtx: IDndOverCtx): boolean;
// User want to drop dragged object here - do it - onDragOver before had to set you target
onDrop?(ctx: IBobrilCtx, dndCtx: IDndCtx): boolean;
// this is "static" function that's why it does not have ctx - because it does not exists
canActivate?(transition: IRouteTransition): IRouteCanResult;
canDeactivate?(ctx: IBobrilCtx, transition: IRouteTransition): IRouteCanResult;
}
// new node should at least have tag or component or children member
export interface IBobrilNodeCommon {
tag?: string;
key?: string;
className?: string;
style?: any;
attrs?: IBobrilAttributes;
children?: IBobrilChildren;
ref?: [IBobrilCtx, string] | ((node: IBobrilCacheNode) => void);
// set this for children to be set to their ctx.cfg, if undefined your own ctx.cfg will be used anyway
cfg?: any;
component?: IBobrilComponent;
// Bobril does not touch this, it is completely for user passing custom data to component
// It is very similar to props in ReactJs, it must be immutable, you have access to this through ctx.data
data?: any;
}
export type IBobrilNode = IBobrilNodeCommon & object;
export interface IBobrilCacheNode {
tag: string | undefined;
key: string | undefined;
className: string | undefined;
style: any;
attrs: IBobrilAttributes | undefined;
children: IBobrilCacheChildren;
ref: [IBobrilCtx, string] | ((node: IBobrilCacheNode) => void);
cfg: any;
component: IBobrilComponent;
data: any;
element: Node | Node[] | undefined;
parent: IBobrilCacheNode | undefined;
ctx: IBobrilCtx | undefined;
}
export interface IBobrilCtx {
// properties passed from parent component, treat it as immutable
data?: any;
me: IBobrilCacheNode;
// properties passed from parent component automatically, but could be extended for children to IBobrilNode.cfg
cfg?: any;
refs?: { [name: string]: IBobrilCacheNode | null };
disposables?: IDisposableLike[];
}
export class BobrilCtx<TData> implements IBobrilCtx {
constructor(data?: TData, me?: IBobrilCacheNode) {
this.data = data!;
(this as any).me = me;
this.cfg = undefined;
this.refs = undefined;
this.disposables = undefined;
this.$bobxCtx = undefined;
}
$bobxCtx: object | undefined;
data: TData;
me: IBobrilCacheNode;
cfg?: any;
refs?: { [name: string]: IBobrilCacheNode | null };
disposables?: IDisposableLike[];
}
export interface IBobrilScroll {
node: IBobrilCacheNode;
}
export interface ISelectionChangeEvent {
startPosition: number;
// endPosition tries to be also caret position (does not work on any IE or Edge 12)
endPosition: number;
}
declare var DEBUG: boolean;
if (typeof DEBUG === "undefined") DEBUG = true;
// PureFuncs: assert, isArray, isObject, flatten
function assert(shouldBeTrue: boolean, messageIfFalse?: string) {
if (DEBUG && !shouldBeTrue)
throw Error(messageIfFalse || "assertion failed");
}
export const isArray = Array.isArray;
function createTextNode(content: string): Text {
return document.createTextNode(content);
}
function createEl(name: string): HTMLElement {
return document.createElement(name);
}
function null2undefined<T>(value: T | null | undefined): T | undefined {
return value === null ? undefined : value;
}
export function isNumber(val: any): val is number {
return typeof val == "number";
}
export function isString(val: any): val is string {
return typeof val == "string";
}
export function isFunction(val: any): val is Function {
return typeof val == "function";
}
export function isObject(val: any): val is { [name: string]: any } {
return typeof val === "object";
}
if (Object.assign == null) {
Object.assign = function assign(target: Object, ..._sources: Object[]): Object {
if (target == null) throw new TypeError('Target in assign cannot be undefined or null');
let totalArgs = arguments.length;
for (let i = 1; i < totalArgs; i++) {
let source = arguments[i];
if (source == null) continue;
let keys = Object.keys(source);
let totalKeys = keys.length;
for (let j = 0; j < totalKeys; j++) {
let key = keys[j];
(<any>target)[key] = (<any>source)[key];
}
}
return target;
}
}
export let assign = Object.assign;
export function flatten(a: any | any[]): any[] {
if (!isArray(a)) {
if (a == null || a === false || a === true)
return [];
return [a];
}
a = a.slice(0);
let aLen = a.length;
for (let i = 0; i < aLen;) {
let item = a[i];
if (isArray(item)) {
a.splice.apply(a, [i, 1].concat(item));
aLen = a.length;
continue;
}
if (item == null || item === false || item === true) {
a.splice(i, 1);
aLen--;
continue;
}
i++;
}
return a;
}
var inSvg: boolean = false;
var inNotFocusable: boolean = false;
var updateCall: Array<Function> = [];
var updateInstance: Array<IBobrilCacheNode> = [];
var setValueCallback: (el: Element, node: IBobrilCacheNode, newValue: any, oldValue: any) => void = (el: Element, _node: IBobrilCacheNode, newValue: any, oldValue: any): void => {
if (newValue !== oldValue)
(<any>el)[tValue] = newValue;
}
export function setSetValue(callback: (el: Element, node: IBobrilCacheNode, newValue: any, oldValue: any) => void): (el: Element, node: IBobrilCacheNode, newValue: any, oldValue: any) => void {
var prev = setValueCallback;
setValueCallback = callback;
return prev;
}
function newHashObj(): { [name: string]: any } {
return Object.create(null);
}
var vendors = ["Webkit", "Moz", "ms", "O"];
var testingDivStyle: any = document.createElement("div").style;
function testPropExistence(name: string) {
return isString(testingDivStyle[name]);
}
var mapping: IBobrilShimStyleMapping = newHashObj();
var isUnitlessNumber = {
boxFlex: true,
boxFlexGroup: true,
columnCount: true,
flex: true,
flexGrow: true,
flexNegative: true,
flexPositive: true,
flexShrink: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
strokeDashoffset: true,
widows: true,
zIndex: true,
zoom: true,
};
function renamer(newName: string) {
return (style: any, value: any, oldName: string) => {
style[newName] = value;
style[oldName] = undefined;
};
};
function renamerPx(newName: string) {
return (style: any, value: any, oldName: string) => {
if (isNumber(value)) {
style[newName] = value + "px";
} else {
style[newName] = value;
}
style[oldName] = undefined;
};
}
function pxAdder(style: any, value: any, name: string) {
if (isNumber(value))
style[name] = value + "px";
}
export function ieVersion() {
return (<any>document).documentMode;
}
function shimStyle(newValue: any) {
var k = Object.keys(newValue);
for (var i = 0, l = k.length; i < l; i++) {
var ki = k[i];
var mi = mapping[ki];
var vi = newValue[ki];
if (vi === undefined) continue; // don't want to map undefined
if (mi === undefined) {
if (DEBUG) {
if (ki === "float" && window.console && console.error) console.error("In style instead of 'float' you have to use 'cssFloat'");
if (/-/.test(ki) && window.console && console.warn) console.warn("Style property " + ki + " contains dash (must use JS props instead of css names)");
}
if (testPropExistence(ki)) {
mi = ((<any>isUnitlessNumber)[ki] === true) ? null : pxAdder;
} else {
var titleCaseKi = ki.replace(/^\w/, match => match.toUpperCase());
for (var j = 0; j < vendors.length; j++) {
if (testPropExistence(vendors[j] + titleCaseKi)) {
mi = (((<any>isUnitlessNumber)[ki] === true) ? renamer : renamerPx)(vendors[j] + titleCaseKi); break;
}
}
if (mi === undefined) {
mi = ((<any>isUnitlessNumber)[ki] === true) ? null : pxAdder;
if (DEBUG && window.console && console.warn
&& ["overflowScrolling"].indexOf(ki) < 0) // whitelist rare but useful
console.warn("Style property " + ki + " is not supported in this browser");
}
}
mapping[ki] = mi;
}
if (mi !== null)
mi(newValue, vi, ki);
}
}
function removeProperty(s: any, name: string) {
(<any>s)[name] = "";
}
function updateStyle(el: HTMLElement, newStyle: any, oldStyle: any) {
var s = el.style;
if (isObject(newStyle)) {
shimStyle(newStyle);
var rule: string;
if (isObject(oldStyle)) {
for (rule in oldStyle) {
if (!(rule in newStyle))
removeProperty(s, rule);
}
for (rule in newStyle) {
var v = newStyle[rule];
if (v !== undefined) {
if (oldStyle[rule] !== v) s[<any>rule] = v;
} else {
removeProperty(s, rule);
}
}
} else {
if (oldStyle)
s.cssText = "";
for (rule in newStyle) {
var v = newStyle[rule];
if (v !== undefined)
s[<any>rule] = v;
}
}
} else if (newStyle) {
s.cssText = newStyle;
} else {
if (isObject(oldStyle)) {
for (rule in oldStyle) {
removeProperty(s, rule);
}
} else if (oldStyle) {
s.cssText = "";
}
}
}
function setClassName(el: Element, className: string) {
if (inSvg)
el.setAttribute("class", className);
else
(<HTMLElement>el).className = className;
}
const focusableTag = /^input$|^select$|^textarea$|^button$/;
const tabindexStr = "tabindex";
function updateElement(n: IBobrilCacheNode, el: Element, newAttrs: IBobrilAttributes | undefined, oldAttrs: IBobrilAttributes, notFocusable: boolean): IBobrilAttributes {
var attrName: string, newAttr: any, oldAttr: any, valueOldAttr: any, valueNewAttr: any;
let wasTabindex = false;
if (newAttrs != null) for (attrName in newAttrs) {
newAttr = newAttrs[attrName];
oldAttr = oldAttrs[attrName];
if (notFocusable && attrName === tabindexStr) {
newAttr = -1;
wasTabindex = true;
} else if (attrName === tValue && !inSvg) {
if (isFunction(newAttr)) {
oldAttrs[bValue] = newAttr;
newAttr = newAttr();
}
valueOldAttr = oldAttr;
valueNewAttr = newAttr;
oldAttrs[attrName] = newAttr;
continue;
}
if (oldAttr !== newAttr) {
oldAttrs[attrName] = newAttr;
if (inSvg) {
if (attrName === "href") el.setAttributeNS("http://www.w3.org/1999/xlink", "href", newAttr);
else el.setAttribute(attrName, newAttr);
} else if (attrName in el && !(attrName === "list" || attrName === "form")) {
(<any>el)[attrName] = newAttr;
} else el.setAttribute(attrName, newAttr);
}
}
if (notFocusable && !wasTabindex && n.tag && focusableTag.test(n.tag)) {
el.setAttribute(tabindexStr, "-1");
oldAttrs[tabindexStr] = -1;
}
if (newAttrs == null) {
for (attrName in oldAttrs) {
if (oldAttrs[attrName] !== undefined) {
if (notFocusable && attrName === tabindexStr) continue;
if (attrName === bValue) continue;
oldAttrs[attrName] = undefined;
el.removeAttribute(attrName);
}
}
} else {
for (attrName in oldAttrs) {
if (oldAttrs[attrName] !== undefined && !(attrName in newAttrs)) {
if (notFocusable && attrName === tabindexStr) continue;
if (attrName === bValue) continue;
oldAttrs[attrName] = undefined;
el.removeAttribute(attrName);
}
}
}
if (valueNewAttr !== undefined) {
setValueCallback(el, n, valueNewAttr, valueOldAttr);
}
return oldAttrs;
}
function pushInitCallback(c: IBobrilCacheNode) {
var cc = c.component;
if (cc) {
let fn = cc.postInitDom;
if (fn) {
updateCall.push(fn);
updateInstance.push(c);
}
}
}
function pushUpdateCallback(c: IBobrilCacheNode) {
var cc = c.component;
if (cc) {
let fn = cc.postUpdateDom;
if (fn) {
updateCall.push(fn);
updateInstance.push(c);
}
fn = cc.postUpdateDomEverytime;
if (fn) {
updateCall.push(fn);
updateInstance.push(c);
}
}
}
function pushUpdateEverytimeCallback(c: IBobrilCacheNode) {
var cc = c.component;
if (cc) {
let fn = cc.postUpdateDomEverytime;
if (fn) {
updateCall.push(fn);
updateInstance.push(c);
}
}
}
function findCfg(parent: IBobrilCacheNode | undefined): any {
var cfg: any;
while (parent) {
cfg = parent.cfg;
if (cfg !== undefined) break;
if (parent.ctx) {
cfg = parent.ctx.cfg;
break;
}
parent = parent.parent;
}
return cfg;
}
function setRef(ref: [IBobrilCtx, string] | ((node: IBobrilCacheNode | null) => void), value: IBobrilCacheNode | null) {
if (ref == null) return;
if (isFunction(ref)) {
(<(node: IBobrilCacheNode | null) => void>ref)(value);
return;
}
var ctx = (<[IBobrilCtx, string]>ref)[0];
var refs = ctx.refs;
if (refs == null) {
refs = newHashObj();
ctx.refs = refs;
}
refs[(<[IBobrilCtx, string]>ref)[1]] = value;
}
let focusRootStack: IBobrilCacheNode[] = [];
let focusRootTop: IBobrilCacheNode | null = null;
export function registerFocusRoot(ctx: IBobrilCtx) {
focusRootStack.push(ctx.me);
addDisposable(ctx, unregisterFocusRoot);
ignoreShouldChange();
}
export function unregisterFocusRoot(ctx: IBobrilCtx) {
let idx = focusRootStack.indexOf(ctx.me);
if (idx !== -1) {
focusRootStack.splice(idx, 1);
ignoreShouldChange();
}
}
let currentCtx: IBobrilCtx | undefined;
export function getCurrentCtx() {
return currentCtx;
}
export function setCurrentCtx(ctx: IBobrilCtx | undefined) {
currentCtx = ctx;
}
export function createNode(n: IBobrilNode, parentNode: IBobrilCacheNode | undefined, createInto: Element, createBefore: Node | null): IBobrilCacheNode {
var c = <IBobrilCacheNode>{ // This makes CacheNode just one object class = fast
tag: n.tag,
key: n.key,
ref: n.ref,
className: n.className,
style: n.style,
attrs: n.attrs,
children: n.children,
component: n.component,
data: n.data,
cfg: n.cfg,
parent: parentNode,
element: undefined,
ctx: undefined
};
var backupInSvg = inSvg;
var backupInNotFocusable = inNotFocusable;
var component = c.component;
var el: Node | undefined;
setRef(c.ref, c);
if (component) {
var ctx: IBobrilCtx;
if (component.ctxClass) {
ctx = new component.ctxClass(c.data || {}, c);
if (ctx.data === undefined) ctx.data = c.data || {};
if (ctx.me === undefined) ctx.me = c;
} else {
ctx = { data: c.data || {}, me: c, cfg: undefined };
}
ctx.cfg = findCfg(parentNode);
c.ctx = ctx;
currentCtx = ctx;
if (component.init) {
component.init(ctx, c);
}
if (beforeRenderCallback !== emptyBeforeRenderCallback)
beforeRenderCallback(n, RenderPhase.Create);
if (component.render) {
component.render(ctx, c);
}
currentCtx = undefined;
}
var tag = c.tag;
if (tag === "-") { // Skip update
c.tag = undefined;
c.children = undefined;
return c;
}
var children = c.children;
var inSvgForeignObject = false;
if (isNumber(children)) {
children = "" + children;
c.children = children;
}
if (tag === undefined) {
if (isString(children)) {
el = createTextNode(<string>children);
c.element = el;
createInto.insertBefore(el, createBefore);
} else {
createChildren(c, createInto, createBefore);
}
if (component) {
if (component.postRender) {
component.postRender(c.ctx!, c);
}
pushInitCallback(c);
}
return c;
}
if (tag === "/") {
var htmlText = <string>children;
if (htmlText === "") {
// nothing needs to be created
} else if (createBefore == null) {
var before = createInto.lastChild;
(<HTMLElement>createInto).insertAdjacentHTML("beforeend", htmlText);
c.element = <Node[]>[];
if (before) {
before = before.nextSibling;
} else {
before = createInto.firstChild;
}
while (before) {
(<Node[]>c.element).push(before);
before = before.nextSibling;
}
} else {
el = createBefore;
var elPrev = createBefore.previousSibling;
var removeEl = false;
var parent = createInto;
if (!(<HTMLElement>el).insertAdjacentHTML) {
el = parent.insertBefore(createEl("i"), el);
removeEl = true;
}
(<HTMLElement>el).insertAdjacentHTML("beforebegin", htmlText);
if (elPrev) {
elPrev = elPrev.nextSibling;
}
else {
elPrev = parent.firstChild;
}
var newElements: Array<Node> = [];
while (elPrev !== el) {
newElements.push(elPrev!);
elPrev = elPrev!.nextSibling;
}
c.element = newElements;
if (removeEl) {
parent.removeChild(el);
}
}
if (component) {
if (component.postRender) {
component.postRender(c.ctx!, c);
}
pushInitCallback(c);
}
return c;
}
if (inSvg || tag === "svg") {
el = document.createElementNS("http://www.w3.org/2000/svg", tag);
inSvgForeignObject = tag === "foreignObject";
inSvg = !inSvgForeignObject;
} else {
el = createEl(tag);
}
createInto.insertBefore(el, createBefore);
c.element = el;
createChildren(c, <Element>el, null);
if (component) {
if (component.postRender) {
component.postRender(c.ctx!, c);
}
}
if (inNotFocusable && focusRootTop === c)
inNotFocusable = false;
if (inSvgForeignObject) inSvg = true;
if (c.attrs || inNotFocusable) c.attrs = updateElement(c, <HTMLElement>el, c.attrs, {}, inNotFocusable);
if (c.style) updateStyle(<HTMLElement>el, c.style, undefined);
var className = c.className;
if (className) setClassName(<HTMLElement>el, className);
inSvg = backupInSvg;
inNotFocusable = backupInNotFocusable;
pushInitCallback(c);
return c;
}
function normalizeNode(n: any): IBobrilNode | undefined {
if (n === false || n === true || n === null) return undefined;
if (isString(n)) {
return { children: n };
}
if (isNumber(n)) {
return { children: "" + n };
}
return <IBobrilNode | undefined>n;
}
function createChildren(c: IBobrilCacheNode, createInto: Element, createBefore: Node | null): void {
var ch = c.children;
if (!ch)
return;
if (!isArray(ch)) {
if (isString(ch)) {
createInto.textContent = ch;
return;
}
ch = <any>[ch];
}
ch = (<any[]>ch).slice(0);
var i = 0, l = (<any[]>ch).length;
while (i < l) {
var item = (<any[]>ch)[i];
if (isArray(item)) {
(<IBobrilCacheNode[]>ch).splice.apply(ch, (<any>[i, 1]).concat(item));
l = (<IBobrilCacheNode[]>ch).length;
continue;
}
item = normalizeNode(item);
if (item == null) {
(<any[]>ch).splice(i, 1);
l--;
continue;
}
(<IBobrilCacheNode[]>ch)[i] = createNode(item, c, createInto, createBefore);
i++;
}
c.children = ch;
}
function destroyNode(c: IBobrilCacheNode) {
setRef(c.ref, null);
let ch = c.children;
if (isArray(ch)) {
for (let i = 0, l = ch.length; i < l; i++) {
destroyNode(ch[i]);
}
}
let component = c.component;
if (component) {
let ctx = c.ctx!;
currentCtx = ctx;
if (beforeRenderCallback !== emptyBeforeRenderCallback)
beforeRenderCallback(c, RenderPhase.Destroy);
if (component.destroy)
component.destroy(ctx, c, <HTMLElement>c.element);
let disposables = ctx.disposables;
if (isArray(disposables)) {
for (let i = disposables.length; i-- > 0;) {
let d = disposables[i];
if (isFunction(d)) d(ctx); else d.dispose();
}
}
}
}
export function addDisposable(ctx: IBobrilCtx, disposable: IDisposableLike) {
let disposables = ctx.disposables;
if (disposables == null) {
disposables = [];
ctx.disposables = disposables;
}
disposables.push(disposable);
}
function removeNodeRecursive(c: IBobrilCacheNode) {
var el = c.element;
if (isArray(el)) {
var pa = (<Node[]>el)[0].parentNode;
if (pa) {
for (let i = 0; i < (<Node[]>el).length; i++) {
pa.removeChild((<Node[]>el)[i]);
}
}
} else if (el != null) {
let p = (<Node>el).parentNode;
if (p) p.removeChild(<Node>el);
} else {
var ch = c.children;
if (isArray(ch)) {
for (var i = 0, l = (<IBobrilCacheNode[]>ch).length; i < l; i++) {
removeNodeRecursive((<IBobrilCacheNode[]>ch)[i]);
}
}
}
}
function removeNode(c: IBobrilCacheNode) {
destroyNode(c);
removeNodeRecursive(c);
}
var roots: IBobrilRoots = newHashObj();
function nodeContainsNode(c: IBobrilCacheNode, n: Node, resIndex: number, res: (IBobrilCacheNode | null)[]): IBobrilCacheNode[] | null | undefined {
var el = c.element;
var ch = c.children;
if (isArray(el)) {
for (var ii = 0; ii < (<Node[]>el).length; ii++) {
if ((<Node[]>el)[ii] === n) {
res.push(c);
if (isArray(ch)) {
return <IBobrilCacheNode[]>ch;
}
return null;
}
}
} else if (el == null) {
if (isArray(ch)) {
for (var i = 0; i < (<IBobrilCacheNode[]>ch).length; i++) {
var result = nodeContainsNode((<IBobrilCacheNode[]>ch)[i], n, resIndex, res);
if (result !== undefined) {
res.splice(resIndex, 0, c);
return result;
}
}
}
} else if (el === n) {
res.push(c);
if (isArray(ch)) {
return <IBobrilCacheNode[]>ch;
}
return null;
}
return undefined;
}
export function vdomPath(n: Node | null | undefined): (IBobrilCacheNode | null)[] {
var res: (IBobrilCacheNode | null)[] = [];
if (n == null) return res;
var rootIds = Object.keys(roots);
var rootElements = rootIds.map((i) => roots[i].e || document.body);
var nodeStack: Node[] = [];
rootFound: while (n) {
for (var j = 0; j < rootElements.length; j++) {
if (n === rootElements[j]) break rootFound;
}
nodeStack.push(n);
n = n.parentNode;
}
if (!n || nodeStack.length === 0) return res;
var currentCacheArray: IBobrilChildren | null = null;
var currentNode = nodeStack.pop()!;
for (j = 0; j < rootElements.length; j++) {
if (n === rootElements[j]) {
var rn = roots[rootIds[j]].n;
if (rn === undefined) continue;
var findResult = nodeContainsNode(rn, currentNode, res.length, res);
if (findResult !== undefined) {
currentCacheArray = findResult;
break;
}
}
}
subtreeSearch: while (nodeStack.length) {
currentNode = nodeStack.pop()!;
if (currentCacheArray && (<any>currentCacheArray).length) for (var i = 0, l = (<any>currentCacheArray).length; i < l; i++) {
var bn = (<IBobrilCacheNode[]>currentCacheArray)[i];
var findResult = nodeContainsNode(bn, currentNode, res.length, res);
if (findResult !== undefined) {
currentCacheArray = findResult;
continue subtreeSearch;
}
}
res.push(null);
break;
}
return res;
}
// PureFuncs: deref, getDomNode
export function deref(n: Node): IBobrilCacheNode | undefined {
var p = vdomPath(n);
var currentNode: IBobrilCacheNode | null | undefined = null;
while (currentNode === null) {
currentNode = p.pop();
}
return currentNode;
}
function finishUpdateNode(n: IBobrilNode, c: IBobrilCacheNode, component: IBobrilComponent | null | undefined) {
if (component) {
if (component.postRender) {
currentCtx = c.ctx!;
component.postRender(currentCtx, n, c);
currentCtx = undefined;
}
}
c.data = n.data;
pushUpdateCallback(c);
}
function finishUpdateNodeWithoutChange(c: IBobrilCacheNode, createInto: Element, createBefore: Node | null) {
currentCtx = undefined;
if (isArray(c.children)) {
const backupInSvg = inSvg;
const backupInNotFocusable = inNotFocusable;
if (c.tag === "svg") {
inSvg = true;
} else if (inSvg && c.tag === "foreignObject") inSvg = false;
if (inNotFocusable && focusRootTop === c)
inNotFocusable = false;
selectedUpdate(<IBobrilCacheNode[]>c.children, <Element>c.element || createInto, c.element != null ? null : createBefore);
inSvg = backupInSvg;
inNotFocusable = backupInNotFocusable;
}
pushUpdateEverytimeCallback(c);
}
export function updateNode(n: IBobrilNode, c: IBobrilCacheNode, createInto: Element, createBefore: Node | null, deepness: number, inSelectedUpdate?: boolean): IBobrilCacheNode {
var component = n.component;
var bigChange = false;
var ctx = c.ctx;
if (component && ctx != null) {
let locallyInvalidated = false;
if ((<any>ctx)[ctxInvalidated] === frameCounter) {
deepness = Math.max(deepness, (<any>ctx)[ctxDeepness]);
locallyInvalidated = true;
}
if (component.id !== c.component.id) {
bigChange = true;
} else {
currentCtx = ctx;
if (c.parent != undefined)
ctx.cfg = findCfg(c.parent);
if (component.shouldChange)
if (!component.shouldChange(ctx, n, c) && !ignoringShouldChange && !locallyInvalidated) {
finishUpdateNodeWithoutChange(c, createInto, createBefore);
return c;
}
(<any>ctx).data = n.data || {};
c.component = component;
if (beforeRenderCallback !== emptyBeforeRenderCallback)
beforeRenderCallback(n, inSelectedUpdate ? RenderPhase.LocalUpdate : RenderPhase.Update);
if (component.render) {
n = assign({}, n); // need to clone me because it should not be modified for next updates
component.render(ctx, n, c);
}
c.cfg = n.cfg;
currentCtx = undefined;
}