mosaic 1.0.9 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mosaic.js DELETED
@@ -1,1088 +0,0 @@
1
- function systemReducer(state, action) {
2
- switch (action.type) {
3
- case "SET": {
4
- const { name, value } = action.payload;
5
- return {
6
- ...state,
7
- [name]: value,
8
- }
9
- }
10
- case "MERGE": {
11
- return {
12
- ...state,
13
- ...action.payload,
14
- }
15
- }
16
- }
17
- }
18
-
19
- /*
20
-
21
- Notes
22
-
23
- - any call to dispatch will immediately invoke the reducer
24
- - any call to dispatch within middleware is also immediately processed
25
- - SET and MERGE are not interceptable by middleware
26
- - middleware functions are assumed to call next synchronously
27
- - the render function (subscriber) is invoked once for every call to dispatch
28
- - the render function is debounced
29
-
30
- */
31
-
32
- function configure(
33
- { update = {}, middleware = [], derivations = {}, initialState = {} },
34
- node
35
- ) {
36
- let subscribers = [];
37
- let state;
38
- let updatedCallback = () => {};
39
-
40
- let dollarKeys = Object.keys(update)
41
- .concat(...middleware.map(Object.keys))
42
- .filter((v) => v.startsWith("$"));
43
-
44
- function updateState(o) {
45
- state = { ...o };
46
- for (let k in derivations) {
47
- state[k] = derivations[k](o);
48
- }
49
- }
50
-
51
- updateState(initialState);
52
-
53
- function getState() {
54
- return { ...state }
55
- }
56
-
57
- function subscribe(fn) {
58
- subscribers.push(fn);
59
- }
60
-
61
- function flush() {
62
- subscribers.forEach((fn) => fn());
63
- subscribers = [];
64
- }
65
-
66
- function onUpdate(fn) {
67
- updatedCallback = fn;
68
- }
69
-
70
- function dispatch(action) {
71
- const { type } = action;
72
-
73
- if (type.startsWith("$") && !(type in update)) {
74
- node.dispatchEvent(
75
- new CustomEvent(type, {
76
- detail: action,
77
- bubbles: true,
78
- })
79
- );
80
- }
81
-
82
- if (type === "SET" || type === "MERGE") {
83
- updateState(systemReducer(getState(), action));
84
- } else {
85
- if (middleware.length) {
86
- let mw = middleware.slice();
87
-
88
- let next = (action) => {
89
- if (mw.length) {
90
- let x = mw.shift();
91
-
92
- if (action.type in x) {
93
- x[action.type](action, next, {
94
- getState,
95
- dispatch,
96
- afterNextRender: subscribe,
97
- });
98
- } else {
99
- next(action);
100
- }
101
- } else if (action.type in update) {
102
- updateState(update[action.type](getState(), action));
103
- }
104
- };
105
-
106
- let x = mw.shift();
107
-
108
- if (type in x) {
109
- x[type](action, next, {
110
- getState,
111
- dispatch,
112
- afterNextRender: subscribe,
113
- });
114
- } else {
115
- next(action);
116
- }
117
- } else if (type in update) {
118
- updateState(update[type](getState(), action));
119
- }
120
- }
121
- updatedCallback();
122
- }
123
-
124
- for (let actionName of dollarKeys) {
125
- node.addEventListener(actionName, ({ detail }) => dispatch(detail));
126
- }
127
-
128
- return {
129
- dispatch,
130
- getState,
131
- onUpdate,
132
- flush,
133
- }
134
- }
135
-
136
- const TEXT = 1;
137
- const ATTRIBUTE = 2;
138
- const INPUT = 3;
139
- const EVENT = 4;
140
- const REPEAT = 5;
141
-
142
- const updateFormControl = (node, value) => {
143
- if (node.nodeName === "SELECT") {
144
- Array.from(node.querySelectorAll("option")).forEach((option) => {
145
- option.selected = value.includes(option.value);
146
- });
147
- return
148
- }
149
-
150
- let checked;
151
-
152
- switch (node.getAttribute("type")) {
153
- case "checkbox":
154
- checked = value;
155
- if (node.checked === checked) break
156
- if (checked) {
157
- node.setAttribute("checked", "");
158
- } else {
159
- node.removeAttribute("checked");
160
- }
161
- break
162
- case "radio":
163
- checked = value === node.getAttribute("value");
164
- if (node.checked === checked) break
165
- node.checked = checked;
166
- if (checked) {
167
- node.setAttribute("checked", "");
168
- } else {
169
- node.removeAttribute("checked");
170
- }
171
- break
172
- default:
173
- if (node.value === value) break
174
- node.setAttribute("value", (node.value = value || ""));
175
- break
176
- }
177
- };
178
-
179
- const last = (v = []) => v[v.length - 1];
180
-
181
- const isWhitespace = (node) => {
182
- return node.nodeType === node.TEXT_NODE && node.nodeValue.trim() === ""
183
- };
184
-
185
- const walk = (node, callback, deep = true) => {
186
- if (!node) return
187
- if (!isWhitespace(node)) {
188
- let v = callback(node);
189
- if (v === false) return
190
- if (v?.nodeName) return walk(v, callback, deep)
191
- }
192
- if (deep) walk(node.firstChild, callback, deep);
193
- walk(node.nextSibling, callback, deep);
194
- };
195
-
196
- const transformBrackets = (str = "") => {
197
- let parts = str.split(/(\[[^\]]+\])/).filter((v) => v);
198
- return parts.reduce((a, part) => {
199
- let v = part.charAt(0) === "[" ? "." + part.replace(/\./g, ":") : part;
200
- return a + v
201
- }, "")
202
- };
203
-
204
- const getTarget = (path, target) => {
205
- let parts = transformBrackets(path)
206
- .split(".")
207
- .map((k) => {
208
- if (k.charAt(0) === "[") {
209
- let p = k.slice(1, -1).replace(/:/g, ".");
210
- return getValueAtPath(p, target)
211
- } else {
212
- return k
213
- }
214
- });
215
-
216
- let t =
217
- parts.slice(0, -1).reduce((o, k) => {
218
- return o && o[k]
219
- }, target) || target;
220
- return [t, last(parts)]
221
- };
222
-
223
- const getValueAtPath = (path, target) => {
224
- let [a, b] = getTarget(path, target);
225
- let v = a?.[b];
226
- if (typeof v === "function") return v.bind(a)
227
- return v
228
- };
229
-
230
- const fragmentFromTemplate = (v) => {
231
- if (typeof v === "string") {
232
- let tpl = document.createElement("template");
233
- tpl.innerHTML = v.trim();
234
- return tpl.content
235
- }
236
- if (v.nodeName === "TEMPLATE") return v.cloneNode(true).content
237
- if (v.nodeName === "defs") return v.firstElementChild.cloneNode(true)
238
- };
239
-
240
- const debounce = (fn) => {
241
- let wait = false;
242
- let invoke = false;
243
- return () => {
244
- if (wait) {
245
- invoke = true;
246
- } else {
247
- wait = true;
248
- fn();
249
- requestAnimationFrame(() => {
250
- if (invoke) fn();
251
- wait = false;
252
- });
253
- }
254
- }
255
- };
256
-
257
- const isPrimitive = (v) => v === null || typeof v !== "object";
258
-
259
- const typeOf = (v) =>
260
- Object.prototype.toString.call(v).match(/\s(.+[^\]])/)[1];
261
-
262
- const pascalToKebab = (string) =>
263
- string.replace(/[\w]([A-Z])/g, function (m) {
264
- return m[0] + "-" + m[1].toLowerCase()
265
- });
266
-
267
- const kebabToPascal = (string) =>
268
- string.replace(/[\w]-([\w])/g, function (m) {
269
- return m[0] + m[2].toUpperCase()
270
- });
271
-
272
- const applyAttribute = (node, name, value) => {
273
- name = pascalToKebab(name);
274
-
275
- if (typeof value === "boolean") {
276
- if (name.startsWith("aria-")) {
277
- value = "" + value;
278
- } else if (value) {
279
- value = "";
280
- }
281
- }
282
-
283
- if (typeof value === "string" || typeof value === "number") {
284
- node.setAttribute(name, value);
285
- } else {
286
- node.removeAttribute(name);
287
- }
288
- };
289
-
290
- const attributeToProp = (k, v) => {
291
- let name = kebabToPascal(k);
292
- if (v === "") v = true;
293
- if (k.startsWith("aria-")) {
294
- if (v === "true") v = true;
295
- if (v === "false") v = false;
296
- }
297
- return {
298
- name,
299
- value: v,
300
- }
301
- };
302
-
303
- function parseEach(node) {
304
- let each = node.getAttribute("each");
305
- let m = each?.match(/(.+)\s+in\s+(.+)/);
306
- if (!m) {
307
- if (!each) return m
308
- return {
309
- path: each.trim(),
310
- key: node.getAttribute("key"),
311
- }
312
- }
313
- let [_, left, right] = m;
314
- let parts = left.match(/\(([^\)]+)\)/);
315
- let [a, b] = (parts ? parts[1].split(",") : [left]).map((v) => v.trim());
316
-
317
- return {
318
- path: right.trim(),
319
- identifier: b ? b : a,
320
- index: b ? a : b,
321
- key: node.getAttribute("key"),
322
- }
323
- }
324
-
325
- const getBlockSize = (template) => {
326
- let i = 0;
327
- walk(template.content?.firstChild || template.firstChild, () => i++, false);
328
- return i
329
- };
330
-
331
- const nextNonWhitespaceSibling = (node) => {
332
- return isWhitespace(node.nextSibling)
333
- ? nextNonWhitespaceSibling(node.nextSibling)
334
- : node.nextSibling
335
- };
336
-
337
- const getBlockFragments = (template, numBlocks) => {
338
- let blockSize = getBlockSize(template);
339
-
340
- let r = [];
341
- if (numBlocks) {
342
- while (numBlocks--) {
343
- let f = document.createDocumentFragment();
344
- let n = blockSize;
345
- while (n--) {
346
- f.appendChild(nextNonWhitespaceSibling(template));
347
- }
348
- r.push(f);
349
- }
350
- }
351
- return r
352
- };
353
-
354
- const getBlocks = (template) => {
355
- let numBlocks = template.getAttribute("length");
356
- let blockSize = getBlockSize(template);
357
- let r = [];
358
- let node = template;
359
- if (numBlocks) {
360
- while (numBlocks--) {
361
- let f = [];
362
- let n = blockSize;
363
- while (n--) {
364
- node = nextNonWhitespaceSibling(node);
365
- f.push(node);
366
- }
367
- r.push(f);
368
- }
369
- }
370
- return r
371
- };
372
-
373
- const compareKeyedLists = (key, a = [], b = []) => {
374
- let delta = b.map(([k, item]) =>
375
- !key ? (k in a ? k : -1) : a.findIndex(([_, v]) => v[key] === item[key])
376
- );
377
- if (a.length !== b.length || !delta.every((a, b) => a === b)) return delta
378
- };
379
-
380
- function lastChild(v) {
381
- return (v.nodeType === v.DOCUMENT_FRAGMENT_NODE && v.lastChild) || v
382
- }
383
-
384
- const updateList = (template, delta, entries, createListItem) => {
385
- let n = template.getAttribute("length") || 0;
386
- let blocks = getBlockFragments(template, n);
387
- let t = template;
388
-
389
- delta.forEach((i, newIndex) => {
390
- let frag =
391
- i === -1
392
- ? createListItem(entries[newIndex][1], entries[newIndex][0])
393
- : blocks[i];
394
- let x = lastChild(frag);
395
- t.after(frag);
396
- t = x;
397
- });
398
-
399
- template.setAttribute("length", delta.length);
400
- };
401
-
402
- const VALUE = 1;
403
- const KEY = 2;
404
- const FUNCTION = 3;
405
-
406
- const hasMustache = (v) => v.match(/({{[^{}]+}})/);
407
-
408
- const getParts = (value) =>
409
- value
410
- .trim()
411
- .split(/({{[^{}]+}})/)
412
- .filter((v) => v)
413
- .map((value) => {
414
- let match = value.match(/{{([^{}]+)}}/);
415
-
416
- if (!match)
417
- return {
418
- type: VALUE,
419
- value,
420
- negated: false,
421
- }
422
-
423
- value = match[1].trim();
424
- let negated = value.charAt(0) === "!";
425
- if (negated) value = value.slice(1);
426
-
427
- return {
428
- type: KEY,
429
- value,
430
- negated,
431
- }
432
- });
433
-
434
- const getValueFromParts = (target, parts) => {
435
- return parts.reduce((a, part) => {
436
- let { type, value, negated } = part;
437
-
438
- let v;
439
-
440
- if (type === VALUE) v = value;
441
- if (type === KEY) {
442
- v = getValueAtPath(value, target);
443
- }
444
- if (type === FUNCTION) {
445
- let args = part.args.map((value) => getValueAtPath(value, target));
446
-
447
- v = getValueAtPath(part.method, target)?.(...args);
448
- }
449
-
450
- if (negated) v = !v;
451
-
452
- return a || a === 0 ? a + v : v
453
- }, "")
454
- };
455
-
456
- const pascalToKebab$1 = (string) =>
457
- string.replace(/[\w]([A-Z])/g, function (m) {
458
- return m[0] + "-" + m[1].toLowerCase()
459
- });
460
-
461
- const kebabToPascal$1 = (string) =>
462
- string.replace(/[\w]-([\w])/g, function (m) {
463
- return m[0] + m[2].toUpperCase()
464
- });
465
-
466
- const parseStyles = (value) => {
467
- let type = typeof value;
468
-
469
- if (type === "string")
470
- return value.split(";").reduce((o, value) => {
471
- const [k, v] = value.split(":").map((v) => v.trim());
472
- if (k) o[k] = v;
473
- return o
474
- }, {})
475
-
476
- if (type === "object") return value
477
-
478
- return {}
479
- };
480
-
481
- const joinStyles = (value) =>
482
- Object.entries(value)
483
- .map(([k, v]) => `${k}: ${v};`)
484
- .join(" ");
485
-
486
- const convertStyles = (o) =>
487
- Object.keys(o).reduce((a, k) => {
488
- a[pascalToKebab$1(k)] = o[k];
489
- return a
490
- }, {});
491
-
492
- const applyAttribute$1 = (node, name, value) => {
493
- if (name === "style") {
494
- value = joinStyles(
495
- convertStyles({
496
- ...parseStyles(node.getAttribute("style")),
497
- ...parseStyles(value),
498
- })
499
- );
500
- } else if (name === "class") {
501
- switch (typeOf(value)) {
502
- case "Array":
503
- value = value.join(" ");
504
- break
505
- case "Object":
506
- value = Object.keys(value)
507
- .reduce((a, k) => {
508
- if (value[k]) a.push(k);
509
- return a
510
- }, [])
511
- .join(" ");
512
- break
513
- }
514
- } else if (!isPrimitive(value)) {
515
- return (node[kebabToPascal$1(name)] = value)
516
- }
517
-
518
- name = pascalToKebab$1(name);
519
-
520
- if (typeof value === "boolean") {
521
- if (name.startsWith("aria-")) {
522
- value = "" + value;
523
- } else if (value) {
524
- value = "";
525
- }
526
- }
527
-
528
- let current = node.getAttribute(name);
529
-
530
- if (value === current) return
531
-
532
- if (typeof value === "string" || typeof value === "number") {
533
- node.setAttribute(name, value);
534
- } else {
535
- node.removeAttribute(name);
536
- }
537
- };
538
-
539
- const handler = ({ path, identifier, key, index, i, k }) => ({
540
- get(target, property) {
541
- let x = getValueAtPath(path, target);
542
-
543
- // x === the collection
544
-
545
- if (property === identifier) {
546
- for (let n in x) {
547
- let v = x[n];
548
- if (key) {
549
- if (v[key] === k) return v
550
- } else {
551
- if (n == i) return v
552
- }
553
- }
554
- }
555
-
556
- if (property === index) {
557
- for (let n in x) {
558
- let v = x[n];
559
- if (key) {
560
- if (v[key] === k) return n
561
- } else {
562
- if (n == i) return n
563
- }
564
- }
565
- }
566
-
567
- let t = key ? x.find((v) => v[key] === k) : x[i];
568
- if (t?.hasOwnProperty?.(property)) return t[property]
569
-
570
- return Reflect.get(...arguments)
571
- },
572
- set(target, property, value) {
573
- let x = getValueAtPath(path, target);
574
- let t = key ? x.find((v) => v[key] === k) : x[i];
575
- if (t && !isPrimitive(t)) {
576
- t[property] = value;
577
- return true
578
- }
579
-
580
- return Reflect.set(...arguments)
581
- },
582
- });
583
-
584
- const createContext = (v = []) => {
585
- let context = v;
586
- return {
587
- get: () => context,
588
- push: (v) => context.push(v),
589
- wrap: (state) => {
590
- return context.reduce(
591
- (target, ctx) => new Proxy(target, handler(ctx)),
592
- state
593
- )
594
- },
595
- }
596
- };
597
-
598
- const render = (
599
- target,
600
- { getState, dispatch },
601
- template,
602
- updatedCallback,
603
- beforeMountCallback
604
- ) => {
605
- let observer = () => {
606
- let subscribers = new Set();
607
- return {
608
- publish: (cb) => {
609
- for (let fn of subscribers) {
610
- fn();
611
- }
612
- cb?.();
613
- },
614
- subscribe(fn) {
615
- subscribers.add(fn);
616
- },
617
- }
618
- };
619
-
620
- const createSubscription = {
621
- [TEXT]: ({ value, node, context }, { getState }) => {
622
- return {
623
- handler: () => {
624
- let state = context ? context.wrap(getState()) : getState();
625
- let a = node.textContent;
626
- let b = getValueFromParts(state, getParts(value));
627
- if (a !== b) node.textContent = b;
628
- },
629
- }
630
- },
631
- [ATTRIBUTE]: ({ value, node, name, context }, { getState }) => {
632
- return {
633
- handler: () => {
634
- let state = context ? context.wrap(getState()) : getState();
635
- let b = getValueFromParts(state, getParts(value));
636
-
637
- applyAttribute$1(node, name, b);
638
-
639
- if (node.nodeName === "OPTION") {
640
- let path = node.parentNode.getAttribute("name");
641
- let selected = getValueAtPath(path, state);
642
- node.selected = selected === b;
643
- }
644
- },
645
- }
646
- },
647
- [INPUT]: ({ node, path, context }, { getState, dispatch }) => {
648
- node.addEventListener("input", () => {
649
- let value =
650
- node.getAttribute("type") === "checkbox" ? node.checked : node.value;
651
-
652
- if (value.trim?.().length && !isNaN(value)) value = +value;
653
-
654
- if (context) {
655
- let state = context.wrap(getState());
656
- state[path] = value;
657
- dispatch({
658
- type: "MERGE",
659
- payload: state,
660
- });
661
- } else {
662
- dispatch({
663
- type: "SET",
664
- payload: {
665
- name: path,
666
- value,
667
- context,
668
- },
669
- });
670
- }
671
- });
672
-
673
- return {
674
- handler: () => {
675
- let state = context ? context.wrap(getState()) : getState();
676
- updateFormControl(node, getValueAtPath(path, state));
677
- },
678
- }
679
- },
680
- [EVENT]: (
681
- { node, eventType, actionType, context },
682
- { dispatch, getState }
683
- ) => {
684
- node.addEventListener(eventType, (event) => {
685
- let action = {
686
- type: actionType,
687
- event,
688
- context: context ? context.wrap(getState()) : getState(),
689
- };
690
-
691
- dispatch(action);
692
- });
693
- return {
694
- handler: () => {},
695
- }
696
- },
697
- [REPEAT]: (
698
- {
699
- node,
700
- context,
701
- map,
702
- path,
703
- identifier,
704
- index,
705
- key,
706
- blockIndex,
707
- hydrate,
708
- pickupNode,
709
- },
710
- { getState }
711
- ) => {
712
- let oldValue;
713
- node.$t = blockIndex - 1;
714
-
715
- const initialiseBlock = (rootNode, i, k, exitNode) => {
716
- walk(
717
- rootNode,
718
- multi(
719
- (node) => {
720
- if (node === exitNode) return false
721
- },
722
- bindAll(
723
- map,
724
- hydrate,
725
- createContext(
726
- (context?.get() || []).concat({
727
- path,
728
- identifier,
729
- key,
730
- index,
731
- i,
732
- k,
733
- })
734
- )
735
- ),
736
- (child) => (child.$t = blockIndex)
737
- )
738
- );
739
- };
740
-
741
- function firstChild(v) {
742
- return (v.nodeType === v.DOCUMENT_FRAGMENT_NODE && v.firstChild) || v
743
- }
744
-
745
- const createListItem = (datum, i) => {
746
- let k = datum[key];
747
- let frag = fragmentFromTemplate(node);
748
- initialiseBlock(firstChild(frag), i, k);
749
- return frag
750
- };
751
-
752
- if (hydrate) {
753
- let x = getValueAtPath(path, getState());
754
- let blocks = getBlocks(node);
755
-
756
- blocks.forEach((block, i) => {
757
- let datum = x[i];
758
- let k = datum?.[key];
759
- initialiseBlock(block[0], i, k, last(block).nextSibling);
760
- });
761
-
762
- pickupNode = last(last(blocks)).nextSibling;
763
- }
764
-
765
- return {
766
- handler: () => {
767
- let state = context ? context.wrap(getState()) : getState();
768
-
769
- const newValue = Object.entries(getValueAtPath(path, state) || []);
770
- const delta = compareKeyedLists(key, oldValue, newValue);
771
-
772
- if (delta) {
773
- updateList(node, delta, newValue, createListItem);
774
- }
775
- oldValue = newValue.slice(0);
776
- },
777
- pickupNode,
778
- }
779
- },
780
- };
781
-
782
- const mediator = () => {
783
- const o = observer();
784
- return {
785
- bind(v) {
786
- let s = createSubscription[v.type](v, { getState, dispatch });
787
- o.subscribe(s.handler);
788
- return s
789
- },
790
- // scheduleUpdate: debounce((state, cb) => {
791
- // return o.publish(state, cb)
792
- // }),
793
- update(cb) {
794
- return o.publish(cb)
795
- },
796
- }
797
- };
798
-
799
- const { bind, update } = mediator();
800
-
801
- let blockCount = 0;
802
-
803
- const parse = (frag) => {
804
- let index = 0;
805
- let map = {};
806
-
807
- walk(frag, (node) => {
808
- let x = [];
809
- let pickupNode;
810
- switch (node.nodeType) {
811
- case node.TEXT_NODE: {
812
- let value = node.textContent;
813
- if (hasMustache(value)) {
814
- x.push({
815
- type: TEXT,
816
- value,
817
- });
818
- }
819
- break
820
- }
821
- case node.ELEMENT_NODE: {
822
- let each = parseEach(node);
823
-
824
- if (each) {
825
- let ns = node.namespaceURI;
826
- let m;
827
-
828
- if (ns.endsWith("/svg")) {
829
- node.removeAttribute("each");
830
- let tpl = document.createElementNS(ns, "defs");
831
- tpl.innerHTML = node.outerHTML;
832
- node.parentNode.replaceChild(tpl, node);
833
- node = tpl;
834
- m = parse(node.firstChild);
835
- } else {
836
- if (node.nodeName !== "TEMPLATE") {
837
- node.removeAttribute("each");
838
- let tpl = document.createElement("template");
839
-
840
- tpl.innerHTML = node.outerHTML;
841
- node.parentNode.replaceChild(tpl, node);
842
- node = tpl;
843
- }
844
- m = parse(node.content.firstChild);
845
- }
846
-
847
- pickupNode = node.nextSibling;
848
-
849
- x.push({
850
- type: REPEAT,
851
- map: m,
852
- blockIndex: blockCount++,
853
- ...each,
854
- pickupNode,
855
- });
856
-
857
- break
858
- }
859
-
860
- let attrs = node.attributes;
861
- let i = attrs.length;
862
- while (i--) {
863
- let { name, value } = attrs[i];
864
-
865
- if (
866
- name === ":name" &&
867
- value &&
868
- (node.nodeName === "INPUT" ||
869
- node.nodeName === "SELECT" ||
870
- node.nodeName === "TEXTAREA")
871
- ) {
872
- x.push({
873
- type: INPUT,
874
- path: value,
875
- });
876
-
877
- node.removeAttribute(name);
878
- node.setAttribute("name", value);
879
- } else if (name.startsWith(":on")) {
880
- node.removeAttribute(name);
881
- let eventType = name.split(":on")[1];
882
- x.push({
883
- type: EVENT,
884
- eventType,
885
- actionType: value,
886
- });
887
- } else if (name.startsWith(":")) {
888
- let prop = name.slice(1);
889
-
890
- let v = value || prop;
891
-
892
- if (!v.includes("{{")) v = `{{${v}}}`;
893
-
894
- x.push({
895
- type: ATTRIBUTE,
896
- name: prop,
897
- value: v,
898
- });
899
- node.removeAttribute(name);
900
- }
901
- }
902
- }
903
- }
904
- if (x.length) map[index] = x;
905
- index++;
906
- return pickupNode
907
- });
908
-
909
- return map
910
- };
911
-
912
- const multi =
913
- (...fns) =>
914
- (...args) => {
915
- for (let fn of fns) {
916
- let v = fn(...args);
917
- if (v === false) return false
918
- }
919
- };
920
-
921
- const bindAll = (bMap, hydrate = 0, context) => {
922
- let index = 0;
923
- return (node) => {
924
- let k = index;
925
- let p;
926
- if (k in bMap) {
927
- bMap[k].forEach((v) => {
928
- let x = bind({
929
- ...v,
930
- node,
931
- context,
932
- hydrate,
933
- });
934
- p = x.pickupNode;
935
- });
936
- node.$i = index;
937
- }
938
- index++;
939
- return p
940
- }
941
- };
942
-
943
- let frag = fragmentFromTemplate(template);
944
- let map = parse(frag);
945
-
946
- walk(frag, bindAll(map));
947
- beforeMountCallback?.(frag);
948
- target.prepend(frag);
949
- update();
950
-
951
- return debounce(() => update(updatedCallback))
952
- };
953
-
954
- const childNodes = (node) => {
955
- let frag = document.createDocumentFragment();
956
- while (node.firstChild) {
957
- frag.appendChild(node.firstChild);
958
- }
959
- return frag
960
- };
961
-
962
- const mergeSlots = (targetNode, sourceNode) => {
963
- let namedSlots = sourceNode.querySelectorAll("slot[name]");
964
-
965
- namedSlots.forEach((slot) => {
966
- let name = slot.attributes.name.value;
967
- let node = targetNode.querySelector(`[slot="${name}"]`);
968
- if (!node) {
969
- slot.parentNode.replaceChild(childNodes(slot), slot);
970
- return
971
- }
972
- node.removeAttribute("slot");
973
- slot.parentNode.replaceChild(node, slot);
974
- });
975
-
976
- let defaultSlot = sourceNode.querySelector("slot:not([name])");
977
-
978
- if (defaultSlot) {
979
- defaultSlot.parentNode.replaceChild(
980
- childNodes(targetNode.innerHTML.trim() ? targetNode : defaultSlot),
981
- defaultSlot
982
- );
983
- }
984
- };
985
-
986
- const define = (name, factory, template) =>
987
- customElements.define(
988
- name,
989
- class extends HTMLElement {
990
- async connectedCallback() {
991
- if (!this.initialised) {
992
- let config = factory(this);
993
-
994
- if (config instanceof Promise) config = await config;
995
-
996
- let { subscribe, shadow, initialState = {}, observe = [] } = config;
997
-
998
- this.connectedCallback = config.connectedCallback;
999
- this.disconnectedCallback = config.disconnectedCallback;
1000
-
1001
- const { dispatch, getState, onUpdate, flush } = configure(
1002
- config,
1003
- this
1004
- );
1005
-
1006
- initialState = getState();
1007
-
1008
- observe = observe.map(kebabToPascal);
1009
-
1010
- let observedAttributes = observe.map(pascalToKebab);
1011
-
1012
- let sa = this.setAttribute;
1013
- this.setAttribute = (k, v) => {
1014
- if (observedAttributes.includes(k)) {
1015
- let { name, value } = attributeToProp(k, v);
1016
- dispatch({
1017
- type: "SET",
1018
- payload: { name, value },
1019
- });
1020
- }
1021
- sa.apply(this, [k, v]);
1022
- };
1023
-
1024
- observedAttributes.forEach((name) => {
1025
- let property = attributeToProp(name).name;
1026
- let value;
1027
-
1028
- if (this.hasAttribute(name)) {
1029
- value = this.getAttribute(name);
1030
- } else {
1031
- value = this[property] || initialState[property];
1032
- }
1033
-
1034
- Object.defineProperty(this, property, {
1035
- get() {
1036
- return getState()[property]
1037
- },
1038
- set(v) {
1039
- dispatch({
1040
- type: "SET",
1041
- payload: { name: property, value: v },
1042
- });
1043
- if (isPrimitive(v)) {
1044
- applyAttribute(this, property, v);
1045
- }
1046
- },
1047
- });
1048
-
1049
- this[property] = value;
1050
- });
1051
-
1052
- let beforeMountCallback;
1053
-
1054
- if (shadow) {
1055
- this.attachShadow({
1056
- mode: shadow,
1057
- });
1058
- } else {
1059
- beforeMountCallback = (frag) => mergeSlots(this, frag);
1060
- }
1061
-
1062
- onUpdate(
1063
- render(
1064
- this.shadowRoot || this,
1065
- { getState, dispatch },
1066
- template,
1067
- () => {
1068
- observe.forEach((k) => {
1069
- let v = getState()[k];
1070
- if (isPrimitive(v)) applyAttribute(this, k, v);
1071
- });
1072
- subscribe?.(getState());
1073
- flush();
1074
- },
1075
- beforeMountCallback
1076
- )
1077
- );
1078
- this.initialised = true;
1079
- }
1080
- this.connectedCallback?.();
1081
- }
1082
- disconnectedCallback() {
1083
- this.disconnectedCallback?.();
1084
- }
1085
- }
1086
- );
1087
-
1088
- export { define };