Repository navigation
Expand file tree
/
Copy pathdmax.js
More file actions
1952 lines (1871 loc) · 97.5 KB
/
Copy pathdmax.js
File metadata and controls
1952 lines (1871 loc) · 97.5 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
// @js-check
const indexFirst = (s, chars, pos = 0) => {
let i, first = s.length
for (let c of chars) if ((i = s.indexOf(c, pos)) >= 0 && i < first) first = i
return first === s.length ? -1 : first
}
const NIL = Object.freeze([])
const _KEBABS = new Map(), _CAMELS = new Map()
const toName = (s, k) => {
if (!s) return s
const m = k ? _CAMELS : _KEBABS, cached = m.get(s)
if (cached !== undefined) return cached
const out = k ? s.replace(/-+([a-zA-Z]?)/g, (_, ch) => ch ? ch.toUpperCase() : '') : s.replace(/[A-Z]/g, ch => '-' + ch.toLowerCase())
m.set(s, out)
return out
}
const MOD = '^', TARG = ':', TRIG = '@', ADD = '+'
const ALL = [MOD, TARG, TRIG, ADD]
const MODS = [MOD]
const DOT = '.', ID = '#', NOT = '!', BRACKET_OPEN = '[', BRACKET_CLOSE = ']'
const NAME_DELIMS = [DOT, BRACKET_OPEN]
const SEL_LEADS = '#.[*:', SSE_COMMENT = ':'
const SI = 's', EP = DOT, SP = '_'
const M_WITH_SHAPE = 'with_shape', M_SHAPE_ONLY = 'shape_only', M_DOM = 'dom'
const WC_HOST_ROOT = '_wc'
const M_IMMEDIATE = 'immediate', M_NOT_IMMEDIATE = 'notImmediate'
const M_ONCE = 'once', M_ALWAYS = 'always', M_DEBOUNCE = 'debounce', M_THROTTLE = 'throttle', M_RAF = 'raf', M_PREVENT = 'prevent'
const M_AND = 'and', M_EQ = 'eq', M_NE = 'ne', M_LT = 'lt', M_GT = 'gt', M_LE = 'le', M_GE = 'ge', M_UNIV = '', M_CONST = 'const', M_NULL = 'null', M_TRUE = 'true', M_FALSE = 'false', M_UNDEFINED = 'undefined', M_EL = 'el', M_ATTRS = 'attrs', M_SEL = 'sel', M_SEL_ALL = 'selAll', M_SI = 'si', M_EV = 'ev', M_RW = 'rw', M_NUM = 'num', M_STR = 'str', M_BOOL = 'bool', M_JSOS = 'jsos'
const M_JSON = 'json', M_TEXT = 'text', M_HTML = 'html', M_FORM = 'form', M_SSE = 'sse'
const M_BUSY = 'busy', M_COMPLETE = 'complete', M_ERR = 'err', M_CODE = 'code', M_STAT = 'stat'
const M_NO_CACHE = 'noCache', M_HS = 'hs', M_HS_RAW = 'hsRaw', M_AUTH = 'auth'
const M_BROTLI = 'brotli', M_BR = 'br', M_GZIP = 'gzip', M_DEFLATE = 'deflate', M_COMPRESS = 'compress'
const M_REPLACE='replace', M_MERGE='merge', M_APPEND='append', M_PREPEND='prepend', M_INC='inc', M_DEC='dec'
const M_BEFORE = 'before', M_AFTER = 'after', M_INNER = 'inner', M_REMOVE = 'remove', M_OUTER = 'outer'
const M_SSE_OPEN = 'open', M_SSE_CLOSE = 'close', M_RETRY = 'retry', M_ABORT = 'abort'
const M_URL = 'url', M_BODY = 'body', M_HDR = 'h'
const M_SPREAD = 'spread', M_SEND_ALL = 'sendAll', M_PATCH_ALL = 'patchAll', M_SYNC_ALL = 'syncAll'
const M_DEBOUNCE_MS = 500, M_THROTTLE_MS = 500, M_RETRY_MS = 1000
const H_ACCEPT = 'accept', H_ACCEPT_ENCODING = 'accept-encoding', H_AUTHORIZATION = 'authorization'
const H_CACHE_CONTROL = 'cache-control', H_CONTENT_TYPE = 'content-type', H_PRAGMA = 'pragma'
const noProto = () => Object.create(null)
const ACT_HS_EMPTY = Object.freeze(noProto())
const ACT_HS_JSON = Object.freeze({ [H_CONTENT_TYPE]: 'application/json', [H_ACCEPT]: 'application/json' })
const ACT_HS_HTML = Object.freeze({ [H_ACCEPT]: 'text/html' })
const ACT_HS_FORM = Object.freeze({ [H_CONTENT_TYPE]: 'application/x-www-form-urlencoded' })
const ACT_HS_TEXT = Object.freeze({ [H_CONTENT_TYPE]: 'text/plain;charset=UTF-8' })
const ACT_HS_NO_CACHE = Object.freeze({ [H_CACHE_CONTROL]: 'no-cache', [H_PRAGMA]: 'no-cache' })
const ACT_HS_SSE = Object.freeze({ [H_ACCEPT]: 'text/event-stream', [H_CACHE_CONTROL]: 'no-cache', [H_PRAGMA]: 'no-cache' })
const SP_WIN = 'window', SP_DOC = 'document', SP_HISTORY = 'history', SP_FORM = 'form', SP_INTERVAL = 'interval', SP_TIMEOUT = 'timeout', SP_VIEWED = 'viewed', SP_INIT = 'init'
const SPS = [SP_WIN, SP_DOC, SP_HISTORY, SP_FORM, SP_INTERVAL, SP_TIMEOUT, SP_VIEWED, SP_INIT]
const SP_WIN_EV = 'resize', SP_DOC_EV = 'visibilitychange', SP_INTERVAL_MS = 500, SP_TIMEOUT_MS = 500
const SP_TA_WIN = 1, SP_TA_DOC = 2, SP_TA_FORM = 3
const SP_DEFS = Object.assign(noProto(), {
[SP_WIN]: { ta: SP_TA_WIN, ev: SP_WIN_EV },
[SP_DOC]: { ta: SP_TA_DOC, ev: SP_DOC_EV },
[SP_HISTORY]: { ta: 'history' },
[SP_FORM]: { ta: SP_TA_FORM, ev: 'submit', immediate: 1 },
[SP_INTERVAL]: { ms: SP_INTERVAL_MS, repeat: 1 },
[SP_TIMEOUT]: { ms: SP_TIMEOUT_MS },
[SP_VIEWED]: { io: 1 },
[SP_INIT]: { init: 1, act: 1 }
})
const ACT_METHODS = Object.freeze({ get: 'GET', post: 'POST', put: 'PUT', patch: 'PATCH', delete: 'DELETE' }), DM_KEY = 'data-m-'
const DM_NO = DM_KEY + 'no', DM_NO_SCAN = DM_NO + '^scan', DM_NO_MORPH = DM_NO + '^morph'
const E_RW_REQ = `dmEx ${MOD}${M_RW} requires an element/property trigger in:`
const E_RW_EL = `dmEx ${MOD}${M_RW} source element is not found in trigger:`
const E_RW_EV = `dmEx ${MOD}${M_RW} event is not found in trigger:`
const E_TRIG_EL = 'Element is not found in trigger:', E_TRIG_EV = 'Event is not found in trigger:', E_FORM_EL = 'Form element is not found for trigger:'
const IT_STATES = new WeakMap(), IT_ATTRS = new WeakMap()
const isSp = (n) => { if (n.startsWith(SP)) for (const s of SPS) if (n.startsWith(s, 1)) return true; return false }
const mkIt = (kind, not, root, path, mods = NIL) => ({ kind, not, root, path, mods, sp: kind === SP ? SP_DEFS[root] || null : null, isSi: kind === SI, isEv: kind === EP, isSp: kind === SP, isImmediate: null })
const mkMod = (not, root, path) => ({ not, root, path, isImmediate: root === M_IMMEDIATE ? true : root === M_NOT_IMMEDIATE ? false : null })
const RE_DIGITS = /^\d+$/
const parseRef = (dKey, n, pos = 0) => {
if (!n) return null
let p = pos, l = n.length
while (n.startsWith(NOT, p)) ++p
let not = p == 0 ? null : p % 2 != 0
let d = indexFirst(n, NAME_DELIMS, p)
let root = d < 0 ? (p == 0 ? n : n.slice(p)) : n.slice(p, d), kind = EP
if (root && root.length > 0) {
const id = root[0] === ID
if (id || isSp(root)) {
kind = id ? EP : SP
root = root.slice(1)
if (!root) { logErr('empty', kind + ':', n, dKey); return null }
} else {
kind = SI
root = toName(root, 1)
}
}
if (d < 0 && !root && not !== null) { logErr('bare', NOT + ':', n); return null }
if (d < 0 || (n[d] === DOT && d + 1 == l)) return mkIt(kind, not, root, null)
p = d; let path = []
while (p >= 0 && p < l) {
const c = n[p]
if (c === DOT) {
const partStart = ++p
d = indexFirst(n, NAME_DELIMS, p)
const part = n.slice(partStart, p = d < 0 ? l : d)
if (!part) { logErr('empty path part:', n, dKey); return null }
path.push(part[0] === '-' ? part : toName(part, 1))
} else if (c === BRACKET_OPEN) {
d = n.indexOf(BRACKET_CLOSE, p + 1)
if (d < 0) { logErr('missing ]:', n, dKey); return null }
const part = n.slice(p + 1, d)
if (!isDigitsOnly(part)) { logErr('non-const idx:', part, n, dKey); return null }
path.push(part)
p = d + 1
} else {
logErr('bad path token:', n, dKey)
return null
}
}
return mkIt(kind, not, root, path)
}
const parseMod = (dKey, name) => {
if (!name) return null
let p = 0, l = name.length
while (name.startsWith(NOT, p)) ++p
let not = p == 0 ? null : p % 2 != 0
const d = indexFirst(name, NAME_DELIMS, p)
let root = d < 0 ? (p == 0 ? name : name.slice(p)) : name.slice(p, d)
if (root) root = toName(root, 1)
if (root === M_CONST) return mkMod(not, root, d < 0 || d + 1 >= l ? '' : name.slice(d + 1))
if (root === 'pr') return logErr('legacy ^pr removed, use ^ / ^ev / ^el / ^si:', name, dKey), null
if (root === M_ATTRS) {
if (d < 0 || d + 1 >= l) return mkMod(not, root, { r: '', v: '' })
const rest = name.slice(d + 1)
if (rest[0] !== ID) return mkMod(not, root, { r: '', v: rest })
const d2 = rest.indexOf(DOT, 1), r = rest.slice(1, d2 < 0 ? rest.length : d2)
if (!r) return logErr('empty attrs mod:', name, dKey), null
return mkMod(not, root, { r, v: d2 < 0 ? '' : rest.slice(d2 + 1) })
}
if (root === M_SEL || root === M_SEL_ALL) return mkMod(not, root, d < 0 || d + 1 >= l ? '' : name.slice(d + 1))
return mkMod(not, root, d < 0 || d + 1 >= l ? null : name.indexOf(DOT, p = d + 1) < 0 ? toName(name.slice(p), 1) : parseRef(dKey, name, p))
}
const parse = (dKey, p) => { p ??= 'data-'.length
const n = dKey.length, items = noProto(); items[MOD] = items[TARG] = items[TRIG] = items[ADD] = NIL
while (p >= 0 && p < n) {
if ((p = indexFirst(dKey, ALL, p)) < 0) { p = n; break }
const t=dKey[p];let item = null
if (++p < n) {
const end = indexFirst(dKey, ALL, p)
const name = dKey.slice(p, p = end < 0 ? n : end)
if (name) item = t == MOD ? parseMod(dKey, name) : parseRef(dKey, name)
}
if (!item) continue
if (t == MOD) {
const ts = items[MOD]
if (ts === NIL) items[MOD] = [item]
else ts.push(item)
if (item.isImmediate !== null) items[MOD].isImmediate = item.isImmediate
continue
}
let localMods = null
while (p < n && dKey[p] == MOD) {
const end = indexFirst(dKey, ALL, ++p)
const name = dKey.slice(p, p = end < 0 ? n : end)
const mod = parseMod(dKey, name)
if (!mod) continue
if (localMods) localMods.push(mod)
else localMods = [mod]
if (mod.isImmediate !== null) localMods.isImmediate = mod.isImmediate
}
const globalMods = items[MOD], ts = items[t]
item.mods = localMods ? globalMods.length ? localMods.concat(globalMods) : localMods : globalMods
item.isImmediate = localMods?.isImmediate ?? globalMods.isImmediate ?? null
if (ts === NIL) items[t] = [item]
else ts.push(item)
}
if (p < n) warn('unparsed tail:', dKey.slice(p), dKey)
return [items, p]
}
const _parseCache = new Map()
const parseCached = (dKey) => { let r = _parseCache.get(dKey); if (!r) _parseCache.set(dKey, r = parse(dKey)[0]); return r }
const RETURN_THEN = [' ', '(', '{', ';', '[', '"', '\'', '\n', '\r', '\t']
const FN_ARGS = ['dm', 'el', 'trig', 'val', 'detail']
const _compiledFnCache = new Map()
const compileFn = (dVal, dKey, args = FN_ARGS) => {
const cacheKey = args === FN_ARGS ? dVal + '\x00' + dKey : null
if (cacheKey !== null && _compiledFnCache.has(cacheKey)) return _compiledFnCache.get(cacheKey)
let val = '' + dVal
const returnPos = val.indexOf('return')
let body = returnPos >= 0 && (returnPos + 6 >= val.length || indexFirst(val, RETURN_THEN, returnPos + 6) == returnPos + 6) ? val : `return(${val})`
body = `try{ ${body} }catch(e){ console.error('[dmax]','eval ${dKey}:',e.message,${val}); return }`
let fn
try { fn = Function(...args, body) }
catch (e) { logErr(`compile ${dKey}:`, e.message, val); return }
if (cacheKey !== null) _compiledFnCache.set(cacheKey, fn)
return fn;
}
const _dm = new Map()
const _wcSubs = new WeakMap()
const isWcRoot = (root) => root === WC_HOST_ROOT
// Walk up the DOM (including shadow host) to find the nearest ancestor
// whose _wc has been initialized. Falls back to lazily creating one
// on the binding's element when no scope owner is found.
const resolveWcHost = (el) => {
if (!el) return null
let cur = el
while (cur) {
if (cur._wc && typeof cur._wc === 'object') return cur
let parent = cur.parentNode
if (!parent && cur.host) parent = cur.host
cur = parent
}
return el
}
// Collect _wc subscriptions from the host and its descendants.
const getWcSubsFor = (host) => {
const out = _wcSubs.get(host) || []
const stack = [host.firstElementChild]
while (stack.length) {
const el = stack.pop()
if (!el) continue
const s = _wcSubs.get(el)
if (s && s.length) for (const sub of s) out.push(sub)
if (el.shadowRoot) for (let ch = el.shadowRoot.firstElementChild; ch; ch = ch.nextElementSibling) stack.push(ch)
for (let ch = el.lastElementChild; ch; ch = ch.previousElementSibling) stack.push(ch)
}
return out
}
const DM = new Proxy({}, {
get: (_, key) => _dm.get(key),
set: (_, key, val) => { _dm.set(key, val); return true; },
has: (_, key) => _dm.has(key),
ownKeys: () => Array.from(_dm.keys()),
getOwnPropertyDescriptor: (_, key) =>
_dm.has(key) ? { value: _dm.get(key), enumerable: true, configurable: true } : undefined
});
// - data-m-si='{foo: {bar: "hey"}, baz: 1}' // top level fields to signals
// - data-m-si:foo='{bar: "hey"}' // foo signal
// - data-m-si:foo:baz='`js expr ${42}`' // eval expr as Function body and set to all signals
// - data-m-si:foo='el.Value * dm.bar' // you may use other signals and element props
const initWcStore = (host, path, val) => {
if (!path || !path.length) { host._wc = val && typeof val === 'object' ? val : noProto(); return }
if (!host._wc || typeof host._wc !== 'object') host._wc = noProto()
let parent = host._wc
for (let i = 0; i < path.length - 1; ++i) parent = parent[path[i]] && typeof parent[path[i]] === 'object' ? parent[path[i]] : (parent[path[i]] = noProto())
parent[path.at(-1)] = val
}
const dmSi = (el, dKey, dVal) => {
const it = parseCached(dKey), tars = it[TARG]
if (it[MOD].length || it[TRIG].length || it[ADD].length) warn('targets only:', dKey)
let fn = compileFn(dVal, dKey)
if (!fn) return
let val = dVal ? fn(DM, el, null) : null
if (!tars.length) {
if (!(val && typeof val === 'object')) return logErr('object value expected:', dKey, dVal)
for (const t in val) setSiAndNotifySubsNDeep(dKey, mkIt(SI, null, toName(t, 1), null), val[t], el)
return
}
for (const t of tars) {
if (t.kind != SI) { logErr('signal targets only:', t, dKey); continue }
if (t.mods.length) warn('mods ignored:', t.mods, dKey)
if (isWcRoot(t.root)) { if (!el) { logErr('dmSi :_wc needs a host element:', dKey); continue } initWcStore(el, t.path, val) }
else _dm.set(t.root, val)
}
}
// data-m-dbg renders the current dm state as formatted JSON into the node.
const dmDbg = (el) => { if (el) {_debugEls.add(el); updateDebug() } }
const getElById = (id, dKey) => {
const el = document.getElementById(id)
if (!el) logErr(`no #${id}:`, dKey)
return el
}
const getDefaultPr = (el) => { const t = el.type, n = el.tagName; return t === 'checkbox' || t === 'radio' ? 'checked' : n === 'DETAILS' ? 'open' : n === 'INPUT' || n === 'SELECT' || n === 'TEXTAREA' || n && n.indexOf('-') >= 0 && 'value' in el ? 'value' : 'textContent' }
const getDefaultEv = (el) => { const n = el.tagName; return n === 'FORM' ? 'submit' : n === 'DETAILS' ? 'toggle' : n === 'INPUT' || n === 'SELECT' || n === 'TEXTAREA' ? 'change' : 'click' }
const getElPrVal = (el, prPath) => {
if (!el) return null
const prop = prPath && prPath.length ? prPath[0] : getDefaultPr(el)
let val = el[prop]
if (val === undefined && el.getAttribute) val = el.getAttribute(toName(prop, 0))
return prPath && prPath.length > 1 ? getPrValAndDepth(val, prPath, -1, 1)[0] : val
}
const isDefaultPrName = (el, prop) => prop === getDefaultPr(el) || prop === 'value' || prop === 'checked' || prop === 'textContent'
const mkEv = (nam) => {
try { return new Event(nam, { bubbles: true }) }
catch (_) {
const ev = document.createEvent('Event')
ev.initEvent(nam, true, true)
return ev
}
}
const isNil = (v) => v === null || v === undefined
const getPrValAndDepth = (obj, path, depth = -1, off = 0) => {
let v = obj
if (isNil(v) || !path) return [v, 0]
let n = depth == -1 || depth > path.length - off ? path.length - off : depth
for (let i = 0; i < n; ++i) if (isNil(v = v[path[i + off]])) return [v, i + 1]
return [v, n]
}
const VAL_CHANGE_DEPTH_MAX = 32
const valChangedDeep = (before, after, depth = 0) => {
if (depth >= VAL_CHANGE_DEPTH_MAX) { console.warn('[dmax] Warning: too deep to compare for signal value change, consider it changed, stopped at:', VAL_CHANGE_DEPTH_MAX); return true }
const b = before, a = after
if (Array.isArray(b)) { // means b is also an array
if (!Array.isArray(a) || b.length != a.length) return true
for (let i = 0; i < b.length; ++i) if (valChangedDeep(b[i], a[i], ++depth)) return true
} else if (b && typeof b === 'object') {
if (!a || typeof a !== 'object') return true
for (const k in b) {
if (!(k in a)) return true
if (valChangedDeep(b[k], a[k], ++depth)) return true
}
for (const k in a) if (!(k in b)) return true
} else if (a !== b) return true
return false
}
const setPr = (el, dKey, tar, val) => {
if (!(tar.isEv || tar.isSp)) return null
let obj = tar.isSp ? tar.root === SP_WIN ? window : tar.root === SP_DOC ? document : tar.root === SP_HISTORY ? window.history : null : tar.root ? getElById(tar.root, dKey) : el
const path = tar.path; let prop = !path ? getDefaultPr(obj) : null
if (path && path.length) ([obj] = getPrValAndDepth(obj, path, path.length - 1), prop = path.at(-1))
if (!obj || !prop) return logErr('Error setting non existing property for:', tar, 'in', dKey)
try {
if (typeof obj[prop] === 'function') return Array.isArray(val) ? obj[prop](...val) : obj[prop](val)
if (prop === 'style' && isPlainObj(val) && obj[prop]) for (const k in val) {
const st = obj[prop], v = val[k], cssVar = k[0] === '-' ? k : '--' + toName(k, 0)
if (k in st) { if (valChangedDeep(st[k], v)) st[k] = v }
else if (st.getPropertyValue(cssVar) !== '' + v) st.setProperty(cssVar, v)
} else if (obj && typeof obj.setProperty === 'function' && !(prop in obj)) {
const cssVar = prop[0] === '-' ? prop : '--' + toName(prop, 0)
if (obj.getPropertyValue(cssVar) !== '' + val) obj.setProperty(cssVar, val)
} else if (valChangedDeep(obj[prop], val)) obj[prop] = val
} catch (e) { logErr('Error: Failed to set property:', e.message, '>>>', tar, 'on', el) }
return obj[prop]
}
const getComputedDisplay = (el) => (typeof window !== 'undefined' && window.getComputedStyle) ? window.getComputedStyle(el).display : ''
const applyClVal = (adds, taEl, val) => {
for (const add of adds) {
const name = add.kb || (add.kb = toName(add.root, 0))
if (add.not ? !val : !!val) taEl.classList.add(name)
else taEl.classList.remove(name)
}
}
const applyDisplayValue = (taEl, inline, origDisp, val) => {
const d = taEl.style.display
if (!val){if (d !== 'none') taEl.style.display='none';return}
if (inline) taEl.style.display=origDisp
else if (d === 'none' || getComputedDisplay(taEl) === 'none') taEl.style.display=origDisp
else taEl.style.removeProperty('display')
}
const diffShapeShallow = (before, after) => {
let b = before, a = after
if (!b || typeof b != 'object') b = NIL
if (!a || typeof a != 'object') a = NIL
if (Array.isArray(b)) {
if (Array.isArray(a)) {
const al = a.length, bl = b.length
return al == bl ? null : al > bl ? { addedRange: [bl, al - bl] } : { removedRange: [al, bl - al] }
}
let added = []
for (const k in a) if (hasOwn(a, k)) added.push(k)
return { added, removedRange: [0, b.length] }
}
if (Array.isArray(a)) {
let removed = []
for (const k in b) if (hasOwn(b, k)) removed.push(k)
return { removed, addedRange: [0, a.length] }
}
// Shallow object key shape diff: track added/removed keys only
let added = [], removed = []
for (const k in a) if (!(k in b)) added.push(k)
for (const k in b) if (!(k in a)) removed.push(k)
return added.length ? (removed.length ? { added, removed } : { added }) : (removed.length ? { removed } : null)
}
const samePath = (a, b) => {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; ++i)
if (a[i] !== b[i]) return false
return true
}
const SI_CHANGED_ANY = 0, SI_CHANGED_WITH_SHAPE = 1, SI_CHANGED_SHAPE_ONLY = 2
const MV_UNIV = 0, MV_SI = 1, MV_EV = 2, MV_ATTRS = 3, MV_SEL = 4, MV_SEL_ALL = 5, MV_EL = 6, MV_CONST = 7
const MF_ONCE = 1, MF_ALWAYS = 2, MF_PREVENT = 4, MF_NUM = 8, MF_RW = 16, MF_RAF = 32, MF_STR = 64, MF_BOOL = 128
const compileTrMods = (tr, globMods) => compileMods(tr, tr.mods.length ? tr.mods : globMods)
const modPath = (x) => x == null ? NIL : x.kind ? x.root ? x.path?.length ? [x.root, ...x.path] : [x.root] : x.path || NIL : Array.isArray(x) ? x : typeof x == 'string' ? [x] : [x]
const compileMods = (tr, mods) => {
const isTimer = tr.sp?.ms != null
let f = 0, d = 0, t = 0, p = null, c = SI_CHANGED_ANY, j = null
const rm = []
for (const m of mods) {
const r = m.root
if (r === M_WITH_SHAPE) c = SI_CHANGED_WITH_SHAPE
else if (r === M_SHAPE_ONLY) c = SI_CHANGED_SHAPE_ONLY
else if (r === M_EL) {
const x = m.path
rm.push({ s: MV_EL, r: x?.root || '', v: x?.path || NIL })
} else if (r === M_ATTRS) rm.push({ s: MV_ATTRS, r: m.path?.r || '', v: m.path?.v || '' })
else if (r === M_SEL) rm.push({ s: MV_SEL, v: m.path || '' })
else if (r === M_SEL_ALL) rm.push({ s: MV_SEL_ALL, v: m.path || '' })
else if (r === M_SI) rm.push({ s: MV_SI, v: modPath(m.path) })
else if (r === M_EV) rm.push({ s: MV_EV, v: modPath(m.path) })
else if (r === M_UNIV) rm.push({ s: MV_UNIV, v: modPath(m.path) })
else if (r === M_CONST) { const raw = m.path == null ? '' : (typeof m.path === 'string' ? m.path : String(m.path)); let val; if (raw === '') val = ''; else if (raw === 'true') val = true; else if (raw === 'false') val = false; else if (raw === 'null') val = null; else if (raw === 'undefined') val = undefined; else if (/^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(raw)) val = +raw; else val = String(raw); rm.push({ s: MV_CONST, v: val }) }
else if (r === M_NULL) rm.push({ s: MV_CONST, v: null })
else if (r === M_TRUE) rm.push({ s: MV_CONST, v: true })
else if (r === M_FALSE) rm.push({ s: MV_CONST, v: false })
else if (r === M_UNDEFINED) rm.push({ s: MV_CONST, v: undefined })
else if (r === M_ONCE) f |= MF_ONCE
else if (r === M_ALWAYS) f |= MF_ALWAYS
else if (r === M_PREVENT) f |= MF_PREVENT
else if (r === M_NUM) f |= MF_NUM
else if (r === M_STR) f |= MF_STR
else if (r === M_BOOL) f |= MF_BOOL
else if (r === M_RAF) f |= MF_RAF
else if (r === M_JSOS) j = m.path ?? 2
else if (r === M_RW) f |= MF_RW
else if (!isTimer && r === M_DEBOUNCE) d = +(resolveMPathVal(m.path) ?? M_DEBOUNCE_MS) || M_DEBOUNCE_MS
else if (!isTimer && r === M_THROTTLE) t = +(resolveMPathVal(m.path) ?? M_THROTTLE_MS) || M_THROTTLE_MS
else if (r in PERMIT_MODS) p = p ? p.push ? (p.push(m), p) : [p, m] : m
}
return { f, d, t, p, rm, c, j }
}
const getTrPrTa = (el, dKey, tr, mod, missElMsg, missEvMsg, usePrPath = true) => {
const taEl = tr.root ? getElById(tr.root, dKey) : el
if (!taEl) return logErr('Error:', missElMsg, tr, 'in:', dKey), null
let ev = tr.path ? tr.path[0] : null, prPath = null
if (ev && isDefaultPrName(taEl, ev)) prPath = tr.path, ev = getDefaultEv(taEl)
const elRm = mod.rm.find(r => r.s === MV_EL && r.r)
const readEl = elRm ? (getElById(elRm.r, dKey) || taEl) : taEl
const valRm = mod.rm.find(r => r.s === MV_UNIV && r.v.length)
const attrsRm = mod.rm.find(r => r.s === MV_ATTRS)
const selRm = mod.rm.find(r => r.s === MV_SEL || r.s === MV_SEL_ALL)
const readPath = valRm ? valRm.v : attrsRm ? attrsRm.v : selRm ? selRm.v : prPath
if (usePrPath && valRm && !elRm && valRm.v.length) prPath = valRm.v
ev = ev ?? getDefaultEv(taEl)
if (!ev) return logErr('Error:', missEvMsg, tr, 'in:', dKey), null
return readEl ? { taEl, readEl, ev, prPath, readPath, tar: mkIt(EP, null, tr.root, prPath, NIL) } : logErr('Error:', missElMsg, tr, 'in:', dKey)
}
const addNonSiTrSub = (el, tr, mod, fn, elSubs, ran, prTa = null) => {
const sp = tr.sp, isSp = !!sp
if (!isSp && !expected(prTa, 'Expected non-SP trigger target in addNonSiTrSub:', tr, 'on:', el)) return null
const modded = addTrSub(el, tr, mod, fn, elSubs, isSp ? null : prTa.taEl, isSp ? (tr.path?.[0] || sp?.ev || null) : prTa.ev, isSp ? null : prTa.prPath, isSp ? null : prTa.readPath, isSp ? null : prTa.readEl)
if (sp?.init) return modded && !ran && invokeSub(modded, { type: SP_INIT }, mod.rm.length ? getReadVal(el, mod, null) : SP_INIT, el, tr), true
if (modded && !ran && tr.isImmediate && (!sp || sp.immediate)) return invokeSub(modded, null, isSp ? null : getReadVal(prTa.readEl, mod, prTa.readPath), el, tr), true
return ran
}
const PERMIT_MODS = Object.assign(noProto(), { [M_AND]: 1, [M_EQ]: 1, [M_NE]: 1, [M_LT]: 1, [M_GT]: 1, [M_LE]: 1, [M_GE]: 1 })
const getSiVal = (it, host) => {
let sig
if (isWcRoot(it.root)) { const h = resolveWcHost(host); sig = h ? (h._wc || (h._wc = noProto())) : null }
else sig = _dm.get(it.root)
const path = it.path
return path ? getPrValAndDepth(sig, path)[0] : sig
}
const getSiValOrIt = (it, host) => {
if (!it.kind) return it
const val = getSiVal(it, host)
return it.not ? !val : val
}
const resolveMPathVal = (v, host) => {
if (v && v.kind) return getSiValOrIt(v, host)
if (typeof v !== 'string') return v
if (!isWcRoot(v) && _dm.has(v)) return _dm.get(v)
const parsed = parseRef('mod', v)
if (!parsed || !parsed.kind) return v
if (parsed.isSi && !parsed.path && !isWcRoot(parsed.root) && !_dm.has(parsed.root)) return v
return getSiValOrIt(parsed, host)
}
const dmJsos = (v, sp = 2) => typeof v === 'string' ? v : JSON.stringify(v, null, +(resolveMPathVal(sp) ?? 2) || 0)
const resolveHtmlSelector = (mPath) => {
const v = resolveMPathVal(mPath)
if (typeof v === 'string' && v) {
const c = v[0]; return SEL_LEADS.includes(c) ? v : '#' + v
}
return ''
}
const mkOrStatSi = (mod, fallbackRoot) => {
if (!mod) return null
const p = mod.path
return typeof p === 'string' ? mkIt(SI, null, p || fallbackRoot, null) : p?.isSi ? p : mkIt(SI, null, fallbackRoot, null)
}
const mkStatTar = (root, path, key) => ({ root, path: path ? path.concat(key) : [key] })
const STAT_KEYS_F = [M_BUSY, M_COMPLETE, M_SSE_OPEN, M_SSE_CLOSE], STAT_KEYS_N = [M_ERR, M_CODE, M_ABORT]
const defStatSi = (stat) => {
if (!stat) return null
let cur = _dm.get(stat.root)
if (!cur || typeof cur !== 'object') _dm.set(stat.root, cur = noProto())
let parent = cur
const path = stat.path
if (path && path.length) for (let i = 0; i < path.length; ++i) parent = parent[path[i]] && typeof parent[path[i]] === 'object' ? parent[path[i]] : (parent[path[i]] = noProto())
for (const k of STAT_KEYS_F) if (!hasOwn(parent, k)) parent[k] = false
for (const k of STAT_KEYS_N) if (!hasOwn(parent, k)) parent[k] = null
return stat
}
const mkActStats = (mod) => {
const stat = defStatSi(mkOrStatSi(mod, M_STAT))
if (!stat) return null
const { root, path } = stat, out = noProto()
for (const k of STAT_KEYS_F) out[k] = mkStatTar(root, path, k)
for (const k of STAT_KEYS_N) out[k] = mkStatTar(root, path, k)
return out
}
const isJsonContentType = (ct) => {
const low = (ct || '').toLowerCase()
if (low.indexOf('application/json') >= 0) return true
const p = low.indexOf('+json')
if (p < 0) return false
const end = p + 5
if (end >= low.length) return true
const c = low[end]
return c === ';' || c === ' ' || c === '\t'
}
const isPlainObj = (val) => !!val && typeof val === 'object' && !Array.isArray(val)
const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key)
const cloneOwnProps = (obj) => {
const out = noProto()
for (const key in obj) if (hasOwn(obj, key)) out[key] = obj[key]
return out
}
const mergeActHs = (base, extra) => {
if (!base || base === ACT_HS_EMPTY) return extra || ACT_HS_EMPTY
if (!extra || extra === ACT_HS_EMPTY) return base
const out = cloneOwnProps(base)
for (const key in extra) if (hasOwn(extra, key)) out[key] = extra[key]
return Object.freeze(out)
}
const buildActBaseHs = (isJson, isText, isHtml, isForm, isSse, noCache, enc) => {
let hs = isJson ? ACT_HS_JSON : isForm ? ACT_HS_FORM : isText ? ACT_HS_TEXT : ACT_HS_EMPTY
if (isHtml) hs = mergeActHs(hs, ACT_HS_HTML)
hs = isSse ? mergeActHs(hs, ACT_HS_SSE) : noCache ? mergeActHs(hs, ACT_HS_NO_CACHE) : hs
if (!enc) return hs
const out = hs === ACT_HS_EMPTY ? noProto() : cloneOwnProps(hs)
out[H_ACCEPT_ENCODING] = enc
return Object.freeze(out)
}
const isDigitsOnly = (s) => typeof s == 'string' && RE_DIGITS.test(s)
const buildItRefBase = (siRoot, siPath) => { let out = siRoot; if (siPath) for (let i = 0; i < siPath.length; ++i) out += '.' + siPath[i]; return out }
const buildItExprBase = (siRoot, siPath) => { let out = 'dm.' + siRoot; if (siPath) for (let i = 0; i < siPath.length; ++i) out += isDigitsOnly(siPath[i]) ? '[' + siPath[i] + ']' : '.' + siPath[i]; return out }
const buildItItemRef = (siRoot, siPath, idx) => buildItRefBase(siRoot, siPath) + '.' + idx
const buildItItemExpr = (siRoot, siPath, idx) => buildItExprBase(siRoot, siPath) + '[' + idx + ']'
const replaceItTokens = (s, itemToken, indexToken) => {
if (typeof s !== 'string') return s
let i = s.indexOf('$')
if (i < 0) return s
const parts = []; let p = 0
while (i >= 0) {
const next = s.startsWith('$it', i) ? itemToken : s.startsWith('$ix', i) ? indexToken : null
if (!next) { i = s.indexOf('$', i + 1); continue }
parts.push(s.slice(p, i), next); p = i + 3; i = s.indexOf('$', p)
}
return parts.length ? parts.join('') + s.slice(p) : s
}
const rewriteItBindings = (rootNode, itemRef, itemExpr, indexText) => {
const stack = [rootNode]
while (stack.length) {
const node = stack.pop()
const attrs = node.attributes
let nextAttrs = null
for (let i = attrs.length - 1; i >= 0; --i) {
const attr = attrs[i]
const nextName = replaceItTokens(attr.name, itemRef, indexText)
const nextVal = replaceItTokens(attr.value, itemExpr, indexText)
if (nextName !== attr.name || nextVal !== attr.value) {
if (!nextAttrs) {
// Keep a parallel attribute list for later wiring because HTML accepts
// some static directive names that DOM setAttribute rejects when recreated.
nextAttrs = []
for (let j = attrs.length - 1; j > i; --j) nextAttrs.push([attrs[j].name, attrs[j].value])
}
if (nextName === attr.name) attr.value = nextVal
}
if (nextAttrs) nextAttrs.push([nextName, nextVal])
}
if (nextAttrs) IT_ATTRS.set(node, nextAttrs)
const children = node.children
for (let i = children.length - 1; i >= 0; --i) stack.push(children[i])
}
}
const noScan = (el) => el && el.hasAttribute && (el.hasAttribute(DM_NO) || el.hasAttribute(DM_NO_SCAN))
const noMorph = (el) => el && el.hasAttribute && (el.hasAttribute(DM_NO) || el.hasAttribute(DM_NO_MORPH))
const warn = (...a) => console.warn('[dmax]', ...a), logErr = (...a) => console.error('[dmax]', ...a)
const wireItClone = (node) => {
const stack = [node]
while (stack.length) {
const el = stack.pop()
if (!el || noScan(el)) continue
const itAttrs = IT_ATTRS.get(el)
if (itAttrs && itAttrs.length) {
for (let i = 0; i < itAttrs.length; ++i) globalThis.wireNode(el, itAttrs[i][0], itAttrs[i][1])
} else if (el.attributes) {
const attrs = el.attributes
for (let i = 0; i < attrs.length; ++i) {
const attr = attrs[i]
globalThis.wireNode(el, attr.name, attr.value)
}
}
const children = el.children
for (let i = children.length - 1; i >= 0; --i) stack.push(children[i])
}
}
const expected = (v, ...msg) => v || (warn(...msg), null)
const renderItState = (el, tr, itState, tplFirst, itemRefBase, itemExprBase) => {
const val = getSiValOrIt(tr)
if (!expected(Array.isArray(val), 'dmIt expected array value from:', tr, 'on:', el)) return
const newLen = val.length, oldLen = itState.count || 0
if (newLen < oldLen) {
for (let i = 0; i < oldLen - newLen; i++) {
const node = itState.nodes.pop()
if (node && node.parentNode) node.parentNode.removeChild(node)
}
itState.count = newLen
}
if (newLen > oldLen) {
const count = newLen - oldLen
if (count === 1) {
const node = tplFirst.cloneNode(true), idxText = '' + oldLen
rewriteItBindings(node, itemRefBase + '.' + idxText, itemExprBase + '[' + idxText + ']', idxText)
el.appendChild(node), itState.nodes.push(node)
} else {
const frag = document.createDocumentFragment()
for (let idx = oldLen; idx < newLen; idx++) {
try {
const node = tplFirst.cloneNode(true)
const idxText = '' + idx
rewriteItBindings(node, itemRefBase + '.' + idxText, itemExprBase + '[' + idxText + ']', idxText)
frag.appendChild(node)
itState.nodes.push(node)
} catch { }
}
el.appendChild(frag)
}
for (let i = itState.nodes.length - count; i < itState.nodes.length; ++i) wireItClone(itState.nodes[i])
itState.count = newLen
}
}
const mergeActVals = (prev, next) => {
if (Array.isArray(prev) && Array.isArray(next)) return prev.concat(next)
if (!isPlainObj(prev) || !isPlainObj(next)) return next
const out = cloneOwnProps(prev)
for (const k in next) if (hasOwn(next, k)) out[k] = hasOwn(out, k) ? mergeActVals(out[k], next[k]) : next[k]
return out
}
const combineActResult = (prev, next, mode) => {
if (mode === M_MERGE) return mergeActVals(prev, next)
if (mode === M_INC || mode === M_DEC) return (+prev || 0) + (mode === M_INC ? 1 : -1)
if (mode === M_APPEND || mode === M_PREPEND) {
if (Array.isArray(prev) && Array.isArray(next)) return mode === M_APPEND ? prev.concat(next) : next.concat(prev)
if (typeof prev === 'string' || typeof next === 'string') return mode === M_APPEND ? '' + (prev ?? '') + (next ?? '') : '' + (next ?? '') + (prev ?? '')
}
return next
}
const getWriteMode = (mods) => { for (const m of mods || NIL) if (m.root === M_REPLACE || m.root === M_MERGE || m.root === M_APPEND || m.root === M_PREPEND || m.root === M_INC || m.root === M_DEC) return m.root; return M_REPLACE }
const patchMatchingSis = (dKey, payload, resultMode) => {
if (!isPlainObj(payload)) return
for (const key in payload) if (hasOwn(payload, key)) {
const root = toName(key, 1)
if (!_dm.has(root)) continue
setSiAndNotifySubsNDeep(dKey, mkIt(SI, null, root, null), combineActResult(_dm.get(root), payload[key], resultMode))
}
}
const applyActPayload = (dKey, resultTa, payload, resultMode, host) => {
if (!resultTa) return
const prev = getSiValOrIt(resultTa, host)
setSiAndNotifySubsNDeep(dKey, resultTa, combineActResult(prev, payload, resultMode), host)
}
const permitVal = (m, val, n = m.root, v = resolveMPathVal(m.path)) => n === M_AND ? !!v != !!m.not : n == M_EQ ? val == v : n == M_NE ? val != v : n == M_GT ? +val > +v : n == M_LT ? +val < +v : n == M_GE ? +val >= +v : +val <= +v
const modsPermitVal = (mods, val) => !mods.push ? permitVal(mods, val) : !mods.some((m) => !permitVal(m, val))
const _subs = new Map()
const _debugEls = new Set()
let _debugQueued = false
const upsert = (map, key) => {
let list = map.get(key)
if (!list) map.set(key, list = [])
return list
}
const removeSiSub = (sub) => {
const subs = isWcRoot(sub.trig.root) ? (sub.wcHost && _wcSubs.get(sub.wcHost)) : _subs.get(sub.trig.root)
if (subs) for (let i = 0; i < subs.length; ++i) if (subs[i] === sub) { subs.splice(i, 1); return }
}
const clearSubId = (sub) => {
const sp = sub.trig.sp
if (sp?.io) sub.clearId.disconnect()
else if (sp?.repeat) clearInterval(sub.clearId)
else clearTimeout(sub.clearId)
sub.clearId = null
}
const removeSubOrClearId = (sub) => {
try {
const ev = sub.ev
if (ev) ev.taEl.removeEventListener(ev.evName, sub.fn, ev.opts)
else if (sub.clearId != null) clearSubId(sub)
else removeSiSub(sub)
} catch (_) {
}
}
const PASSIVE_LISTENER_OPTS = Object.freeze({ passive: true })
const ELEMENT_NODE = 1
const invokeSub = (fn, detail, trVal, el, tr, host) => fn(DM, el, tr, tr.isSi ? getSiVal(tr, host || el) : trVal, detail)
const invokeBoundSub = (sub, detail = null, host) => sub.fn(DM, sub.el, sub.trig, sub.trig.isSi ? getSiVal(sub.trig, host || sub.el) : null, detail)
const onIntervalSub = (sub) => {
const detail = { tick: sub.tick++, ms: sub.ms, type: SP_INTERVAL }
try { invokeSub(sub.fn, detail, sub.ms, sub.el, sub.trig) }
catch (e) { logErr(`Error: interval handler (${sub.ms}ms) failed:`, e?.message ?? e) }
}
const onTimeoutSub = (sub) => {
try { invokeSub(sub.fn, { tick: 0, ms: sub.ms, type: SP_TIMEOUT }, sub.ms, sub.el, sub.trig) }
catch (e) { logErr(`timeout ${sub.ms}ms:`, e?.message ?? e) }
}
const getAttrs = (el, pre = '') => {
const out = []
if (!el) return out
const attrs = el.attributes || NIL
for (let i = 0; i < attrs.length; ++i) {
const a = attrs[i]
if (a.name.indexOf(pre) === 0) out.push({ name: a.name, value: a.value })
}
return out
}
const getQueryRoot = (el) => { let r = el?.getRootNode?.(); if (!r || r === el) r = el?.ownerDocument || document; return r && typeof r.querySelectorAll === 'function' ? r : document }
const escIdSel = (id) => {
const s = String(id || '')
if (!s) return ''
if (typeof CSS !== 'undefined' && CSS?.escape) return CSS.escape(s)
return s.replace(/["\\]/g, '\\$&')
}
const dmSel = (sel, root = document) => root.querySelector(sel || '')
const dmSelAll = (sel, root = document) => Array.from(root.querySelectorAll(sel || ''))
const dmEl = (id, root = document) => {
if (!id) return null
const rid = String(id)[0] === '#' ? String(id).slice(1) : String(id)
if (!rid) return null
if (root && typeof root.getElementById === 'function') return root.getElementById(rid)
const qRoot = root && typeof root.querySelector === 'function' ? root : getQueryRoot(root)
return qRoot && typeof qRoot.querySelector === 'function' ? qRoot.querySelector('#' + escIdSel(rid)) : null
}
const runRm = (val, readEl, mod, detail) => {
for (const rm of mod.rm) {
if (rm.s === MV_CONST) val = rm.v
else if (rm.s === MV_EV) val = rm.v.length ? getElPrVal(detail, rm.v) : getEvVal(detail)
else if (rm.s === MV_SI) val = rm.v.length ? getPrValAndDepth(val, rm.v)[0] : val
else if (rm.s === MV_SEL) val = dmSel(rm.v, getQueryRoot(readEl))
else if (rm.s === MV_SEL_ALL) val = dmSelAll(rm.v, getQueryRoot(readEl))
else if (rm.s === MV_EL) { const el = rm.r ? (dmEl(rm.r) || readEl) : readEl; val = rm.v.length ? getElPrVal(el, rm.v) : el }
else if (rm.s === MV_ATTRS) val = Array.isArray(val) ? val.map(e => getAttrs(e, rm.v)) : getAttrs(val, rm.v)
else if (rm.s === MV_UNIV && rm.v.length) { const first = getElPrVal(val, [rm.v[0]]); val = rm.v.length > 1 ? getPrValAndDepth(first, rm.v, rm.v.length - 1, 1)[0] : first }
}
return val
}
const getReadVal = (readEl, mod, readPath) => mod.rm.length ? runRm(readEl, readEl, mod, null) : getElPrVal(readEl, readPath)
const getTrVal = (detail, readEl, mod, readPath) => mod.rm.length ? runRm(readEl, readEl, mod, detail) : getElPrVal(readEl, readPath)
const addSpSub = (el, tr, sp, mod, fn, elSubs, evName) => {
if (sp.ms != null) {
const ms = +evName || sp.ms
const sub = { el, trig: tr, fn: null, siChangeM: null, ev: null, clearId: null, ms, tick: 0 }
sub.fn = applyTrMs(fn, tr, mod, sub, el)
if (sp.repeat) sub.clearId = setInterval(onIntervalSub, ms, sub)
else sub.clearId = setTimeout(onTimeoutSub, ms, sub)
elSubs.push(sub)
return sub.fn
}
if (sp.io) {
if (typeof IntersectionObserver === 'undefined') { warn('IntersectionObserver missing, skip _viewed:', el); return null }
const sub = { el, trig: tr, fn: null, siChangeM: null, ev: null, clearId: null }
sub.fn = applyTrMs(fn, tr, mod, sub, el)
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) if (entry.isIntersecting)
try { invokeSub(sub.fn, { ratio: entry.intersectionRatio, type: SP_VIEWED }, entry.intersectionRatio, el, tr) }
catch (e) { logErr('viewed handler:', e?.message ?? e) }
})
observer.observe(el)
sub.clearId = observer
elSubs.push(sub)
return sub.fn
}
if (sp.init) return applyTrMs(fn, tr, mod, null, el)
const taEl = sp.ta === SP_TA_WIN ? window : sp.ta === SP_TA_DOC ? document : sp.ta === SP_TA_FORM ? (el && el.closest ? el.closest('form') : null) : null
const ev = tr.path?.[0] || sp.ev || null
if (sp.ta === SP_TA_FORM && !taEl) return logErr('Error:', E_FORM_EL, tr, 'on:', el), null
if (!expected(taEl && ev, 'Expected event target/name in addSpSub:', tr, 'on:', el)) return null
const opts = mod.f & MF_PREVENT ? false : PASSIVE_LISTENER_OPTS
const sub = { el, trig: tr, fn: null, siChangeM: null, ev: { taEl, evName: ev, opts }, clearId: null }
const modded = applyTrMs(fn, tr, mod, sub, taEl)
sub.fn = (detail) => invokeSub(modded, detail, mod.rm.length ? getTrVal(detail, taEl, mod, null) : detail?.type ?? null, el, tr)
taEl.addEventListener(ev, sub.fn, opts)
elSubs.push(sub)
return modded
}
const addTrSub = (el, tr, mod, fn, elSubs, taEl, evName, prPath, readPath = prPath, readEl = taEl) => {
if (tr.isSi) {
const sub = { el, trig: tr, fn, siChangeM: mod.c, ev: null, clearId: null }
sub.fn = applyTrMs(fn, tr, mod, sub, el)
if (isWcRoot(tr.root)) {
const actualHost = resolveWcHost(el) || el
sub.wcHost = actualHost
upsert(_wcSubs, actualHost).push(sub)
}
else upsert(_subs, tr.root).push(sub)
;(elSubs || upsert(_cleanupBoundSubs, el)).push(sub)
return sub
}
const sp = tr.sp
if (sp) return addSpSub(el, tr, sp, mod, fn, elSubs, evName)
if (!expected(taEl && evName, 'Expected event target/name in addTrSub:', tr, 'on:', el)) return null
const opts = mod.f & MF_PREVENT ? false : PASSIVE_LISTENER_OPTS, customEv = taEl?.tagName && taEl.tagName.indexOf('-') >= 0, ev = customEv ? toName(evName, 0) : evName
const sub = { el, trig: tr, fn: null, siChangeM: null, ev: { taEl, evName: ev, opts }, clearId: null }
const modded = applyTrMs(fn, tr, mod, sub, taEl)
sub.fn = (detail) => invokeSub(modded, detail, getTrVal(detail, readEl, mod, readPath), el, tr)
taEl.addEventListener(ev, sub.fn, opts)
elSubs.push(sub)
return modded
}
const findFirstKind = (items, kind) => {
for (let i = 0; i < items.length; ++i) if (items[i].kind === kind) return items[i]
return null
}
const updateDebug = () => {
if (!_debugEls.size || _debugQueued) return
_debugQueued = true
queueMicrotask(() => {
_debugQueued = false
const state = noProto()
for (const [k, v] of _dm.entries()) state[k] = v
const txt = JSON.stringify(state, null, 2)
for (const el of _debugEls) el.textContent = txt
})
}
const setSiAndNotifySubs = (dKey, tar, val, host) => {
const root = tar?.root, path = tar?.path
if (!root) return null
const wc = isWcRoot(root)
let actualHost, siVal
if (wc) {
actualHost = resolveWcHost(host)
if (!actualHost) return null
if (!actualHost._wc || typeof actualHost._wc !== 'object') actualHost._wc = noProto()
siVal = actualHost._wc
} else {
siVal = _dm.get(root)
}
let curVal = siVal, parent = siVal, d = 0, last = null
if (path) {
if (!path.length) return null
if (!parent || typeof parent !== 'object') {
if (wc) actualHost._wc = siVal = parent = noProto()
else _dm.set(root, parent = siVal = {})
}
for (; d < path.length - 1; ++d) parent = parent[path[d]] && typeof parent[path[d]] === 'object' ? parent[path[d]] : (parent[path[d]] = {})
curVal = parent[last = path[d]]
}
// if change detected it means ALL parents of cur and SOME of children changed
if (!valChangedDeep(curVal, val)) return;
const handlers = wc ? getWcSubsFor(actualHost) : _subs.get(root) || NIL
if (!handlers || !handlers.length) {
if (!path) {
if (wc) actualHost._wc = val && typeof val === 'object' ? val : noProto()
else _dm.set(root, val)
}
else parent[last] = val
return
}
let collected = [], diffed = false, diff = null, pathDiffs = []
for (const h of handlers) {
const hp = h.trig.path, changeMod = h.siChangeM
if (!hp) {
if (!path && !diffed && changeMod !== SI_CHANGED_ANY) diffed = true, diff = diffShapeShallow(curVal, val)
if (path || changeMod !== SI_CHANGED_SHAPE_ONLY || diff) collected.push([h, path ? null : diff])
continue
}
if (path) {
const pl = path.length, hl = hp.length, minLen = hl < pl ? hl : pl
let i = 0
for (; i < minLen && path[i] == hp[i]; ++i);
if (i < minLen) continue
if (hl < pl) { collected.push([h, null]); continue }
if (pl == hl) {
if (!diffed && changeMod !== SI_CHANGED_ANY) diffed = true, diff = diffShapeShallow(curVal, val)
if (changeMod !== SI_CHANGED_SHAPE_ONLY || diff) collected.push([h, diff])
continue
}
}
const pathCur = getPrValAndDepth(siVal, hp)[0]
let pathVal = undefined, pathDiff = null
for (const col of collected) {
const p = col[0].trig.path
if (p && samePath(p, hp)) { pathVal = col[2]; break }
}
if (pathVal === undefined) {
pathVal = getPrValAndDepth(val, hp)[0]
if (!valChangedDeep(pathCur, pathVal)) continue
}
if (changeMod != SI_CHANGED_ANY) {
let pd = null
for (const x of pathDiffs) if (samePath(x[0], hp)) { pd = x; break }
if (pd) pathDiff = pd[1]
else pathDiffs.push([hp, pathDiff = diffShapeShallow(pathCur, pathVal)])
}
if (changeMod !== SI_CHANGED_SHAPE_ONLY || pathDiff) collected.push([h, pathDiff, pathVal])
}
if (!path) {
if (wc) actualHost._wc = val && typeof val === 'object' ? val : noProto()
else _dm.set(root, val)
}
else parent[last] = val
for (const col of collected) { // notify with new values and diff if asked for
const h = col[0]
invokeBoundSub(h, h.siChangeM === SI_CHANGED_ANY ? null : col[1], actualHost)
}
updateDebug()
}
let syncDepth=0,MAX_SYNC_DEPTH=32;
const setSiAndNotifySubsNDeep = (dKey, tar, val, host) => {
if (syncDepth++ > MAX_SYNC_DEPTH) return logErr(`Error: Infinite loop detected for signal: ${tar} (depth > ${MAX_SYNC_DEPTH}) in ${dKey}`)
try { return setSiAndNotifySubs(dKey, tar, val, host) } finally { syncDepth-- }
}
/**
* @typedef {(dm?: any, el?: any, trig?: any, trigVal?: any, detail?: any) => void} TriggerHandler
*/
/**
* @param {TriggerHandler} fn
* @param {{ kind: string, root?: string, path?: any, not?: any }} trig
* @param {{ el?: any, trig: any, fn?: any, siChangeM?: any, ev?: { taEl: EventTarget, evName: string, opts: any } | null, clearId?: any } | undefined} [removeSub]
* @returns {TriggerHandler}
*/
const onRaf = (fn) => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame : setTimeout)(fn, 16)
const getEvVal = (detail, dd = detail && detail.detail) => dd === undefined ? detail : dd && typeof dd === 'object' ? dd.value ?? dd.ms ?? dd : dd
const applyTrMs = (fn, tr, mod, removeSub, readEl = null) => {
const isSig = tr.isSi, deb = mod.d, thr = mod.t, permitMods = mod.p, f = mod.f, once = f & MF_ONCE && !(f & MF_ALWAYS) && removeSub, prevent = !isSig && f & MF_PREVENT, raf = f & MF_RAF, useNum = f & MF_NUM, useStr = f & MF_STR, useBool = f & MF_BOOL, jsos = mod.j
const hasPipeline = mod.rm.length > 0
if (!(once || prevent || deb || thr || raf || permitMods || tr.not || useNum || useStr || useBool || jsos != null || hasPipeline) && (isSig || removeSub || tr.sp?.init)) return fn
let tm = 0, last = 0, inDebounce = false, inRaf = false, rafPending = false
let debDm = null, debEl = null, debVal = null, debDetail = null, rafDm = null, rafEl = null, rafVal = null, rafDetail = null
let onDebounce = null, rafRun = null
const h = function (dm, el, trIt, providedVal, detail) {
trIt = trIt || tr
if (!inDebounce) {
if (prevent) detail?.preventDefault?.()
if (deb) {
onDebounce ??= function () {
inDebounce = true
try { h(debDm, debEl, null, debVal, debDetail) } finally { inDebounce = false }
}
debDm = dm, debEl = el, debVal = providedVal, debDetail = detail
clearTimeout(tm)
tm = setTimeout(onDebounce, deb)
return
}
if (thr) {
const now = Date.now()
if (now - last < thr) return