-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.ts
1391 lines (1195 loc) · 37.3 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
const sbPrefix = Symbol('@sb/prefix');
type Complex = object | Function;
type Prefixed<T extends any> = T extends Complex ? T & Meta : never;
type Meta = { [sbPrefix]: string };
type Watcher = (newValue: unknown) => unknown;
type DirectiveParams = {
el: Element; // The element to which the directive has been applied.
value: unknown; // The updated value.
key: string; // Period '.' delimited key that points to the value in the global data object.
isDelete: boolean; // Whether the value was deleted `delete data.prop`.
parent: Prefixed<object>; // The parent object to which the value belongs (the proxied object, unless isDelete).
prop: string; // Property of the parent which points to the value, `parent[prop] ≈ value`
param: string | undefined; // If directive is a parametric directive, `param` is passed
};
type Directive = (params: DirectiveParams) => void;
type BasicAttrs = 'mark' | 'if' | 'ifnot';
type ComputedList = {
key: string;
computed: Prefixed<Function>;
parent: Prefixed<object>;
prop: string;
}[];
type SyncConfig = {
directive: string;
el: Element;
skipConditionals?: boolean | undefined;
skipMark?: boolean | undefined;
};
const DONT_CALL = Symbol('@sb/dontcall');
let globalData: null | Prefixed<{}> = null;
let globalPrefix = 'sb-';
const globalWatchers = new Map<string, Watcher[]>();
const globalDirectives = new Map<
string,
{ cb: Directive; isParametric?: boolean }
>([
[
'mark',
{
cb: ({ el, value, isDelete }) => {
if (isDelete) {
return remove(el);
}
if (!(el instanceof HTMLElement)) {
return;
}
if (typeof value === 'object' && value !== null) {
value = JSON.stringify(value);
}
const stringValue = typeof value === 'string' ? value : String(value);
el.innerText = stringValue;
},
},
],
['if', { cb: ({ el, value, key }) => ifOrIfNot(el, value, key, 'if') }],
['ifnot', { cb: ({ el, value, key }) => ifOrIfNot(el, value, key, 'ifnot') }],
]);
/**
* Object used to maintain computed values
* - `isEvaluating`: set to true when evaluating a computed function
* - `set`: used to keep track of dependencies when evaluating a computed function
* - `map`: keeps track of dependencies keyed by dependents
*/
const globalDeps = {
isEvaluating: false,
set: new Set<string>(),
map: new Map<string, ComputedList>(),
};
const attr = (k: BasicAttrs) => globalPrefix + k;
function reactive<T>(
obj: T,
prefix: string,
parent?: Prefixed<object>,
prop?: string
): T | Prefixed<T> {
if (obj === null) {
return obj;
}
const isObject = typeof obj === 'object';
const isFunction = typeof obj === 'function';
if (isFunction && parent) {
obj = (obj as Function).bind(parent);
}
if (isObject || isFunction) {
Object.defineProperty(obj, sbPrefix, {
value: prefix,
enumerable: false,
writable: true,
});
}
if (isFunction && prop && parent) {
setDependents(obj as Prefixed<Function>, prefix, parent, prop);
return obj;
}
if (!isObject) {
return obj;
}
type K = keyof T;
const proxied = new Proxy(obj as object, ReactivityHandler) as Prefixed<T>;
for (const prop of Object.keys(obj as object)) {
const newprefix = getKey(prop, prefix);
const value = obj[prop as K];
obj[prop as K] = reactive(value, newprefix, proxied, prop);
}
return proxied;
}
class ReactivityHandler implements ProxyHandler<Prefixed<object>> {
static get(
target: Prefixed<object>,
prop: string | symbol,
receiver: Prefixed<object>
): unknown {
if (
globalDeps.isEvaluating &&
typeof prop === 'string' &&
Object.getOwnPropertyDescriptor(target, prop)?.enumerable
) {
globalDeps.set.add(getKey(prop, target[sbPrefix]));
}
const value = Reflect.get(target, prop, receiver);
if (typeof value === 'function' && value[sbPrefix]) {
const computed = value();
if (computed instanceof Promise) {
return computed.then((v) => proxyComputed(v));
}
return proxyComputed(computed);
}
return value;
}
static set(
target: Prefixed<object>,
prop: string | symbol,
value: unknown,
receiver: Prefixed<object>
): boolean {
if (typeof prop === 'symbol') {
return Reflect.set(target, prop, value, receiver);
}
const key = getKey(prop, target[sbPrefix]);
const reactiveValue = reactive(value, key, receiver, prop);
const success = Reflect.set(target, prop, reactiveValue, receiver);
this.update(reactiveValue, key, false, receiver, prop);
this.updateComputed(key);
return success;
}
static deleteProperty(
target: Prefixed<object>,
prop: string | symbol
): boolean {
if (typeof prop === 'symbol') {
return Reflect.deleteProperty(target, prop);
}
const key = getKey(prop, target[sbPrefix]);
const success = Reflect.deleteProperty(target, prop);
this.update(undefined, key, true, target, prop);
globalDeps.map.delete(key);
for (const k of globalDeps.map.keys()) {
const filtered =
globalDeps.map.get(k)?.filter((d) => d.key !== key) ?? [];
globalDeps.map.set(k, filtered);
}
return success;
}
static defineProperty(
target: Prefixed<object>,
prop: string | symbol,
descriptor: PropertyDescriptor
): boolean {
if (
prop === sbPrefix &&
sbPrefix in target &&
/\.\d+$/.test(descriptor.value)
) {
return Reflect.set(target, prop, descriptor.value);
}
return Reflect.defineProperty(target, prop, descriptor);
}
/**
* Called when a computed value's dependent is changed.
*
* @param key period '.' separated key to the computed value's dep, used to track the computed value
*/
static updateComputed(key: string) {
const dependentNames = [...globalDeps.map.keys()]
.filter(
(k) => k === key || k.startsWith(key + '.') || key.startsWith(k + '.')
)
.flatMap((k) => globalDeps.map.get(k) ?? []);
const executed = new Set<Function>();
for (const dep of dependentNames) {
if (executed.has(dep.computed)) {
continue;
}
this.update(dep.computed, dep.key, false, dep.parent, dep.prop);
executed.add(dep.computed);
}
}
/**
* `update` calls the watchers and directive functions with the value so that changes
* to the object can be propagated
*
* @param value new value that is set, if deleted then `undefined`
* @param key period '.' joined key that points to the value in the global reactive object
* @param isDelete whether the value is being deleted (only if being called from deleteProperty)
* @param parent object to which `value` belongs (actual object, not the proxy)
* @param prop property of the parent which points to the value, `parent[prop] ≈ value`
* @param syncConfig object used to sync a single node on insertion from if | ifnot
*/
static update(
value: unknown,
key: string,
isDelete: boolean,
parent: Prefixed<object>,
prop: string,
syncConfig?: SyncConfig
) {
if (typeof value === 'function' && !value.hasOwnProperty(DONT_CALL)) {
value = runComputed(value, key, parent, prop);
}
if (value instanceof Promise) {
(value as Promise<unknown>).then((v: unknown) =>
this.update(v, key, false, parent, prop, syncConfig)
);
return;
}
if (!syncConfig) {
this.callWatchers(value, key);
}
this.callDirectives(
value,
key,
isDelete,
parent,
prop,
undefined,
undefined,
syncConfig
);
}
static callWatchers(value: unknown, key: string) {
for (const k of globalWatchers.keys()) {
if (key === k) {
globalWatchers.get(k)?.forEach((cb) => cb(value));
} else if (key.startsWith(k + '.') && globalData !== null) {
const { value } = getValue(k);
globalWatchers.get(k)?.forEach((cb) => cb(value));
}
}
}
static callDirectives(
value: unknown,
key: string,
isDelete: boolean,
parent: Prefixed<object>,
prop: string,
searchRoot?: Element | Document,
skipUpdateArrayElements?: boolean,
syncConfig?: SyncConfig
): void {
const isParentArray = Array.isArray(parent);
if (
isParentArray &&
/^\d+$/.test(prop) &&
!skipUpdateArrayElements &&
syncConfig?.skipMark !== true
) {
updateArrayItemElement(key, prop, value, parent);
} else if (isParentArray && prop === 'length') {
sortArrayItemElements(parent);
}
const isRDO = isPrefixedObject(value);
if (isRDO && Array.isArray(value) && syncConfig?.skipMark !== true) {
const placeholderKey = `${key}.#`;
const rootQuery = `[${attr('mark')}="${placeholderKey}"]`;
const elsArray: Element[][] = [];
/**
* if skipMark is not true and el is present
* the node being synced has not yet been inserted
* into the DOM, i.e. isConnected=false hence
* query selector must run on the parent.
*/
let target: Document | Element = document;
if (syncConfig?.el.parentElement) {
target = syncConfig.el.parentElement;
}
for (const plc of target.querySelectorAll(rootQuery)) {
const els = initializeArrayElements(plc, placeholderKey, value);
elsArray.push(els);
}
/**
* Set values to the newly initialized elements
*/
for (const els of elsArray) {
for (const i in value) {
this.callDirectives(
value[i],
getKey(i, key),
isDelete,
value,
i,
els[i],
true
);
}
}
} else if (isRDO) {
for (const k in value) {
this.callDirectives(
value[k as unknown as keyof typeof value],
getKey(k, key),
isDelete,
value,
k,
searchRoot
);
}
}
if (isRDO) {
return;
}
if (syncConfig) {
const { el, directive: attrSuffix } = syncConfig;
const { cb, isParametric } = globalDirectives.get(attrSuffix) ?? {};
const param = getParam(el, globalPrefix + attrSuffix, !!isParametric);
cb?.({ el: el, value, key, isDelete, parent, prop, param });
return;
}
searchRoot ??= document;
for (const [attrSuffix, directive] of globalDirectives.entries()) {
const { cb, isParametric } = directive;
const attrName = globalPrefix + attrSuffix;
let query: string;
if (isParametric) {
query = `[${attrName}^='${key}:']`;
} else {
query = `[${attrName}='${key}']`;
}
searchRoot.querySelectorAll(query).forEach((el) => {
const param = getParam(el, attrName, !!isParametric);
cb({ el, value, key, isDelete, parent, prop, param });
});
if (
searchRoot instanceof Element &&
searchRoot.getAttribute(attrName) === key
) {
const param = getParam(searchRoot, attrName, !!isParametric);
cb({ el: searchRoot, value, key, isDelete, parent, prop, param });
}
}
}
}
function ifOrIfNot(
el: Element,
value: unknown,
key: string,
type: 'if' | 'ifnot'
) {
const isShow = type === 'if' ? !!value : !value;
const isTemplate = el instanceof HTMLTemplateElement;
if (isShow && isTemplate) {
const child = el.content.firstElementChild;
if (!child) {
return;
}
child.setAttribute(attr(type), key);
syncNode(child, true);
el.replaceWith(child);
}
if (!isShow && !isTemplate) {
const temp = document.createElement('template');
temp.content.appendChild(el.cloneNode(true));
temp.setAttribute(attr(type), key);
const mark = el.getAttribute(attr('mark'));
if (mark) {
temp.setAttribute(attr('mark'), mark);
}
el.replaceWith(temp);
}
}
/**
* Called from conditionals when it evaluates to true and an elemen
* is inserted into the DOM. Function calls `update` with `syncConfig`
* to trigger only the directives found on the node being synced.
* @param el Element to be synced
* @param isSyncRoot Whether `el` is the root node from where the sync begins
*/
function syncNode(el: Element, isSyncRoot: boolean) {
for (const ch of el.children) {
syncNode(ch, false);
}
syncDirectives(el, isSyncRoot);
}
function syncClone(clone: Element) {
for (const ch of clone.children) {
syncClone(ch);
}
syncDirectives(clone, false, true);
}
function syncDirectives(
el: Element,
skipConditionals?: boolean,
skipMark?: boolean
) {
for (const [name, { isParametric }] of globalDirectives.entries()) {
if (
(skipMark && name === 'mark') ||
(skipConditionals && (name === 'if' || name === 'ifnot'))
) {
continue;
}
let key = el.getAttribute(globalPrefix + name);
if (isParametric) {
key = key?.split(':')[0] ?? null;
}
if (key?.endsWith('.#')) {
key = key.slice(0, -2);
}
if (key === null) {
continue;
}
const { value, parent, prop } = getValue(key);
if (!parent) {
continue;
}
ReactivityHandler.update(value, key, false, parent, prop, {
directive: name,
el,
skipConditionals,
skipMark,
});
}
}
/**
* Stores the list of dependencies the computed value is dependent on.
*
* @param value function for the computed value
* @param key period '.' joined key that points to the value in the global reactive object
* @param parent object to which `value` belongs (not the proxy of the object). undefined if dependency
* @param prop property of the parent which points to the value, parent[prop] ≈ value. undefined if dependency
*/
function setDependents(
value: Prefixed<Function>,
key: string,
parent: Prefixed<object>,
prop: string
) {
/**
* Capture dependencies in `globalDeps.set`. The set is updated
* in the `get` trap of the proxy.
*/
globalDeps.isEvaluating = true;
globalDeps.set.clear();
value();
globalDeps.isEvaluating = false;
const dependent = {
key,
computed: value,
parent,
prop,
};
for (const dep of globalDeps.set) {
const computedList = globalDeps.map.get(dep) ?? [];
computedList.push(dependent);
if (!globalDeps.map.has(dep)) {
globalDeps.map.set(dep, computedList);
}
}
}
/**
* @param key prefixed key (eg: "list.3")
* @param idx index of the newly pushed element (eg: "3")
* @param item array[idx] to prevent repeat get
* @param array array into which the value is pushed
*/
function updateArrayItemElement(
key: string,
idx: string,
item: unknown,
array: Prefixed<unknown[]>
) {
/**
* Called only when an array element is updated,
* i.e. prop is a digit, such as when push, splice, etc are called.
*
* When an item is pushed to an Array, the DOM element that maps to that
* item does not exist.
*
* This function inserts the child element before the template.
*/
const arrayItems = document.querySelectorAll(`[${attr('mark')}="${key}"]`);
if (arrayItems.length && !isPrefixedObject(item)) {
/**
* For primitive items just updating the innerText
* suffices, no need to replace the element.
*/
return;
}
const prefix = array[sbPrefix];
const placeholderKey = key.replace(/\d+$/, '#');
let itemReplaced: boolean = false;
/**
* Loop runs if the array item already exists, so if a value is
* "pushed" into an array, this won't update the element array
* because the array item doesn't already exist.
*/
for (const item of arrayItems) {
let placeholder = item.nextElementSibling;
while (placeholder) {
if (placeholder.getAttribute(attr('mark')) === placeholderKey) {
break;
}
placeholder = placeholder.nextElementSibling;
}
let clone: Node | null | undefined;
if (placeholder instanceof HTMLTemplateElement) {
clone = placeholder.content.firstElementChild?.cloneNode(true);
} else if (placeholder?.getAttribute(attr('mark')) === placeholderKey) {
/**
* possible no-op: unconcealed placeholder should not exist
* if the array had elements when the outer function was called
*/
clone = placeholder?.cloneNode(true);
} else {
continue;
}
if (!(clone instanceof Element)) {
continue;
}
initializeClone(idx, prefix, placeholderKey, clone);
item.replaceWith(clone);
syncClone(clone);
itemReplaced ||= true;
}
if (itemReplaced) {
return;
}
const templates = document.querySelectorAll(
`[${attr('mark')}="${placeholderKey}"]`
);
for (const template of templates) {
if (!(template instanceof HTMLTemplateElement)) {
continue;
}
const clone = template.content.firstElementChild?.cloneNode(true);
if (!(clone instanceof Element)) {
continue;
}
initializeClone(idx, prefix, placeholderKey, clone);
template.before(clone);
syncClone(clone);
}
}
function sortArrayItemElements(array: Prefixed<unknown[]>): void {
/**
* Called only when length prop of an array is set.
*
* Length is the last property to be set after an array shape
* has been altered by using methods such as push, splice, etc.
*
* This sorts the DOM nodes to match the data array since updates
* (get, set sequence) don't always happen in the right order such as
* when using splice. So sorting must take place after the update.
*/
const templateKey = getKey('#', array[sbPrefix]);
const templates = document.querySelectorAll(
`[${attr('mark')}="${templateKey}"]`
);
for (const template of templates) {
const items: Element[] = [];
/**
* populate the items array with item elements
* items array is populated in the reverse order
*/
let prev = template.previousElementSibling;
let isSorted = true;
let lastIdx: number = -1;
while (prev) {
const curr = prev;
prev = curr.previousElementSibling;
const key = curr?.getAttribute(attr('mark'));
if (!key) {
continue;
}
if (key === templateKey) {
break;
}
if (key.replace(/\d+$/, '#') === templateKey) {
items.push(curr);
if (!isSorted) {
continue;
}
const idx = Number(key.slice(key.lastIndexOf('.') + 1) ?? -1);
if (lastIdx !== -1 && lastIdx !== idx + 1) {
isSorted = false;
}
lastIdx = idx;
}
}
if (isSorted) {
return;
}
/**
* reverse the unsorted array to get it in the same order
* as the DOM, and create a sortedArray.
*/
const sortedItems = [...items].sort((a, b) => {
const am = a.getAttribute(attr('mark'));
const bm = b.getAttribute(attr('mark'));
if (!am || !bm) {
return 0;
}
const ams = am.split('.');
const bms = bm.split('.');
const amIdx = +(ams[ams.length - 1] ?? 0);
const bmIdx = +(bms[bms.length - 1] ?? 0);
return amIdx - bmIdx;
});
/**
* Replace the unsorted items by the sorted items.
*/
sortedItems.forEach((item) => template.before(item));
}
}
function initializeArrayElements(
plc: Element,
placeholderKey: string,
array: unknown[]
): Element[] {
/**
* 1. Delete Previous Array Elements
*
* When a new list is set previous list item elements should be
* deleted. Empty list deletes all items, but keeps the placeholder.
*
* When a array is updated a child element is prepended before the
* placeholder element.
*/
let prev = plc.previousElementSibling;
while (prev) {
const curr = prev;
prev = curr.previousElementSibling;
const key = curr?.getAttribute(attr('mark'));
if (!key) {
continue;
}
if (key !== placeholderKey && key.replace(/\d+$/, '#') === placeholderKey) {
curr?.remove();
} else {
break;
}
}
/**
* 2. Get Placeholder and Template from `plc`
*
* `plc` can be either a concealed element,
* i.e. the `template`:
* ```html
* <template sb-mark="list.#">
* <!-- ONLY one child -->
* <li></li>
* </template>
* ```
* Or a rendered element, i.e. the `placeholder`:
* ```html
* <li sb-mark="list.#">zero</li>
* ```
*
* `template` is maintained at the end of a list
* of elements and contains the `placeholder`.
*
* `placeholder` is cloned to create list elements.
*/
let template: HTMLTemplateElement;
let placeholder: Element | null;
if (plc instanceof HTMLTemplateElement) {
template = plc;
placeholder = plc.content.firstElementChild;
placeholder?.setAttribute(attr('mark'), placeholderKey);
} else {
placeholder = plc;
template = document.createElement('template');
template.content.appendChild(plc.cloneNode(true));
template.setAttribute(attr('mark'), placeholderKey);
plc.replaceWith(template);
}
if (placeholder === null) {
console.warn(`empty template found for ${placeholderKey}`);
return [];
}
/**
* For each array item, insert a child element before the
* template
*/
const prefix = placeholderKey.slice(0, -2); // remove '.#' loop indicator
const arrayElements: Element[] = [];
for (const idx in array) {
if (Number.isNaN(+idx)) {
continue;
}
const clone = placeholder.cloneNode(true);
if (!(clone instanceof Element)) {
continue;
}
initializeClone(idx, prefix, placeholderKey, clone);
template.before(clone);
syncClone(clone);
arrayElements.push(clone);
}
return arrayElements;
}
/**
* @param idx index of `item` in `array` eg: "0"
* @param prefix item element key prefix i.e. placholder key without ".#"
* @param placeholderKey key set on the placeholder element eg: "list.#"
* @param clone clone of the placeholder item
*/
function initializeClone(
idx: string,
prefix: string,
placeholderKey: string,
clone: Element
): void {
const key = getKey(idx, prefix);
/**
* Change directive keys from placeholder keys
* eg `"users.#.name"` to actual keys eg `"users.0.name"`
*/
for (const attrSuffix of globalDirectives.keys()) {
const attrName = globalPrefix + attrSuffix;
/**
* Change clone's directive keys
*/
setKey(clone, attrName, key, placeholderKey);
/**
* Change clone's children's directive keys
*/
clone.querySelectorAll(`[${attrName}]`).forEach((ch) => {
setKey(ch, attrName, key, placeholderKey);
});
}
}
function setKey(
el: Element,
attrName: string,
key: string,
placeholderKey: string
) {
const pkey = el.getAttribute(attrName);
if (pkey?.startsWith(placeholderKey)) {
const newPkey = key + pkey.slice(placeholderKey.length);
el.setAttribute(attrName, newPkey);
}
}
function remove(el: Element) {
const parent = el.parentElement;
if (!(el instanceof HTMLElement) || !parent) {
return el.remove();
}
if (el.getAttribute(attr('mark')) === parent.getAttribute(attr('mark'))) {
return parent.remove();
}
el.remove();
}
function isPrefixedObject(value: unknown): value is Prefixed<object> {
if (typeof value !== 'object' || value === null) {
return false;
}
return sbPrefix in value;
}
function getKey(prop: string, prefix: string) {
return prefix === '' ? prop : prefix + '.' + prop;
}
function getParam(el: Element, attrName: string, isParametric: boolean) {
let value;
if (!isParametric || !(value = el.getAttribute(attrName))) {
return undefined;
}
return value.slice(value.indexOf(':') + 1);
}
/**
* Function gets a value from the `globalData` object when passed a '.' separated
* key. Also returns the `parent` object containing the `value` and the `prop` of
* the value in the parent object.
*
* @param key period '.' separated key to a value in the reactive `globalData`
*/
function getValue(key: string) {
let parent = globalData;
let value: unknown = undefined;
let prop: string = '';
if (parent === null) {
return { parent, value, prop };
}
const parts = key.split('.').reverse();
while (parts.length) {
prop = parts.pop() ?? '';
value = Reflect.get(parent, prop);
if (!parts.length || typeof value !== 'object' || value === null) {
break;
} else {
parent = value as Prefixed<object>;
}
}
return { parent, value, prop };
}
function runComputed(
computed: Function,
key: string,
parent: Prefixed<object>,
prop: string
) {
const value = computed();
if (value instanceof Promise) {
return value.then((v) => proxyComputed(v, key, parent, prop));
}
return proxyComputed(value, key, parent, prop);
}
function proxyComputed(
value: any,
key?: string,
parent?: Prefixed<object>,
prop?: string
) {
if (typeof value === 'function') {
value[DONT_CALL] = true;
return value;
}
if (key === undefined || parent === undefined || prop === undefined) {
return clone(value);
}
return reactive(clone(value), key, parent, prop);
}
function clone<T>(target: T): T {
if (typeof target !== 'object' || target === null) {
return target;
}
const cl = Array.isArray(target) ? [] : {};
for (const key in target) {
// @ts-ignore
cl[key] = clone(target[key]);
}
return cl as T;
}
/**
* External API Code
*/
/**
* Used to override the global prefix value.
* @param value string value for the prefix eg: 'data-sb'
*/
export function prefix(value: string = 'sb'): void {
if (!value.endsWith('-')) {
value = value + '-';
}
globalPrefix = value;
}
/**
* Used to register a directive.
* @param name name of the directive
* @param cb the directive callback
* @param isParametric whether the directive is a parametric directive
*/
export function directive(
name: string,
cb: Directive,
isParametric: boolean = false
): void {
if (!globalDirectives.has(name)) {
globalDirectives.set(name, { cb, isParametric });
}
}
/**
* Initializes strawberry and returns the reactive object.
*/
export function init(): Meta {
globalData ??= reactive({}, '') as {} & Meta;