compelem 0.20.0-b2 → 0.20.1

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/index.js CHANGED
@@ -1,4181 +1,7 @@
1
1
  /**
2
- * compelem v0.20.0-b2.1772633551
2
+ * compelem v0.20.1.1773752323
3
3
  * A modern, reactive, fast, lightweight and flexible lib for building web components
4
4
  * @holyhigh2
5
5
  * git+https://github.com/holyhigh2/compelem.git
6
6
  */
7
- import myfx, { concat, toPath, some, isString, isUndefined, isBlank, closest, defaults, isLowerCaseChar, merge, each, kebabCase, has, toArray, set, get, includes, find, debounce, throttle, once, remove, map, size, isSymbol, isFunction, isArray, isObject, eachRight, slice, flatMap, test, assign, first, walkTree, isEmpty, filter, camelCase, isNull, startsWith, isNil, bind as bind$1, isDefined, trim, isBoolean, parseJSON, cloneDeep, keys, groupBy, last, reject, toString, reduce, compact, initial, except, join, split, isEqual, replace, replaceAll, snakeCase, isMatch, clone, findIndex, call } from 'myfx';
8
-
9
- /**
10
- * 样式模板
11
- * @author holyhigh2
12
- */
13
- class CssTemplate {
14
- strings;
15
- vars;
16
- constructor(strings, vars) {
17
- this.strings = concat(strings);
18
- this.vars = vars;
19
- }
20
- getCss(comp) {
21
- let str = '';
22
- this.strings.forEach((s, i) => {
23
- str = str + s + (this.vars[i] ?? '');
24
- });
25
- return str;
26
- }
27
- destroy() {
28
- this.strings = this.vars = null;
29
- }
30
- }
31
-
32
- const SLOT_NAME_DEFAULT = 'default';
33
- /**
34
- * 共享内容
35
- */
36
- const EXP_KEY = /\s+\.?key\s*=/;
37
- var CollectorType;
38
- (function (CollectorType) {
39
- CollectorType[CollectorType["RENDER"] = 1] = "RENDER";
40
- CollectorType[CollectorType["COMPUTED"] = 2] = "COMPUTED";
41
- CollectorType[CollectorType["DIRECTIVE"] = 3] = "DIRECTIVE";
42
- })(CollectorType || (CollectorType = {}));
43
- var Mode;
44
- (function (Mode) {
45
- Mode["Prod"] = "prod";
46
- Mode["Dev"] = "dev";
47
- })(Mode || (Mode = {}));
48
- const DefinitionCompEventMap = new Map();
49
- const DefinitionTagMap = {};
50
- const DefinitionWatchMap = new Map();
51
- const DefinitionComputedMap = new Map();
52
- const DefinitionStateMap = new Map();
53
- const DefinitionPropMap = new Map();
54
- const DefinitionDecoratorMap = new Map();
55
- const ObservedAttrsMap = new Map();
56
- const ComponentDynamicCssUpdaterMap = new WeakMap();
57
- const PATH_SEPARATOR = '-';
58
-
59
- function showError(msg) {
60
- console.error(`[CompElem]`, msg);
61
- }
62
- function showTagError(tagName, msg) {
63
- console.error(`[CompElem <${tagName}>]`, msg);
64
- }
65
- function showWarn(...args) {
66
- console.warn(`[CompElem]`, ...args);
67
- }
68
- function showTagWarn(tagName, msg) {
69
- console.warn(`[CompElem <${tagName}>]`, msg);
70
- }
71
- //为依赖收集提供标准地址
72
- function _toUpdatePath(varPath) {
73
- return toPath(varPath).join("-");
74
- }
75
- //获取父类构造
76
- function _getSuper(cls) {
77
- return Object.getPrototypeOf(cls);
78
- }
79
- function isBooleanProp(type) {
80
- return type === Boolean || some(type, t => t === Boolean);
81
- }
82
- //返回boolean值或非boolean值
83
- function getBooleanValue(v) {
84
- let val = v;
85
- if (isString(v) && /(?:^true$)|(?:^false$)/.test(val)) {
86
- val = val === 'true' ? true : false;
87
- }
88
- else if (isUndefined(val) || isBlank(val)) {
89
- val = true;
90
- }
91
- return val;
92
- }
93
- const DomUtil = {
94
- getNodes(startNode, endNode) {
95
- let nextNode = startNode.nextSibling;
96
- if (!endNode)
97
- return [nextNode];
98
- let rs = [];
99
- while (nextNode && nextNode !== endNode) {
100
- rs.push(nextNode);
101
- nextNode = nextNode?.nextSibling;
102
- }
103
- return rs;
104
- },
105
- insertBefore: function (node, newNodes) {
106
- if (!node.parentNode)
107
- return;
108
- let fragment = document.createDocumentFragment();
109
- fragment.append(...newNodes);
110
- node.parentNode.insertBefore(fragment, node);
111
- },
112
- remove: function (startNode, endNode) {
113
- if (startNode === endNode) {
114
- startNode?.parentNode?.removeChild(startNode);
115
- return;
116
- }
117
- let nextNode = startNode.nextSibling;
118
- while (nextNode && nextNode !== endNode) {
119
- nextNode?.parentNode?.removeChild(nextNode);
120
- nextNode = startNode.nextSibling;
121
- }
122
- },
123
- //清除dom内容并释放内存
124
- clear(container, comp) {
125
- if (!container)
126
- return;
127
- let nodeIterator = document.createNodeIterator(container, NodeFilter.SHOW_COMMENT);
128
- //subscopes
129
- let currentNode;
130
- nodeIterator = document.createNodeIterator(container, NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_ELEMENT);
131
- while ((currentNode = nodeIterator.nextNode())) {
132
- if (container === currentNode)
133
- continue;
134
- if (currentNode instanceof Comment) ;
135
- else if (currentNode instanceof CompElem) {
136
- currentNode.destroy();
137
- }
138
- else ;
139
- }
140
- }
141
- };
142
- function getSlotComponent(node, renderComponent) {
143
- let documentFragment = closest(node, (n) => n.host && n.host instanceof CompElem, 'parentNode');
144
- if (documentFragment && documentFragment.host === renderComponent)
145
- return undefined;
146
- return documentFragment ? documentFragment.host : undefined;
147
- }
148
-
149
- function prop(options) {
150
- if (arguments.length === 1) {
151
- return (target, propertyKey, descriptor) => {
152
- options.required = options.required || false;
153
- options.attribute = options.attribute === false ? false : true;
154
- defineProp(target, propertyKey, options, descriptor);
155
- };
156
- }
157
- let target = arguments[0], propertyKey = arguments[1], descriptor = arguments[2];
158
- options = { type: undefined, required: false, attribute: true };
159
- if (descriptor && typeof descriptor.type === 'function') {
160
- options = defaults(descriptor, options);
161
- descriptor = undefined;
162
- }
163
- defineProp(target, propertyKey, options, descriptor);
164
- }
165
- function defineProp(target, propertyKey, options, descriptor) {
166
- if (!isLowerCaseChar(propertyKey[0])) {
167
- showError(`Prop '${propertyKey}' must be in CamelCase`);
168
- }
169
- let attrSet;
170
- if (!DefinitionPropMap.has(target.constructor.name)) {
171
- const mixinProps = {};
172
- let parentCtor = target.constructor;
173
- while ((parentCtor = _getSuper(parentCtor)) !== CompElem) {
174
- merge(mixinProps, DefinitionPropMap.get(parentCtor.name) ?? {});
175
- }
176
- attrSet = new Set();
177
- each(mixinProps, (v, k) => {
178
- if (v.attribute) {
179
- let kbb = kebabCase(k);
180
- attrSet?.add(kbb);
181
- }
182
- });
183
- ObservedAttrsMap.set(target.constructor.name, attrSet);
184
- DefinitionPropMap.set(target.constructor.name, mixinProps);
185
- }
186
- if (descriptor) {
187
- if (descriptor.get)
188
- options.getter = descriptor.get;
189
- if (descriptor.set)
190
- options.setter = descriptor.set;
191
- }
192
- if (options.attribute) {
193
- if (!attrSet) {
194
- attrSet = ObservedAttrsMap.get(target.constructor.name);
195
- }
196
- let kbb = kebabCase(propertyKey);
197
- attrSet?.add(kbb);
198
- }
199
- //observeAttrs
200
- if (!has(target.constructor, 'observedAttributes')) {
201
- target.constructor.observedAttributes = [];
202
- }
203
- if (attrSet)
204
- target.constructor.observedAttributes = toArray(attrSet);
205
- set(DefinitionPropMap.get(target.constructor.name), propertyKey, options);
206
- }
207
- //内部接口
208
- const emptySet = new Set;
209
- function _getObservedAttrs(ctor) {
210
- return ObservedAttrsMap.get(ctor.name) ?? emptySet;
211
- }
212
-
213
- /*************************************************************
214
- * 扩展事件
215
- * @author holyhigh2
216
- *
217
- * resize
218
- * outside[.mousedown/mouseup/click/dblclick] 默认click
219
- * mutate[.attr/child/char/tree]
220
- *
221
- *************************************************************/
222
- const ExtEvNames = ['resize', 'outside', 'mutate'];
223
- ///////////////////////////////////////////////// resize
224
- const AllResizeEls = new WeakMap;
225
- const AllOutsideDownEls = [];
226
- const AllOutsideClickEls = [];
227
- const AllOutsideDblClickEls = [];
228
- const resizeObserver = new ResizeObserver((entries) => {
229
- for (const entry of entries) {
230
- const contentBoxSize = Array.isArray(entry.contentBoxSize)
231
- ? entry.contentBoxSize[0]
232
- : entry.contentBoxSize;
233
- const borderBoxSize = Array.isArray(entry.borderBoxSize)
234
- ? entry.borderBoxSize[0]
235
- : entry.borderBoxSize;
236
- let cbk = AllResizeEls.get(entry.target);
237
- if (cbk) {
238
- let ev = new CustomEvent('resize', {
239
- bubbles: false,
240
- cancelable: false,
241
- detail: {
242
- borderBox: { w: borderBoxSize.inlineSize, h: borderBoxSize.blockSize },
243
- contentBox: { w: contentBoxSize.inlineSize, h: contentBoxSize.blockSize },
244
- },
245
- });
246
- cbk(ev, entry.target);
247
- }
248
- }
249
- });
250
- function addResize(node, cbk, component) {
251
- if (AllResizeEls.has(node))
252
- return;
253
- AllResizeEls.set(node, cbk);
254
- resizeObserver.observe(node);
255
- //record
256
- let observer = resizeObserver;
257
- return (remove = false) => {
258
- observer.unobserve(node);
259
- AllResizeEls.delete(node);
260
- if (remove) {
261
- observer = node = null;
262
- }
263
- };
264
- }
265
- ///////////////////////////////////////////////// mutate
266
- var MutationType;
267
- (function (MutationType) {
268
- MutationType["Child"] = "child";
269
- MutationType["Tree"] = "tree";
270
- MutationType["Attr"] = "attr";
271
- MutationType["Char"] = "char";
272
- })(MutationType || (MutationType = {}));
273
- const AllMutationEls = new WeakMap;
274
- const mutationObserver = new MutationObserver(mutations => {
275
- for (let i = 0; i < mutations.length; i++) {
276
- const mutation = mutations[i];
277
- let map = AllMutationEls.get(mutation.target);
278
- if (!map)
279
- return;
280
- let detail = {
281
- target: mutation.target
282
- };
283
- let cbk = null;
284
- switch (mutation.type) {
285
- case 'subtree':
286
- detail.type = MutationType.Tree;
287
- cbk = map[MutationType.Tree];
288
- break;
289
- case "childList":
290
- detail.type = MutationType.Child;
291
- detail.addedNodes = mutation.addedNodes;
292
- detail.removedNodes = mutation.removedNodes;
293
- cbk = map[MutationType.Child];
294
- break;
295
- case "attributes":
296
- detail.type = MutationType.Attr;
297
- detail.attributeName = mutation.attributeName;
298
- detail.oldValue = mutation.oldValue;
299
- cbk = map[MutationType.Attr];
300
- break;
301
- case "characterData":
302
- detail.type = MutationType.Char;
303
- detail.oldValue = mutation.oldValue;
304
- cbk = map[MutationType.Char];
305
- break;
306
- }
307
- if (cbk) {
308
- let ev = new CustomEvent('mutate', {
309
- bubbles: false,
310
- cancelable: false,
311
- detail
312
- });
313
- cbk(ev);
314
- }
315
- }
316
- });
317
- function addMutation(node, cbk, parts, component) {
318
- let child = includes(parts, 'child');
319
- let attr = includes(parts, 'attr');
320
- let char = includes(parts, 'char');
321
- let tree = includes(parts, 'tree');
322
- let map = AllMutationEls.get(node);
323
- if (map)
324
- return;
325
- map = {};
326
- AllMutationEls.set(node, map);
327
- if (child) {
328
- map[MutationType.Child] = cbk;
329
- }
330
- if (attr) {
331
- map[MutationType.Attr] = cbk;
332
- }
333
- if (char) {
334
- map[MutationType.Char] = cbk;
335
- }
336
- if (tree) {
337
- map[MutationType.Tree] = cbk;
338
- }
339
- mutationObserver.observe(node, {
340
- childList: child,
341
- attributes: attr,
342
- characterData: char,
343
- subtree: tree
344
- });
345
- //record
346
- return (remove = false) => {
347
- AllMutationEls.delete(node);
348
- if (remove) {
349
- node = null;
350
- }
351
- };
352
- }
353
- ///////////////////////////////////////////////// outside
354
- document.addEventListener('mousedown', e => {
355
- let t = get(e.composedPath(), 0, e.target);
356
- AllOutsideDownEls.forEach(([node, cbk]) => {
357
- if (!node.contains(t) && !node.contains(closest(t, (node) => node instanceof ShadowRoot, 'parentNode')?.host)) {
358
- let ev = new CustomEvent('outside', {
359
- bubbles: false,
360
- cancelable: false,
361
- detail: {
362
- currentTarget: node,
363
- event: e
364
- },
365
- });
366
- cbk(ev, node);
367
- }
368
- });
369
- }, false);
370
- document.addEventListener('click', e => {
371
- let t = get(e.composedPath(), 0, e.target);
372
- AllOutsideClickEls.forEach(([node, cbk]) => {
373
- if (!node.contains(t) && !node.contains(closest(t, (node) => node instanceof ShadowRoot, 'parentNode')?.host)) {
374
- let ev = new CustomEvent('outside', {
375
- bubbles: false,
376
- cancelable: false,
377
- detail: {
378
- currentTarget: node,
379
- event: e
380
- },
381
- });
382
- cbk(ev, node);
383
- }
384
- });
385
- }, false);
386
- document.addEventListener('dblclick', e => {
387
- let t = get(e.composedPath(), 0, e.target);
388
- AllOutsideDblClickEls.forEach(([node, cbk]) => {
389
- if (!node.contains(t) && !node.contains(closest(t, (node) => node instanceof ShadowRoot, 'parentNode')?.host)) {
390
- let ev = new CustomEvent('outside', {
391
- bubbles: false,
392
- cancelable: false,
393
- detail: {
394
- currentTarget: node,
395
- event: e
396
- },
397
- });
398
- cbk(ev, node);
399
- }
400
- });
401
- }, false);
402
- function addOutsideMouseDown(node, cbk, component) {
403
- AllOutsideDownEls.push([node, cbk]);
404
- //record
405
- return (remove = false) => {
406
- myfx.remove(AllOutsideDownEls, el => el[0] === node && el[1] === cbk);
407
- };
408
- }
409
- function addOutsideClick(node, cbk, component) {
410
- AllOutsideClickEls.push([node, cbk]);
411
- //record
412
- return (remove = false) => {
413
- myfx.remove(AllOutsideClickEls, el => el[0] === node && el[1] === cbk);
414
- };
415
- }
416
- function addOutsideDblClick(node, cbk, component) {
417
- AllOutsideDblClickEls.push([node, cbk]);
418
- //record
419
- return (remove = false) => {
420
- myfx.remove(AllOutsideDblClickEls, el => el[0] === node && el[1] === cbk);
421
- };
422
- }
423
- function isExtEvent(evName) {
424
- return ExtEvNames.includes(evName);
425
- }
426
- function addExtEvent(evName, node, cbk, parts, component) {
427
- if (evName === 'resize') {
428
- return addResize(node, cbk);
429
- }
430
- else if (evName === 'outside') {
431
- switch (parts[0]) {
432
- case 'mousedown':
433
- return addOutsideMouseDown(node, cbk);
434
- case 'dblclick':
435
- return addOutsideDblClick(node, cbk);
436
- case 'click':
437
- default:
438
- return addOutsideClick(node, cbk);
439
- }
440
- }
441
- else if (evName === 'mutate') {
442
- return addMutation(node, cbk, parts);
443
- }
444
- }
445
-
446
- const MODI_EV_DEBOUNCE = /,|^(debounce:.+)|(debounce$)/;
447
- const MODI_EV_THROTTLE = /,|^(throttle:.+)|(throttle$)/;
448
- const MODI_EV_SELF = 'self';
449
- const MODI_EV_STOP = 'stop';
450
- const MODI_EV_PREVENT = 'prevent';
451
- const MODI_EV_ONCE = 'once';
452
- const MODI_EV_CAPTURE = 'capture';
453
- const MODI_EV_PASSIVE = 'passive';
454
- const MODI_EV_MOUSE_LEFT = 'left';
455
- const MODI_EV_MOUSE_RIGHT = 'right';
456
- const MODI_EV_MOUSE_MIDDLE = 'middle';
457
- const MODI_EV_KEYBOARD_COMBO_CTRL = 'ctrl';
458
- const MODI_EV_KEYBOARD_COMBO_ALT = 'alt';
459
- const MODI_EV_KEYBOARD_COMBO_SHIFT = 'shift';
460
- const MODI_EV_KEYBOARD_COMBO_META = 'meta';
461
- const MODI_EV_KEYBOARD_KEY_MAP = {
462
- 'esc': 'escape'
463
- };
464
- const MODI_PARAM_DIVIDER = ":";
465
- /*************************************************************
466
- * 事件修饰符
467
- * @author holyhigh2
468
- *
469
- * 全部通用 debounce/once/throttle/capture/passive 可组合
470
- * 原生通用 stop/prevent/self 可组合
471
- * 鼠标 left/right/middle 不可组合
472
- * 键盘 ctrl/alt/shift/meta 可组合 esc/letters... 不可组合,多个key并列式表示可选
473
- *
474
- * 部分修饰符支持参数,使用冒号传参如:throttle:100 / debounce:100
475
- *************************************************************/
476
- const VFN = () => { };
477
- function addEvent(fullName, cbk, node, component) {
478
- let parts = fullName.split('.');
479
- let evName = parts.shift();
480
- let isOnce = parts.includes(MODI_EV_ONCE);
481
- let c = cbk ?? VFN;
482
- let modi;
483
- if (modi = find(parts, x => MODI_EV_DEBOUNCE.test(x))) {
484
- let params = modi.split(MODI_PARAM_DIVIDER);
485
- c = debounce(c, parseInt(params[1]) || 100);
486
- }
487
- if (modi = find(parts, x => MODI_EV_THROTTLE.test(x))) {
488
- let params = modi.split(MODI_PARAM_DIVIDER);
489
- c = throttle(c, parseInt(params[1]) || 100);
490
- }
491
- if (isOnce) {
492
- c = once(c);
493
- }
494
- if (isExtEvent(evName)) {
495
- return addExtEvent(evName, node, c, parts);
496
- }
497
- let listener = (e) => {
498
- if (parts.includes(MODI_EV_PREVENT))
499
- e.preventDefault();
500
- if (parts.includes(MODI_EV_STOP))
501
- e.stopPropagation();
502
- if (parts.includes(MODI_EV_SELF) && e.target !== e.currentTarget)
503
- return;
504
- if (e instanceof MouseEvent) {
505
- if (parts.includes(MODI_EV_MOUSE_LEFT) && e.button != 0)
506
- return;
507
- if (parts.includes(MODI_EV_MOUSE_RIGHT) && e.button != 2)
508
- return;
509
- if (parts.includes(MODI_EV_MOUSE_MIDDLE) && e.button != 1)
510
- return;
511
- }
512
- else if (e instanceof KeyboardEvent) {
513
- if (remove(parts, p => p == MODI_EV_KEYBOARD_COMBO_CTRL)[0] && !e.ctrlKey)
514
- return;
515
- if (remove(parts, p => p == MODI_EV_KEYBOARD_COMBO_ALT)[0] && !e.altKey)
516
- return;
517
- if (remove(parts, p => p == MODI_EV_KEYBOARD_COMBO_SHIFT)[0] && !e.shiftKey)
518
- return;
519
- if (remove(parts, p => p == MODI_EV_KEYBOARD_COMBO_META)[0] && !e.metaKey)
520
- return;
521
- let checkKeys = map(parts, k => MODI_EV_KEYBOARD_KEY_MAP[k] || k);
522
- if (size(checkKeys) > 0 && !checkKeys.includes(e.key.toLowerCase()))
523
- return;
524
- }
525
- console.debug(evName, c.name, node.tagName);
526
- c(e);
527
- };
528
- let capture = parts.includes(MODI_EV_CAPTURE) || false;
529
- let passive = parts.includes(MODI_EV_PASSIVE) || false;
530
- let options = { capture, passive };
531
- node.addEventListener(evName, listener, options);
532
- //record
533
- return (remove = false) => {
534
- node.removeEventListener(evName, listener, options);
535
- if (remove)
536
- node = null;
537
- };
538
- }
539
-
540
- /**
541
- * 用于提供全局state状态管理
542
- * @author holyhigh2
543
- */
544
- const Collector = {
545
- popDirectiveQ() {
546
- let rs = this.__varPathList.reduceRight((acc, p) => {
547
- if (!acc.includes(p)) {
548
- acc.unshift(p);
549
- }
550
- return acc;
551
- }, []);
552
- return rs;
553
- },
554
- start() {
555
- this.__collecting = true;
556
- this.__varPathList = [];
557
- },
558
- end(renderComponent, up) {
559
- if (renderComponent && up) {
560
- renderComponent._regSubViewDeps(Collector.popVarPathList(), up);
561
- }
562
- this.__collecting = false;
563
- },
564
- popVarPathList() {
565
- let rs = Array.from(new Set(this.__varPathList));
566
- this.__varPathList = [];
567
- return rs;
568
- },
569
- __varPathList: [],
570
- __collecting: false,
571
- };
572
- //对象值在不同上下文的根路径
573
- const OBJECT_VAR_ROOT_PATH_IN_CONTEXT = new WeakMap();
574
- const OBJECT_VAR_PATH = new WeakMap();
575
- //缓存已经创建的proxy对象
576
- const PROXY_MAP = new WeakMap();
577
- //对象值的创建上下文
578
- const OBJECT_VAR_ROOT_CONTEXT = new WeakMap();
579
- //上级对象所在的扩展context
580
- const EXTRA_CONTEXT_OF_VAR = new WeakMap();
581
- function reactive(obj, context, rootProp) {
582
- if (PROXY_MAP.has(obj))
583
- return PROXY_MAP.get(obj);
584
- if (OBJECT_VAR_ROOT_CONTEXT.has(obj)) {
585
- if (rootProp) {
586
- let pathMap = OBJECT_VAR_ROOT_PATH_IN_CONTEXT.get(context);
587
- if (!pathMap) {
588
- pathMap = new WeakMap();
589
- OBJECT_VAR_ROOT_PATH_IN_CONTEXT.set(context, pathMap);
590
- }
591
- pathMap.set(obj, rootProp);
592
- let contextList = EXTRA_CONTEXT_OF_VAR.get(obj);
593
- if (!contextList) {
594
- contextList = new Set();
595
- EXTRA_CONTEXT_OF_VAR.set(obj, contextList);
596
- }
597
- contextList.add(context);
598
- }
599
- return obj;
600
- }
601
- const proxyObject = new Proxy(obj, {
602
- get(target, prop, receiver) {
603
- if (!prop)
604
- return undefined;
605
- const value = Reflect.get(target, prop, receiver);
606
- if (isSymbol(prop))
607
- return value;
608
- if (isFunction(value))
609
- return value;
610
- if (prop === 'length' && isArray(target))
611
- return value;
612
- if (Collector.__collecting) {
613
- let supPath = OBJECT_VAR_PATH.has(receiver) ? concat(OBJECT_VAR_PATH.get(receiver)) : [];
614
- supPath.push(prop);
615
- let propPath = supPath.join('.');
616
- Collector.__varPathList.push(propPath);
617
- }
618
- if (PROXY_MAP.has(value))
619
- return PROXY_MAP.get(value);
620
- let reactiveVal = value;
621
- if (isObject(value) && !isFunction(value) && !(value instanceof Node) && !Object.isFrozen(value)) {
622
- reactiveVal = reactive(value, context);
623
- let supPath = OBJECT_VAR_PATH.has(receiver) ? concat(OBJECT_VAR_PATH.get(receiver)) : [];
624
- supPath.push(prop);
625
- OBJECT_VAR_PATH.set(reactiveVal, supPath);
626
- PROXY_MAP.set(value, reactiveVal);
627
- }
628
- return reactiveVal;
629
- },
630
- set(target, prop, newValue, receiver) {
631
- if (!prop)
632
- return false;
633
- let ov = target[prop];
634
- let chain = OBJECT_VAR_PATH.get(receiver) ?? [];
635
- let subChain = concat(chain, [prop]);
636
- let hasChanged = context._hasChangedPropOrStateMap?.get(subChain[0]);
637
- let moreThan1 = subChain.length > 1;
638
- let rootObjNew = newValue;
639
- let rootObjOld = ov;
640
- if (moreThan1) {
641
- rootObjOld = rootObjNew = context._getPrivateData()[subChain[0]];
642
- }
643
- if (hasChanged) {
644
- if (!hasChanged.call(context, rootObjNew, rootObjOld, subChain, newValue, ov))
645
- return true;
646
- }
647
- else {
648
- //默认对比算法
649
- if (Object.is(ov, newValue)) {
650
- return true;
651
- }
652
- }
653
- let nv = newValue;
654
- let rs = Reflect.set(target, prop, nv);
655
- let extraContext = EXTRA_CONTEXT_OF_VAR.get(receiver);
656
- let k = subChain.join('.');
657
- //check watch
658
- context._requestWatchUpdate(nv, ov, k, rootObjNew, rootObjOld);
659
- //check computed
660
- context._requestComputedUpdate(k);
661
- notifyUpdate(context, rootObjOld, subChain);
662
- each(extraContext, ctx => {
663
- let ctxRootPath = ctx._wrapperProp[subChain[0]];
664
- let ck = subChain.join('.');
665
- ck = ck.replace(subChain[0], ctxRootPath);
666
- //check watch
667
- ctx._requestWatchUpdate(nv, ov, ck);
668
- //check computed
669
- ctx._requestComputedUpdate(ck);
670
- notifyUpdate(ctx, rootObjOld, ck.split('.'));
671
- });
672
- return rs;
673
- }
674
- });
675
- if (!OBJECT_VAR_PATH.has(proxyObject)) {
676
- OBJECT_VAR_PATH.set(proxyObject, rootProp ? [rootProp] : []);
677
- }
678
- PROXY_MAP.set(obj, proxyObject);
679
- if (rootProp) {
680
- OBJECT_VAR_ROOT_CONTEXT.set(proxyObject, context);
681
- if (!OBJECT_VAR_ROOT_PATH_IN_CONTEXT.has(context)) {
682
- let pathMap = new WeakMap();
683
- pathMap.set(proxyObject, rootProp);
684
- OBJECT_VAR_ROOT_PATH_IN_CONTEXT.set(context, pathMap);
685
- }
686
- }
687
- return proxyObject;
688
- }
689
- function notifyUpdate(context, oldValue, path, subNewValue, subOldValue) {
690
- let i = size(path);
691
- eachRight(path, (p) => {
692
- let varPath = slice(path, 0, i--);
693
- context._notify(oldValue, varPath);
694
- });
695
- }
696
- const QMap = new Map();
697
- class Queue {
698
- static nextSet = new Set();
699
- static nextPending = false;
700
- static next;
701
- static flush() {
702
- Queue.nextPending = false;
703
- let nq = Array.from(Queue.nextSet);
704
- Queue.nextSet.clear();
705
- QMap.clear();
706
- nq.forEach(u => u());
707
- nq = null;
708
- }
709
- static pushNext(updater) {
710
- Queue.nextSet.add(updater);
711
- if (!Queue.nextPending) {
712
- Queue.nextPending = true;
713
- Queue.next();
714
- }
715
- }
716
- }
717
- (() => {
718
- const p = Promise.resolve();
719
- const nextFn = Queue.flush;
720
- Queue.next = () => {
721
- p.then(nextFn);
722
- };
723
- })();
724
-
725
- const PropTypeMap = {
726
- boolean: Boolean,
727
- string: String,
728
- number: Number,
729
- object: Object,
730
- array: Array,
731
- function: Function,
732
- undefined: Object
733
- };
734
- //组件静态样式
735
- const ComponentStaticStyleMap = new WeakMap();
736
- let DefaultCss = [];
737
- let CompElemSn = 0;
738
- const SlotCompMap = new WeakMap();
739
- const EMPTY_SLOTS = {};
740
- const PROP_NAME_SLOTS = 'slots';
741
- /**
742
- * CompElem基类,意为组件元素。提供了基本内置属性及生命周期等必备接口
743
- * 每个组件都需要继承自该类
744
- *
745
- * @author holyhigh2
746
- */
747
- class CompElem extends HTMLElement {
748
- static __l_globalRule = document.createElement("style");
749
- //设置全局/组件默认属性
750
- static defaults(options) {
751
- DefaultCss = flatMap(options.css, c => {
752
- if (isString(c)) {
753
- let sheet = new CSSStyleSheet();
754
- sheet.replaceSync(c);
755
- return sheet;
756
- }
757
- else if (c instanceof CSSStyleSheet) {
758
- return c;
759
- }
760
- return [];
761
- });
762
- //todo...
763
- options.global;
764
- each(options, (v, k) => {
765
- if (test(k[0], /[A-Z]/)) ;
766
- });
767
- }
768
- #cid;
769
- #slotPropsMap = {};
770
- #data = {};
771
- #updateSources = {};
772
- #shadow;
773
- //保存所有渲染上下文 {CompElem/Directive}
774
- __updateTree;
775
- __cssSheets;
776
- _eventList;
777
- __docoEventMap;
778
- __updateCssDeps;
779
- __updateSubViewDeps;
780
- __updateViewDeps;
781
- _watchUpdateMap;
782
- _watchDeepUpdateMap;
783
- _watchKeys;
784
- _watchKeysOnceMap;
785
- _watchKeysDeep;
786
- _watchUpdateSetInNextTick;
787
- _watchUpdateArgsInNextTick;
788
- _computedUpdateDeps;
789
- _computedUpdateSetInNextTick;
790
- _hasChangedPropOrStateMap;
791
- _hasSyncPropSet;
792
- _hasShallowStateSet;
793
- get [Symbol.toStringTag]() {
794
- return this.constructor.name;
795
- }
796
- get cid() {
797
- return this.#cid;
798
- }
799
- get attrs() {
800
- return this.#attrs;
801
- }
802
- get props() {
803
- return this.#props;
804
- }
805
- get renderRoot() {
806
- return this.#renderRoot?.deref();
807
- }
808
- get renderRoots() {
809
- return this.#renderRoots.flatMap(wr => wr.deref() ?? []);
810
- }
811
- get parentComponent() {
812
- return this.#parentComponent?.deref();
813
- }
814
- get wrapperComponent() {
815
- return this.#wrapperComponent?.deref();
816
- }
817
- get slotHooks() {
818
- return this.#slotHooks;
819
- }
820
- get styleSheets() {
821
- return ComponentStaticStyleMap.get(this);
822
- }
823
- get globalStyleSheet() {
824
- return CompElem.__l_globalRule.sheet;
825
- }
826
- get isMounted() {
827
- return this.#mounted;
828
- }
829
- get slots() {
830
- return EMPTY_SLOTS;
831
- }
832
- #attrs;
833
- #props;
834
- #renderRoot;
835
- #renderRoots;
836
- #parentComponent;
837
- #wrapperComponent;
838
- #slotsEl = {};
839
- #slotHooks = {};
840
- #slotNodes = {};
841
- #mounted = false;
842
- #updateViewImmediately = false;
843
- #updateNextImmediatelyQ;
844
- //////////////////////////////////// styles
845
- /**
846
- * 组件样式,CSSStyleSheet可动态变更
847
- */
848
- static get styles() {
849
- return [];
850
- }
851
- static get globalStyle() {
852
- return undefined;
853
- }
854
- static get hostStyle() {
855
- return undefined;
856
- }
857
- get styles() {
858
- return [];
859
- }
860
- #inited = false;
861
- #initiating = false;
862
- constructor(...args) {
863
- super();
864
- this.#cid = CompElemSn++;
865
- this.__updateTree = [];
866
- //init props via constructor
867
- if (size(args) === 1) {
868
- this.#props = {};
869
- assign(this.#props, first(args));
870
- }
871
- /////////////////////////////////////////////////// slots
872
- // this.#updateSlotsAry()
873
- /////////////////////////////////////////////////// decorators create
874
- let ary = DefinitionDecoratorMap.get(this.constructor.name) ?? DefinitionDecoratorMap.get(_getSuper(this.constructor).name);
875
- ary && ary.sort((a, b) => b.priority - a.priority).forEach(dw => dw.create(this));
876
- this.#updatedD = this.#update.bind(this);
877
- }
878
- insertStyleSheet(sheet) {
879
- if (!this.#shadow)
880
- return null;
881
- let cssSheet;
882
- if (isString(sheet)) {
883
- cssSheet = new CSSStyleSheet();
884
- try {
885
- cssSheet.replaceSync(sheet);
886
- }
887
- catch (e) {
888
- }
889
- }
890
- else {
891
- if (this.#shadow.adoptedStyleSheets.includes(sheet))
892
- return sheet;
893
- cssSheet = sheet;
894
- }
895
- this.#shadow.adoptedStyleSheets = [...this.#shadow.adoptedStyleSheets, cssSheet];
896
- // Keep ComponentStyleMap in sync for this constructor
897
- const cur = ComponentStaticStyleMap.get(this) ?? [];
898
- cur.push(cssSheet);
899
- return cssSheet;
900
- }
901
- /**
902
- * Returns the root component in the parent chain, or itself if it's the top-level component.
903
- */
904
- get rootComponent() {
905
- let comp = this;
906
- while (comp.parentComponent) {
907
- comp = comp.parentComponent;
908
- }
909
- return comp;
910
- }
911
- #updatedD;
912
- connectedCallback() {
913
- //parent
914
- let node = closest(this.parentNode, (node) => node instanceof CompElem || node.host instanceof CompElem, "parentNode");
915
- this.#parentComponent = node
916
- ? node instanceof CompElem
917
- ? new WeakRef(node)
918
- : new WeakRef(node.host)
919
- : undefined;
920
- if (!CompElem.__l_globalRule.parentNode) {
921
- document.head.appendChild(CompElem.__l_globalRule);
922
- }
923
- //host styles
924
- let hostStyle = get(this.constructor, "hostStyle");
925
- let styleSheet = get(this.constructor, 'hostStyleSheet');
926
- if (hostStyle) {
927
- if (!styleSheet) {
928
- if (isString(hostStyle)) {
929
- styleSheet = new CSSStyleSheet();
930
- styleSheet.replaceSync(hostStyle);
931
- }
932
- else {
933
- styleSheet = hostStyle;
934
- }
935
- set(this.constructor, 'hostStyleSheet', styleSheet);
936
- }
937
- let styleRoot = this.#wrapperComponent?.deref()?.shadowRoot ?? this.#parentComponent?.deref()?.shadowRoot ?? this.ownerDocument;
938
- //detached el
939
- if (this.#wrapperComponent && !this.#wrapperComponent.deref()?.shadowRoot?.contains(this)) {
940
- styleRoot = closest(this, n => n instanceof HTMLDocument || n instanceof ShadowRoot, 'parentNode');
941
- }
942
- if (styleRoot && styleSheet && !styleRoot.adoptedStyleSheets.includes(styleSheet)) {
943
- styleRoot.adoptedStyleSheets = [...styleRoot.adoptedStyleSheets, styleSheet];
944
- }
945
- }
946
- this.__init();
947
- this.__bindEvents();
948
- }
949
- disconnectedCallback() {
950
- this.__unbindEvents();
951
- }
952
- __bindEvents() {
953
- let evs = this._eventList;
954
- each(evs, (v) => {
955
- let [evName, cbk, node, binded] = v;
956
- if (binded)
957
- return;
958
- if (!node)
959
- return;
960
- let handler = cbk ? cbk.bind(this) : cbk;
961
- let unbinder = addEvent(evName, handler, node);
962
- v[3] = unbinder;
963
- });
964
- //event decoration
965
- let events = DefinitionCompEventMap.get(this.constructor.name);
966
- if (size(events) > 0) {
967
- if (!this.__docoEventMap)
968
- this.__docoEventMap = new Map();
969
- each(events, ({ name, targetFn, fnName }) => {
970
- if (this.__docoEventMap.has(name + "@" + fnName))
971
- return;
972
- let eventTarget = targetFn ? targetFn(this) : this;
973
- let cbk = get(this, fnName);
974
- let handler = cbk ? cbk.bind(this) : cbk;
975
- let unbinder = addEvent(name, handler, eventTarget);
976
- this.__docoEventMap.set(name + "@" + fnName, unbinder);
977
- });
978
- }
979
- }
980
- __unbindEvents() {
981
- each(this._eventList, (v) => {
982
- let [, , , unbinder] = v;
983
- if (unbinder)
984
- unbinder();
985
- v[3] = null;
986
- });
987
- let delDecoKeys = [];
988
- each(this.__docoEventMap, (unbinder, k) => {
989
- if (unbinder)
990
- unbinder();
991
- delDecoKeys.push(k);
992
- });
993
- delDecoKeys.forEach(k => this.__docoEventMap.delete(k));
994
- }
995
- beforeDestroyed() {
996
- }
997
- destroyed() {
998
- }
999
- get isDestroyed() {
1000
- return this.#destroyed;
1001
- }
1002
- #destroyed = false;
1003
- destroy() {
1004
- if (this.#destroyed)
1005
- return;
1006
- this.#destroyed = true;
1007
- let ary = DefinitionDecoratorMap.get(this.constructor.name) ?? DefinitionDecoratorMap.get(_getSuper(this.constructor).name);
1008
- ary && ary.sort((a, b) => b.priority - a.priority).forEach(dw => {
1009
- dw.destroy(this);
1010
- });
1011
- this.beforeDestroyed();
1012
- //events
1013
- this.__unbindEvents();
1014
- each(this.#rootEvs, (hooks, evName) => {
1015
- each(hooks, hook => {
1016
- this.removeEventListener(evName, hook);
1017
- });
1018
- this.#rootEvs[evName] = null;
1019
- });
1020
- each(this.#nodeEvs, (hooks, evName) => {
1021
- each(hooks, ([hook, ref]) => {
1022
- ref.deref()?.removeEventListener(evName, hook);
1023
- });
1024
- this.#nodeEvs[evName] = null;
1025
- });
1026
- this.__docoEventMap?.clear();
1027
- this.__docoEventMap = this._eventList = null;
1028
- //styles
1029
- ComponentStaticStyleMap.delete(this);
1030
- ComponentDynamicCssUpdaterMap.get(this)?.clear();
1031
- ComponentDynamicCssUpdaterMap.delete(this);
1032
- //reactive
1033
- this._watchUpdateArgsInNextTick?.clear();
1034
- this._watchUpdateSetInNextTick?.clear();
1035
- this._watchKeysOnceMap?.clear();
1036
- this._watchUpdateMap = this._watchDeepUpdateMap = this._watchKeys = this._watchKeysDeep = this._watchKeysOnceMap = null;
1037
- this._computedUpdateDeps?.clear();
1038
- this._computedUpdateSetInNextTick?.clear();
1039
- this._computedUpdateDeps = this._computedUpdateSetInNextTick = null;
1040
- this.__updateCssDeps = this.__updateViewDeps = null;
1041
- this.__updateSubViewDeps?.clear();
1042
- this._hasChangedPropOrStateMap?.clear();
1043
- this._hasShallowStateSet?.clear();
1044
- this._hasSyncPropSet?.clear();
1045
- this._hasChangedPropOrStateMap = this._hasShallowStateSet = this._hasSyncPropSet = null;
1046
- //sup scope
1047
- if (this.#parentComponent) {
1048
- let pComp = this.#parentComponent.deref();
1049
- pComp && walkTree(pComp.__updateTree, (up) => {
1050
- if (up.__destroyed)
1051
- return;
1052
- if (up.node?.deref() === this) {
1053
- up.destroy(pComp);
1054
- remove(up.parent ? up.parent.children : pComp.__updateTree, c => c === up);
1055
- }
1056
- });
1057
- }
1058
- //sub scopes
1059
- each(this.__updateTree, up => up?.destroy(this));
1060
- //slots
1061
- each(this.#slotsEl, (slotEl) => {
1062
- SlotCompMap.delete(slotEl);
1063
- slotEl.remove();
1064
- });
1065
- each(this.#slotNodes, (nodes) => {
1066
- each(nodes, (node) => node.remove());
1067
- });
1068
- each(this.#data.slots, (nodes, k) => {
1069
- each(nodes, (node) => node.remove());
1070
- });
1071
- this.#updateSlots.clear();
1072
- this.#updateSlots = this.#slotPropsMap = this.#data.slots = null;
1073
- this.remove();
1074
- //data
1075
- this._wrapperProp =
1076
- this.#slotNodes =
1077
- this.#propsReady =
1078
- this.#renderRoot = this.#renderRoots = this.#shadow =
1079
- this.#rootEvs =
1080
- this.#nodeEvs =
1081
- this.#updateSources =
1082
- this.#attrs =
1083
- this.#props =
1084
- this.#renderRoot =
1085
- this.#renderRoots =
1086
- this.#slotHooks =
1087
- this.#updatedD =
1088
- this.#data =
1089
- this.#slotsEl =
1090
- this.__updateTree =
1091
- this.#parentComponent =
1092
- this._asyncDirectives =
1093
- this.#wrapperComponent = null;
1094
- //unmount
1095
- this.destroyed();
1096
- }
1097
- //////////////////////////////////// lifecycles
1098
- //********************************** 首次渲染
1099
- //构造时上级传递的参数
1100
- __init() {
1101
- if (this.#inited)
1102
- return;
1103
- //防止在钩子中出现重新挂载的情况
1104
- if (this.#initiating)
1105
- return;
1106
- this.#initiating = true;
1107
- let thisRef = new WeakRef(this);
1108
- //global styles
1109
- let globalTextContent = get(this.constructor, "globalStyle");
1110
- if (!isEmpty(globalTextContent) && isString(globalTextContent) && !get(this.constructor, '_globalRuleInserted')) {
1111
- CompElem.__l_globalRule.textContent += globalTextContent; //.sheet?.insertRule(globalTextContent, 0)
1112
- set(this.constructor, '_globalRuleInserted', true);
1113
- }
1114
- //component styles
1115
- let beAttached2 = ComponentStaticStyleMap.get(this);
1116
- let styleSheets = beAttached2 ?? [];
1117
- if (!beAttached2) {
1118
- each(get(this.constructor, "styles"), (st) => {
1119
- if (isString(st)) {
1120
- let sheet = new CSSStyleSheet();
1121
- sheet.replaceSync(st);
1122
- styleSheets.push(sheet);
1123
- }
1124
- else if (isFunction(st)) ;
1125
- else {
1126
- styleSheets.push(st);
1127
- }
1128
- });
1129
- ComponentStaticStyleMap.set(this, styleSheets);
1130
- }
1131
- ////////////////////////////////////////////////// Props & States
1132
- const props = this.#initProps();
1133
- this.propsReady(props);
1134
- for (const key in props) {
1135
- const v = props[key];
1136
- this.#data[key] = v;
1137
- }
1138
- this.#initStates();
1139
- //2. Data
1140
- this.#data.slots = {};
1141
- each(this.#data, (v, k) => {
1142
- let descr = Reflect.getOwnPropertyDescriptor(this.#data, k);
1143
- Reflect.defineProperty(this, k, {
1144
- get() {
1145
- let thisHost = thisRef.deref();
1146
- let v = descr?.get ? descr?.get() : Reflect.get(thisHost.#data, k);
1147
- if (Collector.__collecting) {
1148
- Collector.__varPathList.push(k);
1149
- }
1150
- if (PROXY_MAP.has(v)) {
1151
- let contextList = EXTRA_CONTEXT_OF_VAR.get(v);
1152
- if (!contextList) {
1153
- contextList = new Set();
1154
- EXTRA_CONTEXT_OF_VAR.set(v, contextList);
1155
- }
1156
- contextList.add(thisHost);
1157
- return PROXY_MAP.get(v);
1158
- }
1159
- if (isObject(v) && !isFunction(v) && !(v instanceof Node) && !Object.isFrozen(v)) {
1160
- let shallow = thisHost._hasShallowStateSet?.has(k);
1161
- v = shallow || k === PROP_NAME_SLOTS ? v : reactive(v, this, k);
1162
- }
1163
- return v;
1164
- },
1165
- set(v) {
1166
- if (descr?.set) {
1167
- descr?.set(v);
1168
- }
1169
- else {
1170
- let thisHost = thisRef.deref();
1171
- if (!thisHost.#inited) {
1172
- Reflect.set(thisHost.#data, k, v);
1173
- return;
1174
- }
1175
- let oldValue = thisHost.#data[k];
1176
- let hasChanged = thisHost._hasChangedPropOrStateMap?.get(k);
1177
- if (hasChanged) {
1178
- if (!hasChanged.call(thisHost, v, oldValue, [k], v, oldValue))
1179
- return true;
1180
- }
1181
- else {
1182
- //默认对比算法
1183
- if (Object.is(oldValue, v)) {
1184
- return true;
1185
- }
1186
- }
1187
- //check watch
1188
- thisHost._requestWatchUpdate(v, oldValue, k);
1189
- //check computed
1190
- thisHost._requestComputedUpdate(k);
1191
- Reflect.set(thisHost.#data, k, v);
1192
- thisHost._notify(oldValue, [k]);
1193
- //update sync
1194
- if (thisHost._hasSyncPropSet?.has(k)) {
1195
- thisHost.emit('update' + ":" + k, { value: v });
1196
- }
1197
- }
1198
- },
1199
- });
1200
- });
1201
- Reflect.defineProperty(this.#data, '__isData', {
1202
- enumerable: false,
1203
- value: true
1204
- });
1205
- //3. Watch
1206
- let watchMap = DefinitionWatchMap.get(this.constructor.name) ?? DefinitionWatchMap.get(_getSuper(this.constructor).name);
1207
- if (watchMap) {
1208
- this._watchUpdateMap = {};
1209
- this._watchDeepUpdateMap = {};
1210
- this._watchKeys = [];
1211
- this._watchKeysDeep = [];
1212
- this._watchUpdateSetInNextTick = new Set();
1213
- this._watchUpdateArgsInNextTick = new Map();
1214
- this._watchKeysOnceMap = new Map();
1215
- each(watchMap, (watchList, k) => {
1216
- watchList.forEach(v => {
1217
- let { source, options, handler } = v;
1218
- let fn = handler;
1219
- let onceWatch = get(options, "once", false);
1220
- if (onceWatch) {
1221
- this._watchKeysOnceMap.set(k, false);
1222
- }
1223
- let deep = get(options, "deep", false);
1224
- this._watchKeys.push(k);
1225
- if (deep) {
1226
- this._watchDeepUpdateMap[k] = this._watchDeepUpdateMap[k] ?? new Set();
1227
- this._watchDeepUpdateMap[k].add(fn);
1228
- this._watchKeysDeep.push(k);
1229
- }
1230
- else {
1231
- this._watchUpdateMap[k] = this._watchUpdateMap[k] ?? new Set();
1232
- this._watchUpdateMap[k].add(fn);
1233
- }
1234
- let immediate = get(options, "immediate", false);
1235
- if (!immediate)
1236
- return;
1237
- let nv = get(this, source);
1238
- fn.call(this, nv, undefined, source);
1239
- if (onceWatch) {
1240
- this._watchKeysOnceMap.set(k, true);
1241
- }
1242
- });
1243
- });
1244
- }
1245
- //4. Computed
1246
- let computedMap = DefinitionComputedMap.get(this.constructor.name) ?? DefinitionComputedMap.get(_getSuper(this.constructor).name);
1247
- if (computedMap) {
1248
- this._computedUpdateDeps = new Map();
1249
- this._computedUpdateSetInNextTick = new Set();
1250
- each(computedMap, (getter, propKey) => {
1251
- set(getter, 'key', propKey);
1252
- Collector.start();
1253
- this.#data[propKey] = getter.call(this);
1254
- Collector.end();
1255
- let computedDeps = Collector.popVarPathList();
1256
- computedDeps.forEach(dep => {
1257
- let list = this._computedUpdateDeps.get(dep);
1258
- if (!list) {
1259
- list = new Set();
1260
- this._computedUpdateDeps.set(dep, list);
1261
- }
1262
- list.add(getter);
1263
- });
1264
- Reflect.defineProperty(this, propKey, {
1265
- get() {
1266
- let v = Reflect.get(thisRef.deref().#data, propKey);
1267
- if (Collector.__collecting) {
1268
- Collector.__varPathList.push(propKey);
1269
- }
1270
- return v;
1271
- }
1272
- });
1273
- });
1274
- }
1275
- //5. Render
1276
- Collector.start();
1277
- let tmpl = this.render();
1278
- Collector.end();
1279
- let nodes;
1280
- if (tmpl === null) {
1281
- this.#renderRoots = [];
1282
- this.#renderRoot = undefined;
1283
- }
1284
- else {
1285
- /////////////////////////////////////////////////// shadow dom
1286
- this.#shadow = this.attachShadow({
1287
- mode: "open"
1288
- });
1289
- let viewDeps = Collector.popVarPathList();
1290
- this.__updateViewDeps = viewDeps;
1291
- this.#shadow.adoptedStyleSheets = [...DefaultCss, ...(ComponentStaticStyleMap.get(this) ?? [])];
1292
- nodes = buildView(tmpl, this);
1293
- if (nodes) {
1294
- this.#renderRoots = filter(nodes, (n) => n.nodeType === Node.ELEMENT_NODE).map(n => new WeakRef(n));
1295
- this.#renderRoot = new WeakRef(nodes[0]);
1296
- }
1297
- }
1298
- this.#inited = true;
1299
- /////////////////////////////////////////////////// slots
1300
- this.#updateSlotsAry();
1301
- //slot hook
1302
- each(this.#slotHooks, (v, k) => {
1303
- this.#updateSlot(k);
1304
- });
1305
- const that = this;
1306
- let ary = DefinitionDecoratorMap.get(this.constructor.name) ?? DefinitionDecoratorMap.get(_getSuper(this.constructor).name);
1307
- ary && ary.sort((a, b) => b.priority - a.priority).forEach(dw => {
1308
- dw.beforeMount(this, (key, value) => {
1309
- that.#data[key] = value;
1310
- return that.#data[key];
1311
- });
1312
- });
1313
- this.beforeMount();
1314
- setTimeout(() => {
1315
- if (this.isDestroyed) {
1316
- console.debug('Component is destroyed before mount', this.tagName);
1317
- return;
1318
- }
1319
- this.#mounted = true;
1320
- if (this.#shadow) {
1321
- //instance dynamic style
1322
- let cssAry = [];
1323
- Collector.start();
1324
- let cssTmpls = this.styles;
1325
- Collector.end();
1326
- this.__updateCssDeps = Collector.popVarPathList();
1327
- cssTmpls.forEach(cssTmpl => {
1328
- let cssss = new CSSStyleSheet();
1329
- cssAry.push(cssss);
1330
- let css = cssTmpl.getCss(this);
1331
- if (isBlank(css))
1332
- return;
1333
- cssss.replaceSync(css);
1334
- });
1335
- if (cssAry.length > 0) {
1336
- this.__cssSheets = cssAry;
1337
- this.#shadow.adoptedStyleSheets = [...this.#shadow.adoptedStyleSheets, ...cssAry];
1338
- }
1339
- }
1340
- if (nodes)
1341
- this.#shadow.append(...nodes);
1342
- ary && ary.forEach(dw => {
1343
- dw.mounted(this, (key, value) => {
1344
- that.#data[key] = value;
1345
- return that.#data[key];
1346
- });
1347
- });
1348
- if (this.#updateNextImmediatelyQ) {
1349
- this.#updateNextImmediatelyQ.forEach((cbk) => Queue.pushNext(cbk));
1350
- }
1351
- if (this.#updateViewImmediately) {
1352
- Queue.pushNext(this.#updatedD);
1353
- }
1354
- this.__bindEvents();
1355
- this.mounted();
1356
- }, 0);
1357
- }
1358
- propsReady(props) { }
1359
- render() {
1360
- return null;
1361
- }
1362
- beforeMount() { }
1363
- mounted() { }
1364
- __onSlotChangeHook(e) {
1365
- let t = e.currentTarget;
1366
- let name = '';
1367
- each(this.#slotsEl, (el, n) => {
1368
- if (el === t) {
1369
- name = n;
1370
- return false;
1371
- }
1372
- });
1373
- if (this.#inited)
1374
- this.#onSlotChange(t, name === SLOT_NAME_DEFAULT ? '' : name);
1375
- }
1376
- #onSlotChange(slot, name) {
1377
- //1. 更新 _slotsPropMap & slots
1378
- this.#updateSlotsAry();
1379
- //2. 设置attrs
1380
- let props = get(this.#slotPropsMap[name], 'props');
1381
- if (props) {
1382
- each(this.slots, (nodeAry, k) => {
1383
- nodeAry.filter(node => node.nodeType === Node.ELEMENT_NODE).forEach((node) => {
1384
- if (node instanceof CompElem) {
1385
- node._updateProps(props);
1386
- return;
1387
- }
1388
- each(props, (v, k) => {
1389
- if (node instanceof HTMLSlotElement) {
1390
- let compOfSlot = SlotCompMap.get(node);
1391
- if (compOfSlot) {
1392
- let sname = node.name || SLOT_NAME_DEFAULT;
1393
- let slotMap = compOfSlot.#slotPropsMap[sname];
1394
- if (!slotMap) {
1395
- slotMap = compOfSlot.#slotPropsMap[sname] = { props: {} };
1396
- }
1397
- if (!slotMap.props) {
1398
- slotMap.props = {};
1399
- }
1400
- slotMap.props[k] = v;
1401
- compOfSlot.#onSlotChange(node, sname);
1402
- }
1403
- }
1404
- else {
1405
- node.setAttribute(k, v);
1406
- }
1407
- });
1408
- });
1409
- });
1410
- }
1411
- //3. callback
1412
- this.slotChange(slot, name);
1413
- }
1414
- slotChange(slot, name) { }
1415
- attributeChangedCallback(attributeName, oldValue, newValue) {
1416
- if (!this.#inited)
1417
- return;
1418
- if (Object.is(newValue, oldValue))
1419
- return;
1420
- let propName = camelCase(attributeName);
1421
- let propDef = DefinitionPropMap.get(this.constructor.name)[propName];
1422
- if (isBooleanProp(propDef.type)) {
1423
- let v = isNull(newValue) ? false : getBooleanValue(newValue);
1424
- if (get(this, propName) === v)
1425
- return;
1426
- }
1427
- this.__attrChanged(attributeName, oldValue, newValue);
1428
- }
1429
- //********************************** 更新
1430
- /**
1431
- * 是否需要更新,可获取变更属性
1432
- * 返回true时更新
1433
- */
1434
- shouldUpdate(changed) {
1435
- return true;
1436
- }
1437
- /**
1438
- * 1. 调用render
1439
- * 2. 更新@query/all
1440
- * 3. 更新ref
1441
- * 4. 更新prop到attr的映射
1442
- * @param changed
1443
- */
1444
- updated(changed) { }
1445
- #rootEvs = {};
1446
- #nodeEvs = {};
1447
- /**
1448
- * 由监控变量调用
1449
- * @param stateKey
1450
- * @param ov
1451
- * @param rootStateKey 如果是对象内部属性变更,会返回根属性名
1452
- * @returns
1453
- */
1454
- _notify(ov, chain, subNewValue, subOldValue) {
1455
- let varPath = [];
1456
- for (let i = 0; i < chain.length; i++) {
1457
- const seg = chain[i];
1458
- varPath.push(seg);
1459
- let v = get(this, varPath);
1460
- let pathStr = _toUpdatePath(varPath);
1461
- this.#updateSources[pathStr] = { value: v, chain: pathStr === PROP_NAME_SLOTS ? [PROP_NAME_SLOTS] : varPath, oldValue: ov, end: varPath.length === chain.length, subNewValue, subOldValue };
1462
- }
1463
- if (!this.isMounted) {
1464
- console.debug('target update...', this.tagName);
1465
- this.#updateViewImmediately = true;
1466
- return;
1467
- }
1468
- Queue.pushNext(this.#updatedD);
1469
- }
1470
- _requestWatchUpdate(newValue, oldValue, fullPath, rootObjNew, rootObjOld) {
1471
- this._watchKeys?.forEach(wk => {
1472
- if (fullPath === wk ||
1473
- (startsWith(wk, fullPath + '.') && !Object.is(get(this._getPrivateData(), wk), get(newValue, wk))) ||
1474
- (startsWith(fullPath, wk + '.') && this._watchKeysDeep.includes(wk) && !Object.is(get(this._getPrivateData(), wk), get(newValue, wk)))) {
1475
- concat(toArray(this._watchUpdateMap[wk]), toArray(this._watchDeepUpdateMap[wk])).forEach(fn => {
1476
- if (!fn)
1477
- return;
1478
- if (this._watchKeysOnceMap.get(wk) === true)
1479
- return;
1480
- this._watchUpdateArgsInNextTick.set(fn, {
1481
- newValue, oldValue, chain: fullPath.split('.'), rootObjNew, rootObjOld, fullMatch: wk === fullPath
1482
- });
1483
- this._watchUpdateSetInNextTick.add(fn);
1484
- if (this._watchKeysOnceMap.has(wk))
1485
- this._watchKeysOnceMap.set(wk, true);
1486
- });
1487
- }
1488
- });
1489
- }
1490
- _requestComputedUpdate(fullPath) {
1491
- if (this._computedUpdateDeps?.has(fullPath)) {
1492
- this._computedUpdateDeps.get(fullPath)?.forEach(fn => {
1493
- this._computedUpdateSetInNextTick.add(fn);
1494
- });
1495
- }
1496
- }
1497
- #update() {
1498
- if (size(this.#updateSources) < 1)
1499
- return;
1500
- if (!this.isMounted)
1501
- return;
1502
- const changed = this.#updateSources;
1503
- this.#updateSources = {};
1504
- let toBreak = !this.shouldUpdate(changed);
1505
- if (toBreak)
1506
- return;
1507
- //update decorators
1508
- let ary = DefinitionDecoratorMap.get(this.constructor.name) ?? DefinitionDecoratorMap.get(_getSuper(this.constructor).name);
1509
- ary && ary.sort((a, b) => b.priority - a.priority).forEach(dw => {
1510
- dw.updated(this, changed);
1511
- });
1512
- //1. filter update point
1513
- let toUpdateCss = false;
1514
- let toUpdateView = false;
1515
- let toUpdateUps = new Set();
1516
- each(changed, (x, k) => {
1517
- if (this.__updateCssDeps?.includes(k)) {
1518
- toUpdateCss = true;
1519
- }
1520
- if (!toUpdateView && this.__updateViewDeps?.includes(k)) {
1521
- toUpdateView = true;
1522
- }
1523
- if (this.__updateSubViewDeps?.has(k)) {
1524
- let ups = this.__updateSubViewDeps.get(k);
1525
- if (ups)
1526
- toUpdateUps = toUpdateUps.union(ups);
1527
- }
1528
- });
1529
- //update watch
1530
- this._watchUpdateSetInNextTick?.forEach((fn) => {
1531
- let { newValue, oldValue, chain, rootObjNew, rootObjOld, fullMatch } = this._watchUpdateArgsInNextTick.get(fn);
1532
- let nv = fullMatch ? newValue : rootObjNew;
1533
- let ov = fullMatch ? oldValue : rootObjOld;
1534
- fn.call(this, nv, ov, chain, newValue, oldValue);
1535
- });
1536
- this._watchUpdateSetInNextTick?.clear();
1537
- this._watchUpdateArgsInNextTick?.clear();
1538
- // update computed
1539
- this._computedUpdateSetInNextTick?.forEach(fn => {
1540
- let k = get(fn, 'key');
1541
- let oldValue = this.#data[k];
1542
- let newValue = fn.call(this);
1543
- if (!isObject(newValue) && newValue === oldValue)
1544
- return;
1545
- this.#data[k] = newValue;
1546
- this._notify(oldValue, [k]);
1547
- });
1548
- this._computedUpdateSetInNextTick?.clear();
1549
- //2. update view
1550
- if (this.#renderRoot?.deref()) {
1551
- if (toUpdateView) {
1552
- console.debug('update view....', this.constructor.name);
1553
- updateView(this.render(), this, this.__updateTree);
1554
- }
1555
- if (size(toUpdateUps) > 0) {
1556
- toUpdateUps.forEach(up => {
1557
- updateSubScopeView(up, this, undefined);
1558
- });
1559
- }
1560
- }
1561
- //update slot view
1562
- this.#updateSlots.forEach((v) => {
1563
- this.#updateSlot(v);
1564
- });
1565
- //update dcss
1566
- if (toUpdateCss) {
1567
- this.#updateCss();
1568
- }
1569
- this.updated(changed);
1570
- }
1571
- /**
1572
- * 1. 初始props中并未包含的属性,可从attributes取,且定义类型不是string时自动转换
1573
- * 2. 如果attributes中也未出现且必填报错
1574
- * 3. 否则设置默认值
1575
- * @returns 非props的attr集合
1576
- */
1577
- #initProps() {
1578
- let propDefs = DefinitionPropMap.get(this.constructor.name) ?? DefinitionPropMap.get(_getSuper(this.constructor).name);
1579
- let attrs = this.attributes;
1580
- let tagName = this.tagName;
1581
- let parentProps = this.#props;
1582
- let filterAttrs = {};
1583
- each(attrs, ({ name, value }) => {
1584
- if (name[0] === ATTR_PREFIX_EVENT ||
1585
- name[0] === ATTR_PREFIX_PROP ||
1586
- name[0] === ATTR_PREFIX_BOOLEAN ||
1587
- name === ATTR_REF || name === 'slot')
1588
- return;
1589
- let camelName = camelCase(name);
1590
- if (propDefs && !propDefs[camelName]) {
1591
- filterAttrs[name] = value;
1592
- }
1593
- });
1594
- this.#attrs = this.#attrs ? assign(this.#attrs, filterAttrs) : filterAttrs;
1595
- let rs = {};
1596
- if (!propDefs)
1597
- return Object.seal(rs);
1598
- let keys = Object.keys(propDefs);
1599
- let size = keys.length;
1600
- for (let i = 0; i < size; i++) {
1601
- const key = keys[i];
1602
- const kbKey = kebabCase(key);
1603
- const hasAttr = this.hasAttribute(kbKey);
1604
- let propDef = propDefs[key];
1605
- let isInited = has(parentProps, key);
1606
- let defaultVal = get(this, key);
1607
- if (!('_defaultValue' in propDef)) {
1608
- //在构造结束后
1609
- propDef._defaultValue = defaultVal;
1610
- if (!propDef.type) {
1611
- if (isUndefined(defaultVal)) {
1612
- showTagError(tagName, "Prop '" + key + "' has neither propType nor defaultValue be used for type inference");
1613
- }
1614
- let type = typeof defaultVal;
1615
- if (isArray(defaultVal))
1616
- type = 'array';
1617
- let inferredType = PropTypeMap[type];
1618
- propDef.type = inferredType;
1619
- }
1620
- }
1621
- if (propDef.hasChanged) {
1622
- if (!this._hasChangedPropOrStateMap) {
1623
- this._hasChangedPropOrStateMap = new Map();
1624
- }
1625
- this._hasChangedPropOrStateMap.set(key, propDef.hasChanged);
1626
- }
1627
- if (propDef.sync) {
1628
- if (!this._hasSyncPropSet) {
1629
- this._hasSyncPropSet = new Set();
1630
- }
1631
- this._hasSyncPropSet.add(key);
1632
- }
1633
- let val = undefined;
1634
- if (isInited) {
1635
- val = isNil(parentProps[key]) ? defaultVal : parentProps[key];
1636
- }
1637
- else {
1638
- val = defaultVal;
1639
- let attr = attrs.getNamedItem(kbKey) ||
1640
- attrs.getNamedItem(ATTR_PREFIX_PROP + kbKey);
1641
- if (attr) {
1642
- isInited = true;
1643
- val = attr.value;
1644
- }
1645
- }
1646
- //required check
1647
- let isRequired = propDef.required;
1648
- if (isRequired && !isInited) {
1649
- showTagError(tagName, "Prop '" + key + "' is required");
1650
- break;
1651
- }
1652
- val = this.#propTypeCheck(propDefs, key, val, hasAttr);
1653
- let getter = get(propDefs, [key, 'getter']);
1654
- if (getter)
1655
- getter = bind$1(getter, this);
1656
- let setter = get(propDefs, [key, 'setter']);
1657
- if (setter)
1658
- setter = bind$1(setter, this);
1659
- if (getter || setter) {
1660
- Reflect.defineProperty(this.#data, key, {
1661
- set: setter || function (v) { },
1662
- get: getter
1663
- });
1664
- }
1665
- if (propDef.attribute && isDefined(val) && !isObject(val)) {
1666
- this.#updateAttribute(propDef, key, val);
1667
- }
1668
- this.#data[key] = val;
1669
- rs[key] = val;
1670
- }
1671
- return Object.seal(rs);
1672
- }
1673
- #updateAttribute(propDef, key, val) {
1674
- let k = kebabCase(key);
1675
- let v = trim(val);
1676
- if (isBooleanProp(propDef.type)) {
1677
- v = getBooleanValue(val);
1678
- if (isBoolean(v)) {
1679
- if (v && !this.hasAttribute(k)) {
1680
- this.toggleAttribute(k, true);
1681
- }
1682
- else if (!v && this.hasAttribute(k)) {
1683
- this.toggleAttribute(k, false);
1684
- }
1685
- }
1686
- else if (this.getAttribute(k) !== v) {
1687
- this.setAttribute(k, v);
1688
- }
1689
- }
1690
- else if (this.getAttribute(k) !== v) {
1691
- this.setAttribute(k, v);
1692
- }
1693
- }
1694
- #convertValue(v, types) {
1695
- let val = v;
1696
- try {
1697
- for (let i = 0; i < types.length; i++) {
1698
- const t = types[i];
1699
- if (t === Boolean) {
1700
- val = getBooleanValue(v);
1701
- }
1702
- else if (t === Number) {
1703
- val = Number(v);
1704
- }
1705
- else if (t === String) {
1706
- val = String(v);
1707
- }
1708
- else if (t === Object || t === Array) {
1709
- val = parseJSON(v);
1710
- }
1711
- else if (t === Date) {
1712
- val = new Date(v);
1713
- }
1714
- else {
1715
- val = new t(v);
1716
- }
1717
- }
1718
- }
1719
- catch (error) {
1720
- showTagError(this.tagName, `Convert attribute error with ` + v);
1721
- }
1722
- return val;
1723
- }
1724
- //属性值检测
1725
- #propTypeCheck(propDefs, propKey, newValue, hasAttr) {
1726
- let propDef = propDefs[propKey];
1727
- if (!propDef)
1728
- return newValue;
1729
- let validator = propDef.isValid;
1730
- let expectType = propDef.type;
1731
- let expectTypeAry = isArray(expectType) ? expectType : [expectType];
1732
- let typeConverter = propDef.converter;
1733
- let val = newValue;
1734
- if (!some(expectTypeAry, (et) => et === String) && isString(val) && !isNull(val)) {
1735
- try {
1736
- val = typeConverter ? typeConverter(val) : this.#convertValue(val, expectTypeAry);
1737
- }
1738
- catch (error) {
1739
- showTagError(this.tagName, `Convert attribute '${propKey}' error with ` + val);
1740
- }
1741
- } //endif
1742
- //extra work
1743
- for (let i = 0; i < expectTypeAry.length; i++) {
1744
- const et = expectTypeAry[i];
1745
- if (et.name === 'Boolean' && hasAttr) {
1746
- val = getBooleanValue(val);
1747
- }
1748
- }
1749
- if (isNil(val)) {
1750
- return val;
1751
- }
1752
- let realType = typeof val;
1753
- let matched = isDefined(val) ? false : true;
1754
- for (let i = 0; i < expectTypeAry.length; i++) {
1755
- const et = expectTypeAry[i];
1756
- if (
1757
- //base form
1758
- test(realType, et.name, "i") ||
1759
- //object form
1760
- val instanceof et || (Object.prototype.toString.call(val) === Object.prototype.toString.call(et.prototype))) {
1761
- matched = true;
1762
- break;
1763
- }
1764
- }
1765
- if (!matched) {
1766
- showTagError(this.tagName, `Invalid prop '${propKey}'. expected '${expectTypeAry.map((t) => t.name || t)}' but got '${realType}'`);
1767
- }
1768
- if (validator) {
1769
- if (!validator.call(this, val, this.#data)) {
1770
- showTagError(this.tagName, `Invalid prop '${propKey}'. IsValid() check failed`);
1771
- }
1772
- }
1773
- return val;
1774
- }
1775
- #initStates() {
1776
- let stateDefs = DefinitionStateMap.get(this.constructor.name) ?? DefinitionStateMap.get(_getSuper(this.constructor).name);
1777
- if (stateDefs)
1778
- each(stateDefs, (def, key) => {
1779
- let stateDef = stateDefs[key];
1780
- let val = get(this, key);
1781
- if (stateDef) {
1782
- let propName = stateDef.prop;
1783
- val = propName ? cloneDeep(this.#data[propName]) : get(this, key);
1784
- }
1785
- if (stateDef.hasChanged) {
1786
- if (!this._hasChangedPropOrStateMap) {
1787
- this._hasChangedPropOrStateMap = new Map();
1788
- }
1789
- this._hasChangedPropOrStateMap.set(key, stateDef.hasChanged);
1790
- }
1791
- if (stateDef.shallow) {
1792
- if (!this._hasShallowStateSet) {
1793
- this._hasShallowStateSet = new Set();
1794
- }
1795
- this._hasShallowStateSet.add(key);
1796
- }
1797
- this.#data[key] = val;
1798
- });
1799
- }
1800
- /**
1801
- * 由外部调用,在初始化及更新时。
1802
- * @param props
1803
- * @param attrs
1804
- */
1805
- #propsReady = debounce(this.propsReady, 100);
1806
- //todo 这里需要直接修改prop
1807
- _updateProps(props) {
1808
- let propDefs = DefinitionPropMap.get(this.constructor.name);
1809
- if (!propDefs)
1810
- return;
1811
- let need2UpdateAttrs = [];
1812
- //存在attrs表示已初始化完成
1813
- each(props, (v, k) => {
1814
- let ck = camelCase(k);
1815
- let propDef = propDefs[ck];
1816
- if (!propDef)
1817
- return;
1818
- v = this.#propTypeCheck(propDefs, ck, v);
1819
- if (propDef.attribute && isDefined(v) && !isObject(v)) {
1820
- need2UpdateAttrs.push([propDef, ck, v]);
1821
- }
1822
- set(this, ck, v);
1823
- });
1824
- assign(this.#props, props);
1825
- need2UpdateAttrs.forEach(([propDef, key, v]) => {
1826
- this.#updateAttribute(propDef, key, v);
1827
- });
1828
- if (this.#props)
1829
- this.#propsReady(this.#props);
1830
- }
1831
- _wrapperProp = {};
1832
- _initProps(props, attrs) {
1833
- this.#props = merge(this.#props || {}, props);
1834
- this.#attrs = merge(this.#attrs || {}, attrs);
1835
- each(props, (v, k) => {
1836
- if (isObject(v)) {
1837
- let fromPath = OBJECT_VAR_PATH.get(v);
1838
- if (fromPath) {
1839
- let propPath = fromPath.join(PATH_SEPARATOR);
1840
- this._wrapperProp[propPath] = k;
1841
- let parentStateDefs = this.wrapperComponent ? DefinitionStateMap.get(this.wrapperComponent?.constructor.name) : null;
1842
- let parentStateKey = fromPath[0];
1843
- if (parentStateDefs && parentStateDefs[parentStateKey]) {
1844
- let propDefs = DefinitionPropMap.get(this.constructor.name);
1845
- set(propDefs, [k, 'shallow'], parentStateDefs[parentStateKey].shallow);
1846
- }
1847
- }
1848
- }
1849
- });
1850
- }
1851
- /**
1852
- * 绑定slot标签,render时调用
1853
- */
1854
- _bindSlot(slot, name, props) {
1855
- //1. 设置map
1856
- if (!this.#slotsEl[name]) {
1857
- this.#slotsEl[name] = slot;
1858
- SlotCompMap.set(slot, this);
1859
- }
1860
- this.addEvent(slot, 'slotchange', this.__onSlotChangeHook);
1861
- //3. 保存参数
1862
- if (!isEmpty(props)) {
1863
- let slotMap = this.#slotPropsMap[name];
1864
- if (!slotMap) {
1865
- slotMap = this.#slotPropsMap[name] = {};
1866
- }
1867
- slotMap.props = props;
1868
- }
1869
- }
1870
- _bindSlotHook(name, hook) {
1871
- this.#slotHooks[name] = hook;
1872
- }
1873
- //slot变量变动时触发
1874
- #updateSlots = new Set();
1875
- _updateSlot(name, propName, value) {
1876
- let slotEl = this.#slotsEl[name];
1877
- let hook = this.#slotHooks[name];
1878
- if (!hook && !slotEl)
1879
- return;
1880
- let slotMap = this.#slotPropsMap[name];
1881
- if (propName) {
1882
- if (!slotMap.props) {
1883
- slotMap.props = {};
1884
- }
1885
- slotMap.props[propName] = value;
1886
- }
1887
- if (!!hook) {
1888
- this.#updateSlots.add(name);
1889
- }
1890
- else {
1891
- //update nodes
1892
- let els = slotEl.assignedElements({ flatten: true });
1893
- for (let i = 0; i < els.length; i++) {
1894
- const el = els[i];
1895
- el.setAttribute(propName, value + '');
1896
- }
1897
- }
1898
- }
1899
- #updateSlotsAry() {
1900
- if (!this.#renderRoot)
1901
- return;
1902
- let slotKeys = keys(this.#slotsEl);
1903
- if (isEmpty(slotKeys))
1904
- return;
1905
- const cs = flatMap(this.childNodes, node => {
1906
- if (node.nodeType === Node.COMMENT_NODE)
1907
- return [];
1908
- if (node instanceof HTMLSlotElement)
1909
- return node.assignedNodes({ flatten: true });
1910
- return node;
1911
- });
1912
- let groups = groupBy(cs, node => {
1913
- if (node.nodeType === Node.TEXT_NODE && slotKeys.includes(SLOT_NAME_DEFAULT))
1914
- return SLOT_NAME_DEFAULT;
1915
- if (node instanceof Element) {
1916
- let sName = node.getAttribute('slot') || SLOT_NAME_DEFAULT;
1917
- if (slotKeys.includes(sName))
1918
- return sName;
1919
- }
1920
- });
1921
- if (isEmpty(groups)) {
1922
- this.slots = {};
1923
- return;
1924
- }
1925
- each(groups, (nodeAry, k) => {
1926
- if (!k)
1927
- return;
1928
- while (nodeAry.length > 0) {
1929
- let node = nodeAry[0];
1930
- if ((node.nodeType === Node.TEXT_NODE && isBlank(node.textContent)) ||
1931
- (node instanceof HTMLSlotElement && isEmpty(node.assignedNodes({ flatten: true })))) {
1932
- nodeAry.shift();
1933
- continue;
1934
- }
1935
- break;
1936
- }
1937
- while (nodeAry.length > 0) {
1938
- let node = last(nodeAry);
1939
- if ((node.nodeType === Node.TEXT_NODE && isBlank(node.textContent)) ||
1940
- (node instanceof HTMLSlotElement && isEmpty(node.assignedNodes({ flatten: true })))) {
1941
- nodeAry.pop();
1942
- continue;
1943
- }
1944
- break;
1945
- }
1946
- });
1947
- let rs = {};
1948
- each(groups, (v, k) => {
1949
- if (!isEmpty(v)) {
1950
- rs[k] = v;
1951
- }
1952
- });
1953
- this.slots = rs;
1954
- }
1955
- #updateSlot(name) {
1956
- let hook = this.#slotHooks[name];
1957
- if (!hook)
1958
- return;
1959
- let slotMap = this.#slotPropsMap[name];
1960
- if (!this.#data.slots)
1961
- return;
1962
- let slot = this.#data.slots[name];
1963
- //slot not ready yet
1964
- //1. 可能是if/each等指令还未插入
1965
- if (!slot)
1966
- return;
1967
- //组件通知渲染异步指令
1968
- this.renderAsync(hook, get(slotMap, 'props'));
1969
- const rc = this._asyncDirectives.get(hook);
1970
- //todo 如果要做成通用异步指令,元素必须插入到指令挂载的位置,并且slot的插入节点还要去掉注释
1971
- let nodes = rc?.buildView(hook(get(slotMap, 'props')));
1972
- let nnodes = reject(toArray(nodes), n => n.nodeType === Node.COMMENT_NODE);
1973
- if (nnodes) {
1974
- let slottedNodes = this.#slotNodes[name];
1975
- if (!isEmpty(slottedNodes)) {
1976
- for (let i = 0; i < slottedNodes.length; i++) {
1977
- const n = slottedNodes[i];
1978
- n.parentNode?.removeChild(n);
1979
- }
1980
- }
1981
- this.#slotNodes[name] = nnodes;
1982
- this.append(...nnodes);
1983
- this.#updateSlots.clear();
1984
- }
1985
- }
1986
- _asyncDirectives = new WeakMap();
1987
- renderAsync(cbk, ...args) {
1988
- }
1989
- #updateCss() {
1990
- let cssTmpls = this.styles;
1991
- cssTmpls.forEach((cssTmpl, i) => {
1992
- let cssss = this.__cssSheets[i];
1993
- let css = cssTmpl.getCss(this);
1994
- cssss.replaceSync(css);
1995
- });
1996
- }
1997
- __attrChanged(name, oldValue, newValue) {
1998
- if (!this.#inited)
1999
- return;
2000
- let observedAttrs = _getObservedAttrs(this.constructor);
2001
- if (observedAttrs.has(name)) {
2002
- let camelName = camelCase(name);
2003
- if (isNull(newValue)) {
2004
- let propDefs = DefinitionPropMap.get(this.constructor.name);
2005
- //使用默认值
2006
- if (propDefs)
2007
- newValue = propDefs[camelName]._defaultValue;
2008
- }
2009
- this._updateProps({ [camelName]: newValue });
2010
- }
2011
- }
2012
- _regWrapper(wrapperComponent) {
2013
- this.#wrapperComponent = new WeakRef(wrapperComponent);
2014
- }
2015
- _regSubViewDeps(props, up) {
2016
- if (!this.__updateSubViewDeps) {
2017
- this.__updateSubViewDeps = new Map();
2018
- }
2019
- props.forEach(prop => {
2020
- let depSet = this.__updateSubViewDeps.get(prop);
2021
- if (!depSet) {
2022
- depSet = new Set();
2023
- this.__updateSubViewDeps.set(prop, depSet);
2024
- }
2025
- depSet.add(up);
2026
- });
2027
- }
2028
- _getPrivateData() {
2029
- return this.#data;
2030
- }
2031
- ////////////////////----------------------------/////////////// APIs
2032
- /**
2033
- * 抛出自定义事件
2034
- * @param evName 事件名称
2035
- * @param args 自定义参数
2036
- */
2037
- emit(evName, arg = {}, options) {
2038
- if (options && options.event) {
2039
- arg.event = options.event;
2040
- }
2041
- arg.target = this;
2042
- this.dispatchEvent(new CustomEvent(evName, {
2043
- bubbles: get(options, "bubbles", false),
2044
- composed: get(options, "composed", false),
2045
- cancelable: true,
2046
- detail: arg,
2047
- }));
2048
- }
2049
- /**
2050
- * 在root上绑定事件
2051
- * @param evName
2052
- * @param hook
2053
- * @returns 函数钩子,用于卸载
2054
- */
2055
- on(evName, hook) {
2056
- if (!this.#rootEvs[evName]) {
2057
- this.#rootEvs[evName] = [];
2058
- }
2059
- let cbk = hook.bind(this);
2060
- this.#rootEvs[evName].push(cbk);
2061
- this.addEventListener(evName, cbk);
2062
- return cbk;
2063
- }
2064
- /**
2065
- * 从root上移除事件
2066
- * @param evName
2067
- * @param hook on函数返回的钩子,可选。为空时移除所有evName事件
2068
- */
2069
- off(evName, hook) {
2070
- if (hook) {
2071
- this.removeEventListener(evName, hook);
2072
- remove(this.#rootEvs[evName], cbk => cbk === hook);
2073
- }
2074
- else {
2075
- each(this.#rootEvs[evName], cbk => {
2076
- this.removeEventListener(evName, cbk);
2077
- });
2078
- this.#rootEvs[evName] = [];
2079
- }
2080
- }
2081
- addEvent(node, evName, hook) {
2082
- if (!this.#nodeEvs[evName]) {
2083
- this.#nodeEvs[evName] = [];
2084
- }
2085
- let cbk = hook.bind(this);
2086
- this.#nodeEvs[evName].push([cbk, new WeakRef(node)]);
2087
- node.addEventListener(evName, cbk);
2088
- return cbk;
2089
- }
2090
- removeEvent(node, evName, hook) {
2091
- if (hook) {
2092
- node.removeEventListener(evName, hook);
2093
- remove(this.#nodeEvs[evName], ([cbk]) => cbk === hook);
2094
- }
2095
- else {
2096
- each(this.#nodeEvs[evName], ([cbk]) => {
2097
- node.removeEventListener(evName, cbk);
2098
- });
2099
- this.#nodeEvs[evName] = [];
2100
- }
2101
- }
2102
- /**
2103
- * 下一帧执行
2104
- * @param cbk
2105
- */
2106
- nextTick(cbk) {
2107
- if (!this.isMounted) {
2108
- if (!this.#updateNextImmediatelyQ) {
2109
- this.#updateNextImmediatelyQ = [];
2110
- }
2111
- console.debug('target update...', this.tagName);
2112
- this.#updateNextImmediatelyQ.push(cbk);
2113
- return;
2114
- }
2115
- Queue.pushNext(cbk);
2116
- }
2117
- /**
2118
- * 强制更新一次视图
2119
- */
2120
- forceUpdate() {
2121
- each(this.#data, (v, k) => {
2122
- this.#updateSources[k] = {
2123
- value: undefined,
2124
- chain: undefined,
2125
- };
2126
- });
2127
- this.#update();
2128
- }
2129
- }
2130
-
2131
- /**
2132
- * 视图模板
2133
- * @author holyhigh2
2134
- */
2135
- class Template {
2136
- strings;
2137
- vars;
2138
- constructor(strings, vars) {
2139
- this.strings = concat(strings);
2140
- this.vars = vars;
2141
- }
2142
- //解析模板中的key
2143
- getKey() {
2144
- let vars = this.vars;
2145
- let k = '';
2146
- each(this.strings, (str, i) => {
2147
- if (EXP_KEY.test(str)) {
2148
- k = toString(vars[i]);
2149
- return false;
2150
- }
2151
- });
2152
- return k;
2153
- }
2154
- getKeys() {
2155
- let vars = this.vars;
2156
- let ks = [];
2157
- for (let i = 0; i < this.strings.length; i++) {
2158
- const str = this.strings[i];
2159
- if (EXP_KEY.test(str)) {
2160
- let k = toString(vars[i]);
2161
- ks.push(k);
2162
- }
2163
- }
2164
- if (isEmpty(ks)) {
2165
- vars.forEach(v => {
2166
- if (v instanceof Template) {
2167
- let k = v.getKey();
2168
- ks.push(k);
2169
- }
2170
- });
2171
- }
2172
- return ks;
2173
- }
2174
- /**
2175
- * 追加tmpl
2176
- * 交接处模板进行合并
2177
- * @param tmpl
2178
- */
2179
- append(tmpl) {
2180
- let lastStr = last(this.strings);
2181
- tmpl.strings.forEach((str, i) => {
2182
- if (i == 0) {
2183
- this.strings[this.strings.length - 1] = lastStr + str;
2184
- return;
2185
- }
2186
- this.strings.push(str);
2187
- });
2188
- this.vars = concat(this.vars, tmpl.vars);
2189
- return this;
2190
- }
2191
- /**
2192
- * 指定位置插入模板
2193
- * @param position 字符模板位置
2194
- * @param tmpl
2195
- * @returns
2196
- */
2197
- insert(position, tmpl) {
2198
- let firstStr = tmpl.strings.shift();
2199
- this.strings[position] += firstStr;
2200
- this.strings.splice(position + 1, 0, ...tmpl.strings);
2201
- this.vars.splice(position, 0, ...tmpl.vars);
2202
- return this;
2203
- }
2204
- getHTML(comp) {
2205
- let [html, vars] = buildHTML(comp, this);
2206
- let nodes = buildTmplate([], html, vars, comp);
2207
- return reduce(nodes, (a, v) => a + (v.outerHTML ?? ''), '');
2208
- }
2209
- /**
2210
- * 对var中的Template类型进行合并
2211
- */
2212
- flatVars(comp) {
2213
- let vars = concat(this.vars);
2214
- let l = this.strings.length - 1;
2215
- let varIndex = 0;
2216
- for (let i = 0; i <= l; i++) {
2217
- let val = get(vars, varIndex, '');
2218
- if (val instanceof Template && val.vars.length > 0) {
2219
- let [h, v] = buildHTML(comp, val);
2220
- val = h;
2221
- vars.splice(varIndex, 1, ...v);
2222
- varIndex += v.length - 1;
2223
- }
2224
- varIndex++;
2225
- }
2226
- return vars;
2227
- }
2228
- destroy() {
2229
- this.strings = this.vars = null;
2230
- }
2231
- }
2232
-
2233
- /**
2234
- * @author holyhigh2
2235
- */
2236
- /**
2237
- * 属性定义
2238
- */
2239
- var EnterPointType;
2240
- (function (EnterPointType) {
2241
- EnterPointType["ATTR"] = "attr";
2242
- EnterPointType["PROP"] = "prop";
2243
- EnterPointType["TEXT"] = "text";
2244
- EnterPointType["CLASS"] = "class";
2245
- EnterPointType["STYLE"] = "style";
2246
- EnterPointType["SLOT"] = "slot";
2247
- EnterPointType["TAG"] = "tag"; //在标签内但不是属性内
2248
- })(EnterPointType || (EnterPointType = {}));
2249
- var DirectiveUpdateTag;
2250
- (function (DirectiveUpdateTag) {
2251
- DirectiveUpdateTag["NONE"] = "NONE";
2252
- DirectiveUpdateTag["REMOVE"] = "REMOVE";
2253
- DirectiveUpdateTag["REPLACE"] = "REPLACE";
2254
- DirectiveUpdateTag["UPDATE"] = "UPDATE";
2255
- DirectiveUpdateTag["APPEND"] = "APPEND";
2256
- })(DirectiveUpdateTag || (DirectiveUpdateTag = {}));
2257
- /**
2258
- * 视图更新点
2259
- */
2260
- class UpdatePoint {
2261
- //在子视图中的平级key
2262
- key;
2263
- //表达式对应的vars位置
2264
- varIndex;
2265
- value;
2266
- //表达式所在节点,可能是元素/文本
2267
- node;
2268
- //如果在属性中,属性名
2269
- attrName;
2270
- //属性值模板
2271
- attrTmpl;
2272
- isText = false;
2273
- //是否模板
2274
- // isTmpl: boolean = false;
2275
- isDirective = false;
2276
- //是否组件
2277
- isComponent = false;
2278
- //是否组件属性
2279
- isProp = false;
2280
- //是否布尔属性
2281
- isToggleProp = false;
2282
- //是否被更新,对于 key,event,ref等属性不需要更新,仅用于占位
2283
- isPlaceholder;
2284
- __destroyed = false;
2285
- directiveOldValue;
2286
- children;
2287
- parent;
2288
- constructor(varIndex, node, attrName, attrTmpl) {
2289
- this.varIndex = varIndex;
2290
- if (node)
2291
- this.node = node;
2292
- if (attrName)
2293
- this.attrName = attrName;
2294
- if (attrTmpl) {
2295
- this.attrTmpl = attrTmpl;
2296
- }
2297
- }
2298
- static createFrom(up) {
2299
- let newUp = new UpdatePoint(up.varIndex, up.node, up.attrName, up.attrTmpl);
2300
- newUp.key = up.key;
2301
- newUp.value = up.value;
2302
- newUp.isText = up.isText;
2303
- newUp.isDirective = up.isDirective;
2304
- newUp.isComponent = up.isComponent;
2305
- newUp.isProp = up.isProp;
2306
- newUp.isToggleProp = up.isToggleProp;
2307
- newUp.isPlaceholder = up.isPlaceholder;
2308
- return newUp;
2309
- }
2310
- destroy(contextComponent) {
2311
- if (this.__destroyed)
2312
- return;
2313
- this.__destroyed = true;
2314
- let node = this.node;
2315
- let children = this.children;
2316
- let parent = this.parent;
2317
- //clean up
2318
- this.node = this.value = this.directiveOldValue = this.children = this.parent = null;
2319
- if (!node)
2320
- return;
2321
- //sup scope
2322
- parent?.children || contextComponent?.__updateTree;
2323
- // contextComponent?._unregDeps(node.deref()!)
2324
- //sub scopes
2325
- let updatePoints = children;
2326
- updatePoints?.forEach((up, i) => {
2327
- up.destroy(contextComponent);
2328
- });
2329
- if (node instanceof CompElem) {
2330
- node.destroy();
2331
- }
2332
- if (contextComponent) {
2333
- DomUtil.clear(node.deref(), contextComponent);
2334
- }
2335
- node.deref()?.remove();
2336
- }
2337
- insert(up) {
2338
- up.parent = this;
2339
- if (!this.children) {
2340
- this.children = [];
2341
- }
2342
- this.children.push(up);
2343
- }
2344
- }
2345
-
2346
- const DI_COMMENT_START_NODE_MAP = new WeakMap();
2347
- const TextOrSlotDirectiveExecutorMap = new Map();
2348
- var MovePosition;
2349
- (function (MovePosition) {
2350
- MovePosition["AFTER_BEGIN"] = "afterbegin";
2351
- })(MovePosition || (MovePosition = {}));
2352
- let newNodeMap = {};
2353
- function addNodes(adds, newTmpls, component, pointNode, newNodeMap, up) {
2354
- const combStrings = [];
2355
- const combVars = [];
2356
- const ks = [];
2357
- let addGroup = [];
2358
- let lastKey;
2359
- adds.forEach(add => {
2360
- let lastAdd = last(addGroup);
2361
- if (lastAdd) {
2362
- if (lastKey === add.prevNode) {
2363
- if (!lastAdd.group) {
2364
- lastAdd.group = [lastKey];
2365
- }
2366
- lastAdd.group.push(add.newkey);
2367
- }
2368
- else {
2369
- addGroup.push(add);
2370
- }
2371
- }
2372
- else {
2373
- addGroup.push(add);
2374
- }
2375
- lastKey = add.newkey;
2376
- let k = add.newkey;
2377
- ks.push(k);
2378
- combStrings.push('');
2379
- combVars.push(newTmpls[k]);
2380
- });
2381
- combStrings.push('');
2382
- let tmpl = new Template(combStrings, combVars);
2383
- let nodes = buildSubView(pointNode, tmpl, component, up, true);
2384
- let kMap = new Map();
2385
- nodes.forEach((n) => {
2386
- const k = n.getAttribute('key');
2387
- if (ks.includes(k)) {
2388
- kMap.set(k, true);
2389
- newNodeMap[k] = n;
2390
- }
2391
- });
2392
- return addGroup;
2393
- }
2394
- function updateDirective(pointNode, newArgs, oldArgs, executor, renderComponent, slotComponent, varChain, up) {
2395
- let rs;
2396
- let isTextOrSlot = [EnterPointType.TEXT, EnterPointType.SLOT].includes(get(executor, '__scope', ''));
2397
- if (isTextOrSlot) {
2398
- Collector.start();
2399
- rs = executor(pointNode, newArgs, oldArgs, { renderComponent, slotComponent, varChain });
2400
- Collector.end(renderComponent, up);
2401
- }
2402
- else {
2403
- rs = executor(pointNode, newArgs, oldArgs, { renderComponent, slotComponent, varChain });
2404
- }
2405
- if (!rs)
2406
- return;
2407
- let [tag, tmpl] = rs;
2408
- if (tag === DirectiveUpdateTag.NONE)
2409
- return;
2410
- let startNode = DI_COMMENT_START_NODE_MAP.get(pointNode);
2411
- let nodes = DomUtil.getNodes(startNode, pointNode);
2412
- let updatePoints = up.children;
2413
- if (tag === DirectiveUpdateTag.REMOVE) {
2414
- for (let i = 0; i < nodes.length; i++) {
2415
- const n = nodes[i];
2416
- n.remove();
2417
- if (n instanceof CompElem) {
2418
- n.destroy();
2419
- }
2420
- }
2421
- updatePoints?.forEach((up, i) => {
2422
- up.destroy(renderComponent);
2423
- });
2424
- }
2425
- else if (tag === DirectiveUpdateTag.REPLACE) {
2426
- let newNodes = [];
2427
- for (let i = 0; i < nodes.length; i++) {
2428
- const n = nodes[i];
2429
- n.parentNode?.removeChild(n);
2430
- if (n instanceof CompElem) {
2431
- n.destroy();
2432
- }
2433
- }
2434
- updatePoints?.forEach((up, i) => {
2435
- up.destroy(renderComponent);
2436
- });
2437
- let nnodes = buildSubView(pointNode, tmpl, renderComponent, up, true);
2438
- newNodes = toArray(nnodes);
2439
- let fragment = document.createDocumentFragment();
2440
- fragment.append(...newNodes);
2441
- pointNode.parentNode.insertBefore(fragment, pointNode);
2442
- }
2443
- else if (tag === DirectiveUpdateTag.UPDATE) {
2444
- let newKeys = {};
2445
- let nodesToUpdate;
2446
- //原节点顺序
2447
- let oldSeq = [];
2448
- let newSeq = [];
2449
- if (!tmpl) {
2450
- tmpl = new Template([], []);
2451
- }
2452
- if (isEmpty(nodes)) {
2453
- let nodes = buildSubView(pointNode, tmpl, renderComponent, up, true);
2454
- startNode.after(...nodes);
2455
- return;
2456
- }
2457
- let newTmpls = {};
2458
- if (tmpl instanceof Template) {
2459
- tmpl.vars.forEach(v => {
2460
- if (v instanceof Template) {
2461
- const k = v.getKey();
2462
- newTmpls[k] = v;
2463
- newKeys[k] = true;
2464
- newSeq.push(k);
2465
- }
2466
- });
2467
- }
2468
- //UPDATE仅处理元素节点
2469
- nodes = filter(compact(nodes), n => n.nodeType === Node.ELEMENT_NODE);
2470
- nodesToUpdate = filter(compact(toArray(nodesToUpdate)), n => n.nodeType === Node.ELEMENT_NODE);
2471
- let oldNodeMap = {};
2472
- let dupKey = '';
2473
- let keyQ = {};
2474
- for (let i = 0; i < nodes.length; i++) {
2475
- const node = nodes[i];
2476
- let treeNode = node;
2477
- let k = treeNode.getAttribute("key");
2478
- if (isNil(k))
2479
- continue;
2480
- if (oldNodeMap[k]) {
2481
- dupKey = k;
2482
- break;
2483
- }
2484
- oldNodeMap[k] = treeNode;
2485
- oldSeq.push(k);
2486
- keyQ[k] = true;
2487
- }
2488
- if (dupKey) {
2489
- showError(`${camelCase(pointNode.nodeValue)} - duplicate key '${dupKey}'`);
2490
- return;
2491
- }
2492
- let updateQ = newKeys;
2493
- //compare
2494
- let adds = [];
2495
- let dels = [];
2496
- //计算del
2497
- each(keyQ, (v, k) => {
2498
- if (!updateQ[k]) {
2499
- dels.push(k);
2500
- delete keyQ[k];
2501
- remove(oldSeq, x => x === k);
2502
- }
2503
- });
2504
- //move
2505
- let moved = false;
2506
- if (!isEmpty(newSeq)) {
2507
- let lastMoveIndex = -1;
2508
- let lastGroup = [];
2509
- let moveQueue = [];
2510
- let edgeOffset = 0;
2511
- let i = 0;
2512
- for (; i < newSeq.length; i++) {
2513
- const nodeId = newSeq[i];
2514
- let oldI = oldSeq.findIndex(c => c === nodeId);
2515
- if (oldI < 0) {
2516
- let prevKey = newSeq[i - 1];
2517
- let prev = prevKey ? oldNodeMap[prevKey] || prevKey : startNode;
2518
- //add
2519
- adds.push({ prevNode: prev, newkey: nodeId });
2520
- edgeOffset++;
2521
- continue;
2522
- }
2523
- if (oldI > -1 && oldI !== (i - edgeOffset)) {
2524
- if (lastMoveIndex < 0 || Math.abs(lastMoveIndex - oldI) === 1) {
2525
- let lastEl = last(lastGroup);
2526
- lastGroup.push({ nodeId, targetId: i === 0 ? MovePosition.AFTER_BEGIN : (lastEl ? lastEl.nodeId : newSeq[i - 1]) });
2527
- }
2528
- else {
2529
- moveQueue.push({ moveGroup: lastGroup, moveIndex: i + lastGroup.length });
2530
- lastGroup = [];
2531
- lastGroup.push({ nodeId, targetId: newSeq[i - 1] });
2532
- }
2533
- lastMoveIndex = oldI;
2534
- }
2535
- }
2536
- if (lastGroup.length > 0) {
2537
- moveQueue.push({ moveGroup: lastGroup, moveIndex: i + lastGroup.length });
2538
- }
2539
- if (moveQueue.length > 0) {
2540
- moved = true;
2541
- let vals = moveQueue.sort((a, b) => a.moveGroup.length - b.moveGroup.length);
2542
- if (vals.length < 2) {
2543
- let { moveGroup } = vals[0];
2544
- if (moveGroup.length > 1) {
2545
- let lastTId = last(moveGroup).targetId;
2546
- if (moveGroup[moveGroup.length - 2].nodeId === lastTId) {
2547
- moveGroup = initial(moveGroup);
2548
- }
2549
- }
2550
- moveGroup.forEach(({ targetId, nodeId }) => {
2551
- let srcEl = oldNodeMap[nodeId];
2552
- let target;
2553
- if (targetId === MovePosition.AFTER_BEGIN) {
2554
- target = startNode;
2555
- target.after(srcEl);
2556
- }
2557
- else if (oldNodeMap[targetId]) {
2558
- target = oldNodeMap[targetId];
2559
- target.after(srcEl);
2560
- }
2561
- });
2562
- }
2563
- else {
2564
- let lastGroupIndex = last(vals).moveIndex;
2565
- if (Math.abs(vals[vals.length - 2].moveIndex - lastGroupIndex) === 1) {
2566
- vals = initial(vals);
2567
- }
2568
- vals.forEach(({ moveGroup }) => {
2569
- moveGroup.forEach(({ targetId, nodeId }) => {
2570
- let srcEl = oldNodeMap[nodeId];
2571
- let target;
2572
- if (targetId === MovePosition.AFTER_BEGIN) {
2573
- target = startNode;
2574
- target.after(srcEl);
2575
- }
2576
- else {
2577
- target = oldNodeMap[targetId];
2578
- target.after(srcEl);
2579
- }
2580
- });
2581
- });
2582
- }
2583
- } //endif
2584
- }
2585
- //del
2586
- dels.forEach(k => {
2587
- let treeNode = oldNodeMap[k];
2588
- if (treeNode && treeNode.parentNode) {
2589
- oldNodeMap[k] = null;
2590
- treeNode.remove();
2591
- let ups = remove(updatePoints, up => up.key == k);
2592
- ups.forEach(up => up.destroy(renderComponent));
2593
- }
2594
- });
2595
- //add
2596
- let addGroup;
2597
- if (adds.length > 0) {
2598
- addGroup = addNodes(adds, newTmpls, renderComponent, pointNode, newNodeMap, up);
2599
- addGroup.forEach((v, i) => {
2600
- let k = v.newkey;
2601
- let treeNode = newNodeMap[k];
2602
- let prevNode = v.prevNode;
2603
- if (v.group) {
2604
- let fragment = document.createDocumentFragment();
2605
- fragment.append(...map(v.group, (nk) => newNodeMap[nk]));
2606
- treeNode = fragment;
2607
- }
2608
- if (prevNode === pointNode) {
2609
- prevNode.before(treeNode);
2610
- }
2611
- else if (prevNode === startNode) {
2612
- prevNode.after(treeNode);
2613
- }
2614
- else if (typeof prevNode === 'string') {
2615
- newNodeMap[prevNode].after(treeNode);
2616
- }
2617
- else {
2618
- prevNode.after(treeNode);
2619
- }
2620
- });
2621
- //release
2622
- newNodeMap = null;
2623
- newNodeMap = {};
2624
- }
2625
- //合并
2626
- if (tmpl.vars[0] instanceof Template) {
2627
- let tStrAry = [];
2628
- let tVarAry = [];
2629
- each(tmpl.vars, v => {
2630
- tVarAry.push(...v.vars);
2631
- tStrAry.push(...map(v.vars, v => '1'));
2632
- });
2633
- tStrAry.push('1');
2634
- tmpl = new Template(tStrAry, tVarAry);
2635
- }
2636
- //移动顺序
2637
- if (moved || dels.length > 0 || addGroup) {
2638
- const upGroup = groupBy(updatePoints, up => up.key);
2639
- let movedUpAry = [];
2640
- let i = 0;
2641
- newSeq.forEach(nk => {
2642
- upGroup[nk] && upGroup[nk].forEach((up) => {
2643
- up.varIndex = i++;
2644
- movedUpAry.push(up);
2645
- });
2646
- });
2647
- let redundant = except(updatePoints, movedUpAry);
2648
- redundant.forEach(up => up.destroy(renderComponent));
2649
- up.children = movedUpAry;
2650
- }
2651
- updateSubScopeView(up, renderComponent, tmpl);
2652
- }
2653
- }
2654
- let DiSn = 0;
2655
- /**
2656
- * 返回指令调用函数
2657
- * @param di
2658
- * @returns
2659
- */
2660
- function directive(fn, scopes) {
2661
- let name = fn.name || ('Di-' + DiSn++);
2662
- let sym = Symbol.for(name);
2663
- return (...args) => {
2664
- let executor = fn(...args);
2665
- if (includes(scopes, EnterPointType.TEXT) || includes(scopes, EnterPointType.SLOT))
2666
- TextOrSlotDirectiveExecutorMap.set(name, executor);
2667
- set(executor, '__scope', scopes[0]);
2668
- return [sym, args, executor, (scopeType) => {
2669
- if (!isEmpty(scopes) && !test(scopes.join(','), scopeType)) {
2670
- showError(`Directive '${Symbol.keyFor(sym)}' is out of scopes, expect '${scopes.join(',')}' bug got '${scopeType}'`);
2671
- return;
2672
- }
2673
- }, Collector.popDirectiveQ()];
2674
- };
2675
- }
2676
-
2677
- const ATTR_PREFIX_EVENT = "@";
2678
- const ATTR_PREFIX_PROP = ".";
2679
- const ATTR_PREFIX_BOOLEAN = "?";
2680
- const ATTR_PREFIX_REF = "*";
2681
- const ATTR_PROP_DELIMITER = ":";
2682
- const ATTR_REF = "ref";
2683
- const ATTR_KEY = "key";
2684
- const EXP_TAG_CONVERT = /(<\/?)\s*([A-Z][A-Za-z0-9]*)([\s>])/gm;
2685
- const EXP_ATTR_CONVERT = /\s+([\.?@*])?((?:[a-zA-Z]*[A-Z][^\s<>="']+))(?=[\s=>])/gm;
2686
- const EXP_ATTR_CHECK = /[.?-a-z]+\s*=\s*(['"])\s*([^='"]*<\!--c_ui-pl_df-->){2,}.*?\1/ims;
2687
- const EXP_PLACEHOLDER = /<\s*[a-z0-9-]+([^>]*<\!--c_ui-pl_df-->)*[^>]*?(?<!-)>/imgs;
2688
- const SLOT_KEY_PROPS = 'slot-props';
2689
- const HTML_TMPL_CACHE = {};
2690
- /**
2691
- * 提供渲染函数相关操作
2692
- * @author holyhigh2
2693
- */
2694
- function buildHTML(component, tmpl) {
2695
- let html = "";
2696
- let vars = concat(tmpl.vars);
2697
- let l = tmpl.strings.length - 1;
2698
- let vl = tmpl.vars.length - 1;
2699
- let varIndex = 0;
2700
- for (let i = 0; i <= l; i++) {
2701
- const str = tmpl.strings[i];
2702
- let val = get(vars, varIndex, '');
2703
- if (val instanceof Template) {
2704
- let [h, v] = buildHTML(component, val);
2705
- val = h;
2706
- vars.splice(varIndex, 1, ...v);
2707
- varIndex += v.length - 1;
2708
- }
2709
- else {
2710
- val = i > vl ? "" : PLACEHOLDER;
2711
- }
2712
- varIndex++;
2713
- html = html + str + val;
2714
- }
2715
- {
2716
- //attr check
2717
- let rs = html.match(EXP_ATTR_CHECK);
2718
- if (rs) {
2719
- let errorMsg = replaceAll(rs[0], PLACEHOLDER, '${...}');
2720
- showError(`Parse error: attribute value can be set only one interpolation —— \n ${errorMsg}`);
2721
- return ['', vars];
2722
- }
2723
- }
2724
- let i = 0;
2725
- html = html.replace(EXP_PLACEHOLDER, (a, b) => {
2726
- let rs = replaceAll(a, PLACEHOLDER, () => PLACEHOLDER.replace('-->', '') + (i++));
2727
- return rs;
2728
- });
2729
- html = html.replace(EXP_STR, '$1><').trim();
2730
- html = convertHTML(html);
2731
- return [html, vars];
2732
- }
2733
- function convertHTML(html) {
2734
- if (!isString(html))
2735
- return html + '';
2736
- //attr convert
2737
- html = html.replace(EXP_ATTR_CONVERT, (a, b, c) => {
2738
- return ` ${b ?? ''}${kebabCase(c)}`;
2739
- });
2740
- //tag convert
2741
- html = html.replace(EXP_TAG_CONVERT, (a, b, c, d) => {
2742
- let tag = DefinitionTagMap[c];
2743
- return b + tag + d;
2744
- });
2745
- return html;
2746
- }
2747
- function buildVars(component, tmpl) {
2748
- let vars = concat(tmpl.vars);
2749
- let l = tmpl.strings.length - 1;
2750
- for (let i = 0; i <= l; i++) {
2751
- let val = get(tmpl.vars, i, '');
2752
- if (val instanceof Template) {
2753
- // let [h, v] = buildHTML(component, val)
2754
- let vs = buildVars(component, val);
2755
- vars.splice(i, 1, ...vs);
2756
- }
2757
- }
2758
- return vars;
2759
- }
2760
- const PLACEHOLDER = "<!--c_ui-pl_df-->";
2761
- const PLACEHOLDER_PREFFIX = "<!--c_ui-pl_df";
2762
- const PLACEHOLDER_EXP = /<!--c_ui-pl_df\d*(-->)?/;
2763
- /**
2764
- * 构建模板为DOM结构
2765
- * @param html
2766
- */
2767
- function buildTmplate(updatePoints, html, vars, renderComponent, isDirective = false) {
2768
- const container = document.createElement("div");
2769
- container.innerHTML = html;
2770
- let evList = renderComponent._eventList;
2771
- if (!evList) {
2772
- evList = renderComponent._eventList = [];
2773
- }
2774
- //遍历dom
2775
- const nodeIterator = document.createNodeIterator(container, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT);
2776
- let currentNode;
2777
- let varIndex = 0;
2778
- let slotComponent;
2779
- let keyNode = null;
2780
- let keyVal = '';
2781
- while ((currentNode = nodeIterator.nextNode())) {
2782
- if (slotComponent && !slotComponent.contains(currentNode)) {
2783
- slotComponent = undefined;
2784
- }
2785
- if (currentNode instanceof HTMLElement || currentNode instanceof SVGElement) {
2786
- if (currentNode instanceof CompElem) {
2787
- slotComponent = currentNode;
2788
- }
2789
- let props = {};
2790
- let attrs = toArray(currentNode.attributes);
2791
- for (let i = 0; i < attrs.length; i++) {
2792
- const attr = attrs[i];
2793
- let { name, value } = attr;
2794
- //todo 这里需要修改为 data-slot-xx
2795
- if (name === SLOT_KEY_PROPS) {
2796
- // varCacheQueue && varCacheQueue.push({ type: VarType.AttrSlot, name: slotName, attrName: name })
2797
- continue;
2798
- } //endif
2799
- if (startsWith(name, PLACEHOLDER_PREFFIX)) {
2800
- let val = vars[varIndex];
2801
- //support directive only for now
2802
- if (isArray(val) && isSymbol(val[0])) {
2803
- let [, args, executor, checker, varChain] = val;
2804
- checker(EnterPointType.TAG);
2805
- let po = new UpdatePoint(varIndex, new WeakRef(currentNode));
2806
- po.isDirective = true;
2807
- po.value = val;
2808
- po.isComponent = !!slotComponent;
2809
- updatePoints.push(po);
2810
- if (keyNode && keyNode?.contains(currentNode)) {
2811
- po.key = keyVal;
2812
- }
2813
- varIndex++;
2814
- executor(currentNode, args, undefined, { renderComponent, slotComponent, varChain });
2815
- }
2816
- currentNode.removeAttribute(name);
2817
- continue;
2818
- } //endif
2819
- //@event.stop.prevent.debounce
2820
- if (name[0] === ATTR_PREFIX_EVENT) {
2821
- let val;
2822
- if (PLACEHOLDER_EXP.test(value)) {
2823
- let po = new UpdatePoint(varIndex);
2824
- po.isPlaceholder = true;
2825
- if (keyNode && keyNode?.contains(currentNode)) {
2826
- po.key = keyVal;
2827
- }
2828
- updatePoints.push(po);
2829
- val = vars[varIndex];
2830
- if (!isFunction(val)) {
2831
- showTagError(currentNode.tagName, `Event '${name}' must be a function`);
2832
- continue;
2833
- }
2834
- varIndex++;
2835
- }
2836
- let evName = name.substring(1);
2837
- evList.push([evName, val, currentNode]);
2838
- currentNode.removeAttribute(name);
2839
- continue;
2840
- } //endif
2841
- if (name === ATTR_REF) {
2842
- if (PLACEHOLDER_EXP.test(value)) {
2843
- let val = vars[varIndex];
2844
- if (!(val instanceof RefObject)) {
2845
- showTagError(currentNode.tagName, `Ref must be a RefObject`);
2846
- continue;
2847
- }
2848
- let po = new UpdatePoint(varIndex);
2849
- po.isPlaceholder = true;
2850
- if (keyNode && keyNode?.contains(currentNode)) {
2851
- po.key = keyVal;
2852
- }
2853
- updatePoints.push(po);
2854
- varIndex++;
2855
- val.__setRef(new WeakRef(currentNode));
2856
- }
2857
- currentNode.removeAttribute(name);
2858
- continue;
2859
- } //endif
2860
- if (name === ATTR_KEY) {
2861
- let val = vars[varIndex];
2862
- currentNode.setAttribute(name, val);
2863
- let po = new UpdatePoint(varIndex);
2864
- po.isPlaceholder = true;
2865
- if (keyNode && keyNode?.contains(currentNode)) {
2866
- po.key = keyVal;
2867
- }
2868
- updatePoints.push(po);
2869
- varIndex++;
2870
- keyNode = currentNode;
2871
- keyVal = val;
2872
- if (updatePoints.length > 0) {
2873
- updatePoints.forEach(up => {
2874
- up.key = up.key ?? val;
2875
- });
2876
- }
2877
- continue;
2878
- } //endif
2879
- //校验变量必须是表达式
2880
- if (name[0] === ATTR_PREFIX_PROP && !PLACEHOLDER_EXP.test(value)) {
2881
- showTagError(currentNode.tagName, `Prop '${name}' must be an interpolation`);
2882
- continue;
2883
- }
2884
- if (PLACEHOLDER_EXP.test(value)) {
2885
- let val = vars[varIndex];
2886
- let po = new UpdatePoint(varIndex, new WeakRef(currentNode), name.replace(/\.|\?|@/, ''), value);
2887
- po.isComponent = !!slotComponent;
2888
- if (keyNode && keyNode?.contains(currentNode)) {
2889
- po.key = keyVal;
2890
- }
2891
- if (name[0] === ATTR_PREFIX_PROP ||
2892
- name[0] === ATTR_PREFIX_BOOLEAN ||
2893
- name[0] === ATTR_PREFIX_REF) {
2894
- if (isArray(val) && isSymbol(val[0])) {
2895
- let [, args, executor, checker, varChain] = val;
2896
- checker(EnterPointType.PROP);
2897
- let attrName = name.substring(1);
2898
- executor(currentNode, args, undefined, { renderComponent, slotComponent, varChain, attrName });
2899
- po.value = val;
2900
- po.isDirective = true;
2901
- }
2902
- else if (name[0] === ATTR_PREFIX_BOOLEAN) {
2903
- po.isToggleProp = true;
2904
- po.value = !!val;
2905
- let attrName = name.substring(1);
2906
- if (po.value)
2907
- currentNode.setAttribute(attrName, val);
2908
- }
2909
- else if (name[0] === ATTR_PREFIX_REF) {
2910
- po.value = val;
2911
- let refNames = name.substring(1);
2912
- const [refNamec, prop] = refNames.split(ATTR_PROP_DELIMITER);
2913
- let refName = refNamec;
2914
- switch (prop) {
2915
- case 'camel':
2916
- refName = camelCase(refName);
2917
- break;
2918
- case 'kebab':
2919
- refName = kebabCase(refName);
2920
- break;
2921
- case 'snake':
2922
- refName = snakeCase(refName);
2923
- break;
2924
- }
2925
- po.attrName = refName;
2926
- currentNode.setAttribute(refName, val);
2927
- }
2928
- else {
2929
- if (!(currentNode instanceof CompElem) && currentNode.tagName !== 'SLOT') {
2930
- showTagError(currentNode.tagName, `Prop '${name}' can only be set on a CompElem or a slot`);
2931
- }
2932
- else {
2933
- let propName = camelCase(name.substring(1));
2934
- if (!(propName in currentNode) && currentNode.tagName !== 'SLOT') {
2935
- showTagError(currentNode.tagName, `Prop '${name}' is not defined in ${currentNode.tagName}`);
2936
- }
2937
- po.value = val;
2938
- po.isProp = true;
2939
- props[propName] = val;
2940
- }
2941
- }
2942
- currentNode.removeAttribute(name);
2943
- val = '';
2944
- }
2945
- else {
2946
- po.value = val;
2947
- let executor;
2948
- let args;
2949
- if (isArray(val) && isSymbol(val[0])) {
2950
- let type = EnterPointType.ATTR;
2951
- if (name === "class") {
2952
- type = EnterPointType.CLASS;
2953
- }
2954
- else if (name === "style") {
2955
- type = EnterPointType.STYLE;
2956
- }
2957
- let [, ags, exec, checker] = val;
2958
- {
2959
- checker(type);
2960
- }
2961
- po.isDirective = true;
2962
- po.attrName = name;
2963
- args = ags;
2964
- executor = exec;
2965
- val = '';
2966
- }
2967
- value = replace(value, PLACEHOLDER_EXP, val);
2968
- //回填
2969
- attr.value = value;
2970
- if (isDefined(value)) {
2971
- currentNode.setAttribute(name, value);
2972
- }
2973
- executor && executor(currentNode, args, undefined, { renderComponent, slotComponent });
2974
- }
2975
- updatePoints.push(po);
2976
- varIndex++;
2977
- } //endif
2978
- } //endfor
2979
- if (currentNode instanceof CompElem) {
2980
- currentNode._regWrapper(renderComponent);
2981
- if (size(props) > 0)
2982
- currentNode._initProps(props);
2983
- }
2984
- else if (currentNode instanceof HTMLSlotElement) {
2985
- renderComponent._bindSlot(currentNode, currentNode.name || 'default', props);
2986
- }
2987
- }
2988
- else {
2989
- let comment = currentNode;
2990
- let ph = `<!--${comment.nodeValue}-->`;
2991
- if (ph !== PLACEHOLDER) {
2992
- continue;
2993
- }
2994
- let po = new UpdatePoint(varIndex, new WeakRef(currentNode));
2995
- if (keyNode && keyNode?.contains(currentNode)) {
2996
- po.key = keyVal;
2997
- }
2998
- updatePoints.push(po);
2999
- po.isComponent = !!slotComponent;
3000
- po.isText = true;
3001
- let val = vars[varIndex];
3002
- if (isArray(val) && isSymbol(val[0])) {
3003
- const diName = Symbol.keyFor(val[0]);
3004
- //插入start占位符
3005
- let startComment;
3006
- startComment = document.createComment(`compelem-${renderComponent.tagName}-${diName}-start`);
3007
- comment.parentNode.insertBefore(startComment, comment);
3008
- comment.nodeValue = `compelem-${renderComponent.tagName}-${diName}-end`;
3009
- comment._diName = diName;
3010
- DI_COMMENT_START_NODE_MAP.set(comment, startComment);
3011
- po.isDirective = true;
3012
- po.value = val;
3013
- let pType = slotComponent ? EnterPointType.SLOT : EnterPointType.TEXT;
3014
- let [, args, executor, checker, varChain] = val;
3015
- checker(pType);
3016
- po.directiveOldValue = [args, varChain];
3017
- Collector.start();
3018
- let tmpl = executor(comment, args, undefined, { renderComponent, slotComponent, varChain });
3019
- Collector.end(renderComponent, po);
3020
- //render
3021
- if (tmpl) {
3022
- let nodes = buildSubView(comment, tmpl[1], renderComponent, po);
3023
- let len = nodes.length;
3024
- if (nodes && len > 0) {
3025
- DomUtil.insertBefore(comment, Array.from(nodes));
3026
- }
3027
- }
3028
- val = undefined;
3029
- }
3030
- else {
3031
- po.value = val;
3032
- po.node = null;
3033
- }
3034
- varIndex++;
3035
- if (!po.isDirective) {
3036
- let text = toString(val ?? '');
3037
- let textDom = document.createTextNode(text);
3038
- comment.parentNode.insertBefore(textDom, comment);
3039
- comment.remove();
3040
- currentNode = textDom;
3041
- po.node = new WeakRef(textDom);
3042
- }
3043
- }
3044
- if (keyNode && !keyNode.contains(currentNode) && keyNode !== currentNode) {
3045
- keyNode = null;
3046
- keyVal = '';
3047
- }
3048
- }
3049
- return container.childNodes;
3050
- }
3051
- function buildView(tmpl, component) {
3052
- let updatePoints = [];
3053
- let nodes;
3054
- if (HTML_TMPL_CACHE[component.tagName]) {
3055
- let htmlTmpl = HTML_TMPL_CACHE[component.tagName];
3056
- let vars = buildVars(component, tmpl);
3057
- nodes = buildTmplate(updatePoints, htmlTmpl, vars, component);
3058
- }
3059
- else {
3060
- let [html, vars] = buildHTML(component, tmpl);
3061
- HTML_TMPL_CACHE[component.tagName] = html;
3062
- nodes = buildTmplate(updatePoints, html, vars, component);
3063
- }
3064
- component.__updateTree = updatePoints;
3065
- return nodes;
3066
- }
3067
- function buildSubView(pointNode, tmpl, component, po, bindEvent = false) {
3068
- let [html, vars] = buildHTML(component, tmpl);
3069
- let updatePoints = [];
3070
- let nodes = buildTmplate(updatePoints, html, vars, component, true);
3071
- if (bindEvent)
3072
- component.__bindEvents();
3073
- updatePoints.forEach(up => {
3074
- po.insert(up);
3075
- });
3076
- return nodes;
3077
- }
3078
- function updateView(tmpl, renderComponent, updatePoints, changedKeys) {
3079
- if (isBlank(join(tmpl.strings)))
3080
- return;
3081
- let vars = tmpl.flatVars(renderComponent);
3082
- for (let i = 0; i < updatePoints.length; i++) {
3083
- const up = updatePoints[i];
3084
- let varIndex = up.varIndex;
3085
- if (varIndex < 0)
3086
- continue;
3087
- if (up.isPlaceholder)
3088
- continue;
3089
- if (up.__destroyed)
3090
- continue;
3091
- let oldValue = up.value;
3092
- let newValue = vars;
3093
- let node = up.node.deref();
3094
- if (!node)
3095
- continue;
3096
- let indexSegs = split(varIndex, PATH_SEPARATOR);
3097
- for (let l = 0; l < indexSegs.length; l++) {
3098
- const seg = indexSegs[l];
3099
- newValue = get(newValue, seg);
3100
- if (newValue && newValue.vars && i < indexSegs.length - 1) {
3101
- newValue = newValue.vars;
3102
- }
3103
- }
3104
- //check
3105
- if (!isObject(oldValue) && oldValue === newValue)
3106
- continue;
3107
- let elNode = node;
3108
- if (up.isDirective) {
3109
- //指令
3110
- let [, oldArgs, executor, , varChain] = up.value;
3111
- if (!isArray(newValue))
3112
- continue;
3113
- let slotComponent = getSlotComponent(node, renderComponent);
3114
- let [, newArgs] = newValue;
3115
- updateDirective(node, newArgs, oldArgs, executor, renderComponent, slotComponent, varChain, up);
3116
- }
3117
- else if (up.isToggleProp) {
3118
- //布尔特性
3119
- if ((!!newValue) === oldValue)
3120
- continue;
3121
- elNode.toggleAttribute(up.attrName, !!newValue);
3122
- set(elNode, up.attrName, !!newValue);
3123
- }
3124
- else if (up.isProp) {
3125
- //子组件属性
3126
- if (!isObject(newValue) && newValue === oldValue)
3127
- continue;
3128
- //如果node是slot则触发组件的slot更新
3129
- if (node instanceof CompElem) {
3130
- node._updateProps({ [up.attrName]: newValue });
3131
- }
3132
- else if (node instanceof HTMLSlotElement) {
3133
- renderComponent._updateSlot(node.getAttribute('name') || 'default', up.attrName, newValue);
3134
- }
3135
- }
3136
- else if (up.attrName) {
3137
- //特性
3138
- if (!isEqual(oldValue, newValue)) {
3139
- switch (up.attrName) {
3140
- case 'value':
3141
- if (node instanceof HTMLInputElement) {
3142
- node.value = newValue;
3143
- break;
3144
- }
3145
- default:
3146
- node.setAttribute(up.attrName, replace(up.attrTmpl, PLACEHOLDER_EXP, newValue + ''));
3147
- }
3148
- }
3149
- }
3150
- else if (up.isText) {
3151
- let textNode = up.node;
3152
- textNode.deref().textContent = toString(newValue ?? '');
3153
- }
3154
- up.value = newValue;
3155
- } //endfor
3156
- // tmpl.destroy()
3157
- }
3158
- function updateSubScopeView(subScopeUpdatePoint, renderComponent, tmpl, changedKeys) {
3159
- if (!subScopeUpdatePoint)
3160
- return;
3161
- let node = subScopeUpdatePoint.node.deref();
3162
- const executor = TextOrSlotDirectiveExecutorMap.get(node._diName);
3163
- let slotComponent = getSlotComponent(node, renderComponent);
3164
- const [oldArgs, varChain] = subScopeUpdatePoint.directiveOldValue;
3165
- if (!tmpl) {
3166
- let rs = executor(node, subScopeUpdatePoint.value[1], oldArgs, { renderComponent, slotComponent, varChain });
3167
- if (!rs)
3168
- return;
3169
- tmpl = rs[1];
3170
- }
3171
- if (!tmpl)
3172
- return;
3173
- //合并
3174
- if (tmpl.vars[0] instanceof Template) {
3175
- let tStrAry = [];
3176
- let tVarAry = [];
3177
- each(tmpl.vars, v => {
3178
- tVarAry.push(...v.vars);
3179
- tStrAry.push(...map(v.vars, v => '1'));
3180
- });
3181
- tStrAry.push('1');
3182
- tmpl = new Template(tStrAry, tVarAry);
3183
- }
3184
- updateView(tmpl, renderComponent, subScopeUpdatePoint.children);
3185
- }
3186
- //////////////////////////////////////////////////// interfaces
3187
- /**
3188
- * 标签函数,用于构建模板
3189
- * @param strings
3190
- * @param vars
3191
- */
3192
- function html(strings, ...vars) {
3193
- return new Template(isString(strings) ? [strings] : strings, vars);
3194
- }
3195
- /**
3196
- * 标签函数,用于构建样式
3197
- * @param strings
3198
- * @param vars
3199
- */
3200
- function css(strings, ...vars) {
3201
- return new CssTemplate(isString(strings) ? [strings] : strings, vars);
3202
- }
3203
- const EXP_STR = /([a-z0-9"'])\s*>\s*</img;
3204
- class RefObject {
3205
- #ref;
3206
- get current() {
3207
- return this.#ref?.deref();
3208
- }
3209
- __setRef(ref) {
3210
- this.#ref = ref;
3211
- }
3212
- }
3213
- /**
3214
- * 使用初始值创建一个引用对象
3215
- * @param initValue
3216
- * @returns
3217
- */
3218
- function createRef() {
3219
- return new RefObject();
3220
- }
3221
-
3222
- //装饰器类型
3223
- var DecoratorType;
3224
- (function (DecoratorType) {
3225
- DecoratorType["CLASS"] = "class";
3226
- DecoratorType["FIELD"] = "field";
3227
- DecoratorType["METHOD"] = "method";
3228
- })(DecoratorType || (DecoratorType = {}));
3229
- /**
3230
- * 用于构造装饰器
3231
- * @author holyhigh2
3232
- */
3233
- class Decorator {
3234
- /**
3235
- * 优先级,越大越先执行
3236
- */
3237
- static get priority() {
3238
- return 0;
3239
- }
3240
- /**
3241
- * 构造会传递自定义参数
3242
- * @param args 自定义参数
3243
- */
3244
- // constructor(...args: any[]) { }
3245
- created(component, ...args) { }
3246
- /**
3247
- * 执行时机与组件一致
3248
- * @param component 组件实例
3249
- * @param setReactive 为实例设置响应属性,注意,仅是设置到了instance.reactiveData中并非this.key。如需实现this访问,可自行定义组件的properties
3250
- * @param args 装饰器函数参数
3251
- */
3252
- beforeMount(component, setReactive, ...args) { }
3253
- mounted(component, setReactive, ...args) { }
3254
- updated(component, changed) { }
3255
- beforeDestroy(component, ...args) { }
3256
- }
3257
-
3258
- /**
3259
- * 装饰器包装类
3260
- * 用于框架内部,表示class上的一个装饰器属性定义
3261
- * 该定义在实例初始化时会产生装饰器实例属性
3262
- */
3263
- class DecoratorWrapper {
3264
- //装饰器参数
3265
- metadata;
3266
- decorator;
3267
- key; //装饰器唯一key
3268
- priority = 0;
3269
- constructor(args, metadata, decoratorClass) {
3270
- this.metadata = metadata;
3271
- this.decorator = new decoratorClass(...args);
3272
- this.priority = get(decoratorClass, 'priority', 0);
3273
- }
3274
- dispose() {
3275
- //clean up
3276
- this.metadata = null;
3277
- this.decorator = null;
3278
- }
3279
- //在组件构造时调用
3280
- create(comp) {
3281
- //1. 校验targets
3282
- let targets = this.decorator.targets;
3283
- let decoType = undefined;
3284
- let descriptor = this.metadata[1];
3285
- if (isObject(descriptor) && isDefined(get(descriptor, 'configurable'))) {
3286
- decoType = DecoratorType.METHOD;
3287
- }
3288
- else if (isUndefined(this.metadata[1])) {
3289
- decoType = DecoratorType.FIELD;
3290
- }
3291
- if (isEmpty(targets) || !decoType || !targets.includes(decoType)) {
3292
- showError(`Decorator '${this.decorator.constructor.name}' is out of targets, expect '${targets.join(',')}' bug got '${decoType}'`);
3293
- return;
3294
- }
3295
- this.decorator.created(comp, ...this.metadata);
3296
- }
3297
- beforeMount(comp, setReactive) {
3298
- this.decorator.beforeMount(comp, setReactive, ...this.metadata);
3299
- }
3300
- mounted(comp, setReactive) {
3301
- this.decorator.mounted(comp, setReactive, ...this.metadata);
3302
- }
3303
- updated(comp, changed) {
3304
- this.decorator.updated(comp, changed);
3305
- }
3306
- destroy(comp) {
3307
- this.decorator.beforeDestroy(comp, ...this.metadata);
3308
- }
3309
- }
3310
- /**
3311
- * 该函数用于创建一个装饰器
3312
- * @param decoClass 装饰器构造
3313
- * @returns 装饰器函数
3314
- */
3315
- function decorator(decoClass) {
3316
- let fn = (...args) => {
3317
- return (...metadata) => {
3318
- let ctor = metadata[0].constructor;
3319
- let ary = DefinitionDecoratorMap.get(ctor.name); // ctor[_DecoratorsKey]
3320
- if (!DefinitionDecoratorMap.has(ctor.name)) {
3321
- //继承父类
3322
- let proto = Object.getPrototypeOf(ctor);
3323
- ary = proto ? concat(DefinitionDecoratorMap.get(proto.name) ?? []) : [];
3324
- DefinitionDecoratorMap.set(ctor.name, ary);
3325
- }
3326
- let dw = new DecoratorWrapper(args, metadata.splice(1), decoClass);
3327
- ary?.push(dw);
3328
- return dw;
3329
- };
3330
- };
3331
- return fn;
3332
- }
3333
- function decoratorWithNoArgs(decoClass) {
3334
- let fn = (...metadata) => {
3335
- if (!metadata || metadata.length < 1)
3336
- return;
3337
- let ctor = metadata[0].constructor;
3338
- let ary = DefinitionDecoratorMap.get(ctor.name); // ctor[_DecoratorsKey]
3339
- if (!DefinitionDecoratorMap.has(ctor.name)) {
3340
- //继承父类
3341
- let proto = Object.getPrototypeOf(ctor);
3342
- ary = proto ? concat(DefinitionDecoratorMap.get(proto.name) ?? []) : [];
3343
- DefinitionDecoratorMap.set(ctor.name, ary);
3344
- }
3345
- let dw = new DecoratorWrapper([], metadata.splice(1), decoClass);
3346
- ary?.push(dw);
3347
- return dw;
3348
- };
3349
- return fn;
3350
- }
3351
-
3352
- function computed(target, propertyKey, descriptor) {
3353
- if (!descriptor.get) {
3354
- showError(`Computed '${propertyKey}' must be a getter`);
3355
- }
3356
- if (!DefinitionComputedMap.has(target.constructor.name)) {
3357
- DefinitionComputedMap.set(target.constructor.name, {});
3358
- }
3359
- DefinitionComputedMap.get(target.constructor.name)[propertyKey] = descriptor.get;
3360
- }
3361
-
3362
- /**
3363
- * 定义防抖函数
3364
- * 同时会创建一个以 _$__ 结尾的非防抖版本
3365
- * @example
3366
- * @debounced(50, true)
3367
- *
3368
- * @param wait 抖动间隔,单位ms
3369
- * @param immediate 立即执行
3370
- */
3371
- class DebouncedDecorator extends Decorator {
3372
- static get priority() {
3373
- return Number.MAX_VALUE;
3374
- }
3375
- created(component, fieldName, ...args) {
3376
- let fn = get(component, fieldName);
3377
- set(component, fieldName, debounce(fn, this.wait, this.immediate));
3378
- set(component, fieldName + '_$__', fn);
3379
- }
3380
- beforeDestroy(component, fieldName) {
3381
- set(component, fieldName, null);
3382
- set(component, fieldName + '_$__', null);
3383
- }
3384
- get targets() {
3385
- return [DecoratorType.METHOD];
3386
- }
3387
- wait;
3388
- immediate;
3389
- constructor(wait, immediate = false) {
3390
- super();
3391
- this.wait = wait;
3392
- this.immediate = immediate;
3393
- }
3394
- }
3395
- const debounced = decorator(DebouncedDecorator);
3396
-
3397
- /**
3398
- * 绑定非视图事件,如window/document等
3399
- * @param eventName 事件名,含修饰参数。同视图模板中的事件名
3400
- * @param eventTarget 事件绑定目标,默认this
3401
- */
3402
- function event(eventName, eventTarget) {
3403
- return (target, name, descriptor) => {
3404
- if (!DefinitionCompEventMap.has(target.constructor.name)) {
3405
- let mixinEvents = [];
3406
- let parentCtor = target.constructor;
3407
- while ((parentCtor = _getSuper(parentCtor)) !== CompElem) {
3408
- mixinEvents = concat(mixinEvents, DefinitionCompEventMap.get(parentCtor.name) ?? []);
3409
- }
3410
- DefinitionCompEventMap.set(target.constructor.name, mixinEvents);
3411
- }
3412
- DefinitionCompEventMap.get(target.constructor.name)?.push({ name: eventName, targetFn: eventTarget, fnName: name });
3413
- };
3414
- }
3415
-
3416
- /**
3417
- * 定义一次性函数
3418
- * 同时会创建一个以 _$__ 结尾的非一次性版本
3419
- * @example
3420
- * @onced
3421
- *
3422
- */
3423
- class OncedDecorator extends Decorator {
3424
- static get priority() {
3425
- return Number.MAX_VALUE;
3426
- }
3427
- created(component, classProto, fieldName, ...args) {
3428
- let fn = bind$1(get(component, fieldName), component);
3429
- set(component, fieldName, once(fn));
3430
- set(component, fieldName + '_$__', fn);
3431
- }
3432
- beforeDestroy(component, fieldName) {
3433
- set(component, fieldName, null);
3434
- set(component, fieldName + '_$__', null);
3435
- }
3436
- get targets() {
3437
- return [DecoratorType.METHOD];
3438
- }
3439
- }
3440
- const onced = decorator(OncedDecorator);
3441
-
3442
- /**
3443
- * 缓存策略
3444
- */
3445
- var QueryCache;
3446
- (function (QueryCache) {
3447
- QueryCache["ONCE"] = "once";
3448
- })(QueryCache || (QueryCache = {}));
3449
- const CacheMap = new WeakMap();
3450
- /**
3451
- * css查询装饰器
3452
- * @example
3453
- * @query('l-popup', QueryCache.ONCE)
3454
- */
3455
- class QueryDecorator extends Decorator {
3456
- static get priority() {
3457
- return Number.MAX_VALUE;
3458
- }
3459
- get targets() {
3460
- return [DecoratorType.FIELD];
3461
- }
3462
- selector;
3463
- cache;
3464
- constructor(selector, cache) {
3465
- super();
3466
- this.selector = selector;
3467
- this.cache = cache;
3468
- }
3469
- static getKey(selector) {
3470
- return selector;
3471
- }
3472
- getter(component) {
3473
- let el = component?.shadowRoot?.querySelector(this.selector);
3474
- let cMap = CacheMap.get(component);
3475
- if (!cMap) {
3476
- cMap = new Map();
3477
- CacheMap.set(component, cMap);
3478
- }
3479
- cMap.set(this.selector, el);
3480
- }
3481
- mounted(component, setReactive, fieldName, ...args) {
3482
- const that = this;
3483
- let wk = new WeakRef(component);
3484
- Reflect.defineProperty(component, fieldName, {
3485
- configurable: true,
3486
- get() {
3487
- let ctx = wk.deref();
3488
- if (CacheMap.has(ctx) && CacheMap.get(ctx)?.has(that.selector) && that.cache === QueryCache.ONCE) {
3489
- return CacheMap.get(ctx)?.get(that.selector);
3490
- }
3491
- that.getter(ctx);
3492
- return CacheMap.get(ctx)?.get(that.selector);
3493
- }
3494
- });
3495
- }
3496
- beforeDestroy(component, fieldName) {
3497
- CacheMap.get(component)?.clear();
3498
- CacheMap.delete(component);
3499
- }
3500
- updated(component, changed) {
3501
- if (this.cache === QueryCache.ONCE)
3502
- return;
3503
- this.getter(component);
3504
- }
3505
- }
3506
- class QueryAllDecorator extends QueryDecorator {
3507
- getter(component) {
3508
- let el = component.shadowRoot?.querySelectorAll(this.selector);
3509
- let cMap = CacheMap.get(component);
3510
- if (!cMap) {
3511
- cMap = new Map();
3512
- CacheMap.set(component, cMap);
3513
- }
3514
- cMap.set(this.selector, el);
3515
- }
3516
- }
3517
- const query = decorator(QueryDecorator);
3518
- const queryAll = decorator(QueryAllDecorator);
3519
-
3520
- function state(options) {
3521
- if (arguments.length === 1) {
3522
- return (target, stateKey) => {
3523
- defineState(target, stateKey, options);
3524
- };
3525
- }
3526
- let target = arguments[0], stateKey = arguments[1];
3527
- defineState(target, stateKey, { prop: "" });
3528
- }
3529
- function defineState(target, stateKey, options) {
3530
- if (!DefinitionStateMap.has(target.constructor.name)) {
3531
- const mixinStates = {};
3532
- let parentCtor = target.constructor;
3533
- while ((parentCtor = _getSuper(parentCtor)) !== CompElem) {
3534
- merge(mixinStates, DefinitionStateMap.get(parentCtor.name) ?? {});
3535
- }
3536
- DefinitionStateMap.set(target.constructor.name, mixinStates);
3537
- }
3538
- options.shallow = options.shallow || false;
3539
- set(DefinitionStateMap.get(target.constructor.name), stateKey, options);
3540
- }
3541
- /**
3542
- * 同@state装饰器,但可用于构造器中调用
3543
- * @param ctor 类构造函数
3544
- * @param stateKey state 名称
3545
- * @param options
3546
- */
3547
- function makeState(ctor, stateKey, options) {
3548
- defineState(ctor.prototype, stateKey, options || { prop: "" });
3549
- }
3550
-
3551
- /**
3552
- * class用注解,用于自动注册自定义组件
3553
- * @param name 自定义组件名称
3554
- */
3555
- function tag(name) {
3556
- return (target) => {
3557
- if (target) {
3558
- DefinitionTagMap[target.name] = name;
3559
- customElements.define(name, target);
3560
- }
3561
- };
3562
- }
3563
-
3564
- /**
3565
- * 定义节流函数
3566
- * 同时会创建一个以 _$__ 结尾的非节流版本
3567
- * @example
3568
- * @throttled(50, true)
3569
- *
3570
- * @param wait 抖动间隔,单位ms
3571
- */
3572
- class ThrottledDecorator extends Decorator {
3573
- static get priority() {
3574
- return Number.MAX_VALUE;
3575
- }
3576
- created(component, fieldName, ...args) {
3577
- let fn = get(component, fieldName);
3578
- set(component, fieldName, throttle(fn, this.wait));
3579
- set(component, fieldName + '_$__', fn);
3580
- }
3581
- beforeDestroy(component, fieldName) {
3582
- set(component, fieldName, null);
3583
- set(component, fieldName + '_$__', null);
3584
- }
3585
- get targets() {
3586
- return [DecoratorType.METHOD];
3587
- }
3588
- wait;
3589
- constructor(wait) {
3590
- super();
3591
- this.wait = wait;
3592
- }
3593
- }
3594
- const throttled = decorator(ThrottledDecorator);
3595
-
3596
- /**
3597
- * 监控prop/state变量值变化
3598
- * @param source 变量路径支持多级路径
3599
- * @param options
3600
- * @returns
3601
- */
3602
- function watch(source, options) {
3603
- return (target, name) => {
3604
- if (!DefinitionWatchMap.has(target.constructor.name)) {
3605
- const watchMap = {};
3606
- let parentCtor = target.constructor;
3607
- while ((parentCtor = _getSuper(parentCtor)) !== CompElem) {
3608
- if (DefinitionWatchMap.has(parentCtor.name)) {
3609
- let parentMap = DefinitionWatchMap.get(parentCtor.name);
3610
- each(parentMap, (list, k) => {
3611
- watchMap[k] = list;
3612
- });
3613
- }
3614
- }
3615
- DefinitionWatchMap.set(target.constructor.name, watchMap);
3616
- }
3617
- const sources = isArray(source) ? source : [source];
3618
- sources.forEach(src => {
3619
- let srcList = DefinitionWatchMap.get(target.constructor.name)[src];
3620
- if (!isArray(srcList)) {
3621
- srcList = [];
3622
- DefinitionWatchMap.get(target.constructor.name)[src] = srcList;
3623
- }
3624
- srcList.push({ source: src, options, handler: target[name] });
3625
- });
3626
- };
3627
- }
3628
-
3629
- const Ignores = ['key'];
3630
- /**
3631
- * 绑定属性到节点上,如果节点是组件会使用in操作符判断是否props
3632
- * @param styles 对象/数组/字符串
3633
- */
3634
- const bind = directive(function Bind(obj) {
3635
- return (pointNode, [obj], oldArgs) => {
3636
- let el = pointNode;
3637
- if (oldArgs) {
3638
- each(obj, (v, k) => {
3639
- el.setAttribute(k, v);
3640
- });
3641
- return;
3642
- }
3643
- if (el instanceof CompElem) {
3644
- //判断是否prop
3645
- let props = {};
3646
- let attrs = {};
3647
- let propDefs = DefinitionPropMap.get(el.constructor.name);
3648
- each(obj, (v, k) => {
3649
- if (Ignores.includes(k))
3650
- return;
3651
- let ck = camelCase(k);
3652
- let propDef = propDefs ? propDefs[ck] : undefined;
3653
- if (propDef) {
3654
- props[k] = v;
3655
- }
3656
- else {
3657
- attrs[k] = v + '';
3658
- }
3659
- });
3660
- el._initProps(props, attrs);
3661
- }
3662
- else {
3663
- each(obj, (v, k) => {
3664
- el.setAttribute(k, v);
3665
- });
3666
- }
3667
- };
3668
- }, [EnterPointType.TAG]);
3669
-
3670
- const ClassLastMap = new WeakMap();
3671
- /**
3672
- * 根据变量内容自动插入class,仅能用于class属性
3673
- * @param styles 对象/数组/字符串
3674
- */
3675
- const classes = directive(function Classes(clazz) {
3676
- return (pointNode, [clazz], oldArgs, { renderComponent }) => {
3677
- let rs = [];
3678
- if (isArray(clazz)) {
3679
- rs = compact(clazz);
3680
- }
3681
- else if (isObject(clazz)) {
3682
- rs = flatMap(clazz, (v, k) => v ? k : []);
3683
- }
3684
- else if (isString(clazz)) {
3685
- rs = clazz.split(' ');
3686
- }
3687
- if (rs.length < 1 && !oldArgs)
3688
- return;
3689
- let el = pointNode;
3690
- if (ClassLastMap.get(el) && ClassLastMap.get(el).length === rs.length && isMatch(ClassLastMap.get(el), rs))
3691
- return;
3692
- let lastCls = ClassLastMap.get(el);
3693
- each(lastCls, (cls) => {
3694
- el.classList.remove(cls);
3695
- });
3696
- each(rs, cls => {
3697
- el.classList.add(cls);
3698
- });
3699
- lastCls = concat(rs);
3700
- ClassLastMap.set(el, lastCls);
3701
- };
3702
- }, [EnterPointType.CLASS]);
3703
-
3704
- const LastValueMap = new WeakMap();
3705
- const LastTmplMap$1 = new WeakMap();
3706
- /**
3707
- * 循环列表并自动优化列表更新
3708
- * foreach循环的只能是节点,且必须有key属性。非节点元素会被过滤掉
3709
- * 使用序号作为key时可能会导致异常问题
3710
- */
3711
- const forEach = directive(function ForEach(value, cbk) {
3712
- return (pointNode, newArgs, oldArgs, { varChain }) => {
3713
- let el = pointNode;
3714
- let lastRenderTmpl = comboTmpl(newArgs[0], newArgs[1], el);
3715
- if (oldArgs && oldArgs[0]) {
3716
- //更新
3717
- const lastAry = LastValueMap.get(el);
3718
- // const lastRenderTmpl = LastTmplMap.get(el)
3719
- let startNode = DI_COMMENT_START_NODE_MAP.get(pointNode);
3720
- let nodes = DomUtil.getNodes(startNode, pointNode);
3721
- if (isEmpty(nodes) && (!newArgs || isEmpty(newArgs[0])))
3722
- return [DirectiveUpdateTag.NONE, lastRenderTmpl];
3723
- if (lastAry && isMatch(lastAry, newArgs[0]) && lastAry.length === newArgs[0].length)
3724
- return [DirectiveUpdateTag.NONE, lastRenderTmpl];
3725
- }
3726
- LastValueMap.set(el, clone(newArgs[0]));
3727
- if (oldArgs) {
3728
- return [DirectiveUpdateTag.UPDATE, lastRenderTmpl];
3729
- }
3730
- return [DirectiveUpdateTag.APPEND, lastRenderTmpl];
3731
- };
3732
- }, [EnterPointType.TEXT, EnterPointType.SLOT]);
3733
- function comboTmpl(value, cbk, el) {
3734
- //1. 产生模板
3735
- let tmpls = map(value, (v, k) => {
3736
- return cbk(v, k);
3737
- });
3738
- if (tmpls.length < 1) {
3739
- let lastRenderTmpl = new Template([], []);
3740
- LastTmplMap$1.set(el, lastRenderTmpl);
3741
- return lastRenderTmpl;
3742
- }
3743
- //2. 检查 & 合并模板
3744
- let keyAry = [];
3745
- let strs = [];
3746
- const combStrings = [];
3747
- const combVars = [];
3748
- for (let l = 0; l < tmpls.length; l++) {
3749
- const tmpl = tmpls[l];
3750
- let lastStr = last(strs);
3751
- let vars = tmpl.vars;
3752
- let hasNoKey = true;
3753
- let tmplStrs = tmpl.strings;
3754
- for (let i = 0; i < tmplStrs.length; i++) {
3755
- const str = tmplStrs[i];
3756
- if (EXP_KEY.test(str)) {
3757
- let key = vars[i] + '';
3758
- if (keyAry.includes(key)) {
3759
- showError(`forEach - duplicate key '${key}'`);
3760
- return;
3761
- }
3762
- keyAry.push(key);
3763
- hasNoKey = false;
3764
- }
3765
- if (i == 0 && lastStr) {
3766
- strs[strs.length - 1] = lastStr + str;
3767
- continue;
3768
- }
3769
- strs.push(str);
3770
- }
3771
- if (hasNoKey) {
3772
- showError("forEach - missing 'key' prop");
3773
- return;
3774
- }
3775
- let lastVar = last(combStrings);
3776
- if (lastVar && tmplStrs.length > 0) {
3777
- combStrings[combStrings.length - 1] = trim(lastVar) + tmplStrs.shift();
3778
- }
3779
- combStrings.push('');
3780
- combVars.push(tmpl);
3781
- }
3782
- combStrings.push('');
3783
- let lastRenderTmpl = new Template(combStrings, combVars);
3784
- LastTmplMap$1.set(el, lastRenderTmpl);
3785
- return lastRenderTmpl;
3786
- }
3787
-
3788
- let compiler = document.createElement('div');
3789
- /**
3790
- * 向指定文本位置插入指定HTML内容
3791
- * @param htmlStr html内容
3792
- */
3793
- const htmlC = directive(function HtmlC(htmlStr) {
3794
- return (pointNode, newArgs, oldArgs, { renderComponent, slotComponent }) => {
3795
- if (oldArgs && newArgs[0] == oldArgs[0])
3796
- return;
3797
- if (isNil(newArgs[0]))
3798
- return;
3799
- compiler.innerHTML = convertHTML(newArgs[0]);
3800
- pointNode.after(...compiler.childNodes);
3801
- };
3802
- }, [EnterPointType.TEXT, EnterPointType.SLOT]);
3803
-
3804
- /**
3805
- * 向元素中插入指定HTML内容
3806
- * 注意,应用该指令的元素内部不应再出现表达式,否则会导致异常显示
3807
- * @param htmlStr html内容
3808
- */
3809
- const htmlD = directive(function HtmlD(htmlStr) {
3810
- return (pointNode, newArgs, oldArgs, { renderComponent, slotComponent }) => {
3811
- if (oldArgs && newArgs[0] == oldArgs[0])
3812
- return;
3813
- if (isNil(newArgs[0]))
3814
- return;
3815
- pointNode.innerHTML = convertHTML(newArgs[0]);
3816
- };
3817
- }, [EnterPointType.TAG]);
3818
-
3819
- const LastTmplMap = new WeakMap();
3820
- /**
3821
- * 条件为真时返回参数1,否则返回参数2,仅能用于文本节点
3822
- * @param condition 条件
3823
- * @param tmpl 模板
3824
- */
3825
- const ifElse = directive(function IfElse(condition, ifTmpl, elseTmpl) {
3826
- return (pointNode, [condi, ifTmpl, elseTmpl], oldArgs, { renderComponent }) => {
3827
- let el = pointNode;
3828
- if (oldArgs) {
3829
- //更新
3830
- if (!!condi === !!oldArgs[0]) {
3831
- let tmpl = LastTmplMap.get(el);
3832
- return [DirectiveUpdateTag.NONE, tmpl.call(renderComponent, condi)];
3833
- }
3834
- let tmpl = condi ? ifTmpl : elseTmpl;
3835
- LastTmplMap.set(el, tmpl);
3836
- return [DirectiveUpdateTag.REPLACE, tmpl.call(renderComponent, condi)];
3837
- }
3838
- else {
3839
- let tmpl = condi ? ifTmpl : elseTmpl;
3840
- LastTmplMap.set(el, tmpl);
3841
- return [DirectiveUpdateTag.APPEND, tmpl.call(renderComponent, condi)];
3842
- }
3843
- };
3844
- }, [EnterPointType.TEXT, EnterPointType.SLOT]);
3845
-
3846
- /**
3847
- * 条件为真时返回内容,仅能用于文本节点
3848
- * @param condition 条件
3849
- * @param tmpl 模板
3850
- */
3851
- const ifTrue = directive(function IfTrue(condition, tmplFn) {
3852
- return (pointNode, [condi, render], oldArgs) => {
3853
- if (oldArgs) {
3854
- //更新
3855
- if (condi === oldArgs[0])
3856
- return [DirectiveUpdateTag.NONE, condi ? render() : html ``];
3857
- if (condi) {
3858
- return [DirectiveUpdateTag.REPLACE, condi ? render() : html ``];
3859
- }
3860
- return [DirectiveUpdateTag.REMOVE];
3861
- }
3862
- else {
3863
- return [DirectiveUpdateTag.APPEND, condi ? render() : html ``];
3864
- }
3865
- };
3866
- }, [EnterPointType.TEXT, EnterPointType.SLOT]);
3867
-
3868
- var ModelTriggerType;
3869
- (function (ModelTriggerType) {
3870
- ModelTriggerType["CHANGE"] = "change";
3871
- ModelTriggerType["INPUT"] = "input";
3872
- })(ModelTriggerType || (ModelTriggerType = {}));
3873
- /**
3874
- * 实现双向绑定(仅支持静态路径,动态增加的属性路径无法识别)
3875
- * 当用于组件时,监控 @update:value 事件
3876
- * 当用于元素时,
3877
- * - 对于 input/textarea 监控 @input,并设置 value 属性
3878
- * - 对于 checkbox/radio 监控 @change,并设置 checked 属性
3879
- * - 对于 select 监控 @change,并设置 value 属性
3880
- * @param modelValue 双向绑定的组件变量
3881
- * @param updateProp 绑定模型变更时的监控属性,默认 value
3882
- * @param modelProp 当初始模型路径不存在时可指定路径
3883
- */
3884
- const model = directive(function Model(modelValue, updateProp = 'value', modelProp) {
3885
- return (pointNode, [modelValue, updateProp, modelProp], oldArgs, { varChain, renderComponent }) => {
3886
- updateProp = updateProp ?? 'value';
3887
- const node = pointNode;
3888
- if (oldArgs) {
3889
- const oldValue = oldArgs[0];
3890
- const newValue = modelValue;
3891
- let nodeValue = get(node, updateProp);
3892
- if (!isObject(newValue) && Object.is(newValue, oldValue) && Object.is(nodeValue, newValue))
3893
- return;
3894
- if (node instanceof CompElem) {
3895
- node._updateProps({ [updateProp]: newValue });
3896
- }
3897
- else if (node instanceof HTMLTextAreaElement || node instanceof HTMLSelectElement) {
3898
- node.setAttribute(updateProp, newValue + '');
3899
- if (node instanceof HTMLSelectElement) {
3900
- let opt = find(node.querySelectorAll('option'), n => n.value == newValue);
3901
- if (opt) {
3902
- opt.selected = true;
3903
- }
3904
- }
3905
- }
3906
- else if (node instanceof HTMLInputElement) {
3907
- if (node.value == newValue)
3908
- return;
3909
- switch (node.type) {
3910
- case 'checkbox':
3911
- case 'radio':
3912
- if (!!newValue) {
3913
- node.setAttribute('checked', '');
3914
- }
3915
- else {
3916
- node.removeAttribute('checked');
3917
- }
3918
- break;
3919
- case 'text':
3920
- case 'email':
3921
- case 'number':
3922
- case 'password':
3923
- case 'search':
3924
- case 'tel':
3925
- case 'url':
3926
- node.setAttribute(updateProp, newValue + '');
3927
- set(node, updateProp, newValue);
3928
- break;
3929
- default:
3930
- node.setAttribute(updateProp, newValue + '');
3931
- break;
3932
- }
3933
- }
3934
- return;
3935
- }
3936
- let path;
3937
- if (isString(modelProp)) {
3938
- path = toPath(modelProp)[0];
3939
- }
3940
- else {
3941
- path = last(varChain);
3942
- }
3943
- const rootPath = split(path, '.')[0];
3944
- if (!(rootPath in renderComponent) && !renderComponent._wrapperProp[rootPath]) {
3945
- showError(`model - property '${rootPath}' is not defined on the instance of ` + renderComponent.tagName);
3946
- }
3947
- let evList = renderComponent._eventList;
3948
- if (!isObject(modelValue) && !trim(modelValue))
3949
- modelValue = '';
3950
- if (node instanceof CompElem) {
3951
- node._initProps({ [updateProp]: modelValue });
3952
- let evName = 'update:' + updateProp;
3953
- evList.push([evName, function (e) {
3954
- console.debug('Model =>', path);
3955
- let ctx = this;
3956
- let pathFromWrapperComponent = ctx._wrapperProp[rootPath];
3957
- let hasPath = rootPath in ctx;
3958
- if (!hasPath && pathFromWrapperComponent && get(ctx.wrapperComponent, rootPath) === get(ctx, pathFromWrapperComponent)) {
3959
- ctx = ctx.wrapperComponent || ctx;
3960
- }
3961
- set(ctx, path, e.detail.value);
3962
- }, node]);
3963
- }
3964
- else if (node instanceof HTMLTextAreaElement) {
3965
- node.setAttribute(updateProp, modelValue + '');
3966
- let evName = 'input';
3967
- evList.push([evName, function (e) {
3968
- console.debug('Model =>', path);
3969
- let t = e.target;
3970
- set(this, path, t.value);
3971
- }, node]);
3972
- }
3973
- else if (node instanceof HTMLInputElement) {
3974
- let propName = '';
3975
- let evName = '';
3976
- switch (node.type) {
3977
- case 'checkbox':
3978
- case 'radio':
3979
- propName = 'checked';
3980
- evName = 'change';
3981
- break;
3982
- case 'text':
3983
- case 'email':
3984
- case 'number':
3985
- case 'password':
3986
- case 'search':
3987
- case 'tel':
3988
- case 'url':
3989
- propName = 'value';
3990
- evName = 'input';
3991
- break;
3992
- default:
3993
- propName = 'value';
3994
- evName = 'input';
3995
- break;
3996
- }
3997
- node.setAttribute(updateProp ?? propName, modelValue + '');
3998
- evList.push([evName, function (e) {
3999
- console.debug('Model =>', path);
4000
- let t = e.target;
4001
- set(this, path, t.value);
4002
- }, node]);
4003
- }
4004
- else if (node instanceof HTMLSelectElement) {
4005
- node.setAttribute(updateProp, modelValue + '');
4006
- evList.push(['change', function (e) {
4007
- console.debug('Model =>', path);
4008
- let t = e.target;
4009
- let ctx = this;
4010
- let pathFromWrapperComponent = ctx._wrapperProp[rootPath];
4011
- let hasPath = rootPath in ctx;
4012
- if (!hasPath && pathFromWrapperComponent && get(ctx.wrapperComponent, rootPath) === get(ctx, pathFromWrapperComponent)) {
4013
- ctx = ctx.wrapperComponent || ctx;
4014
- }
4015
- set(ctx, path, t.value);
4016
- }, node]);
4017
- }
4018
- };
4019
- }, [EnterPointType.TAG]);
4020
-
4021
- const DisplayMap = new WeakMap();
4022
- /**
4023
- * display的快捷指令
4024
- * 如果
4025
- * @param isvisible 是否显示
4026
- * @param cbk 显示状态变更后调用的回调函数
4027
- */
4028
- const show = directive(function Show(isVisible, cbk) {
4029
- return (pointNode, [condi, cbk], oldArgs) => {
4030
- if (oldArgs && condi === oldArgs[0])
4031
- return;
4032
- let el = pointNode;
4033
- if (!DisplayMap.has(el)) {
4034
- let dis = el.style.display;
4035
- DisplayMap.set(el, dis == 'none' ? 'unset' : dis);
4036
- }
4037
- el.style.display = condi ? DisplayMap.get(el) : 'none';
4038
- if (cbk) {
4039
- cbk(el, condi);
4040
- }
4041
- };
4042
- }, [EnterPointType.TAG]);
4043
-
4044
- /**
4045
- * 创建一个动态插槽内容
4046
- * @param cbk 回调函数,函数接收插槽上定义得变量
4047
- * @param slotName 插槽名词,默认default
4048
- */
4049
- const slot = directive(function Slot(cbk, slotName) {
4050
- return (pointNode, [cbk, slotName], oldArgs, { renderComponent, slotComponent }) => {
4051
- if (oldArgs)
4052
- return;
4053
- cbk = cbk.bind(renderComponent);
4054
- slotComponent._bindSlotHook(slotName || 'default', cbk);
4055
- };
4056
- }, [EnterPointType.SLOT]);
4057
-
4058
- /**
4059
- * Css 辅助类
4060
- */
4061
- class CssHelper {
4062
- /**
4063
- * 用于转换style对象为标准style字符串,会自动转换对象key为短横线格式
4064
- * @param styles 样式对象
4065
- * @returns
4066
- */
4067
- static getCssText(styles, important = false) {
4068
- if (isString(styles))
4069
- return styles;
4070
- return join(map(styles, (v, k) => {
4071
- if (k.startsWith('--'))
4072
- return k + ":" + v + (important ? ' !important' : '');
4073
- return kebabCase(k) + ":" + v + (important ? ' !important' : '');
4074
- }), ';') + ';';
4075
- }
4076
- /**
4077
- * 设置样式
4078
- * @param styles 样式字符串或样式对象
4079
- * @param node HTML元素
4080
- * @returns 每个样式的旧值map
4081
- */
4082
- static setStyle(styles, node) {
4083
- if (isString(styles) && !trim(styles))
4084
- return;
4085
- let css = CssHelper.getCssText(styles);
4086
- node.style.cssText = css;
4087
- }
4088
- }
4089
-
4090
- /**
4091
- * 根据变量内容设置元素样式,仅能用于style属性
4092
- * @param styles 对象/字符串
4093
- */
4094
- const styles = directive(function Styles(...styles) {
4095
- return (pointNode, newArgs, oldArgs, { renderComponent }) => {
4096
- let el = pointNode;
4097
- let cssText = reduce(newArgs, (acc, v) => acc + CssHelper.getCssText(v), '');
4098
- let sKeys = compact(cssText.split(';').map(str => str.split(':')[0]));
4099
- let eKeys = compact(el.style.cssText.split(';'));
4100
- let ePairs = reject(eKeys, (str => sKeys.some(key => str.trim().startsWith(key))));
4101
- el.style.cssText = cssText + ePairs.join(';');
4102
- };
4103
- }, [EnterPointType.STYLE]);
4104
-
4105
- /**
4106
- * 类似Model,实现属性的同步跟踪
4107
- * 设置组件prop,并监控 @update:prop 事件
4108
- * @param syncValue 双向绑定的组件变量
4109
- */
4110
- const sync = directive(function Sync(syncValue) {
4111
- return (pointNode, newArgs, oldArgs, { renderComponent, varChain, attrName }) => {
4112
- const targetComponent = pointNode;
4113
- if (oldArgs) {
4114
- if (!isEqual(newArgs, oldArgs)) {
4115
- targetComponent._updateProps({ [attrName]: newArgs[0] });
4116
- }
4117
- return;
4118
- }
4119
- let modelPath = last(varChain);
4120
- targetComponent._initProps({ [attrName]: newArgs[0] });
4121
- targetComponent.addEventListener('update:' + attrName, (e) => {
4122
- set(renderComponent, modelPath, e.detail.value);
4123
- });
4124
- };
4125
- }, [EnterPointType.PROP]);
4126
-
4127
- /**
4128
- * 分支指令,具有switch / else if 两种模式
4129
- * @example
4130
- * switch 模式
4131
- * ${when(var, {
4132
- closed: () => html``, //case 1
4133
- connecting: () => html``, //case 2
4134
- default: () => html``// default是switch模式下的关键字key
4135
- })}
4136
-
4137
- else if 模式
4138
- * ${when(this.editingTitle, [
4139
- [(v: any) => v.substring(2) > 0, () => html`<div style="${PageHome.tunnelLight}"></div>`],
4140
- [(v: any) => v == 'closed', () => html`<div style="${PageHome.tunnelLight}"></div>`],
4141
- [() => true, () => html`默认`]
4142
- ])}
4143
- *
4144
- * @param condition 条件
4145
- * @param tmpl 模板
4146
- */
4147
- const when = directive(function When(value, cases) {
4148
- return (pointNode, [value, cases], oldArgs) => {
4149
- let defaultFn = () => html ``;
4150
- let conditionList = [];
4151
- let tmplList = [];
4152
- each(cases, (v, k) => {
4153
- if (isFunction(v)) {
4154
- conditionList.push(k);
4155
- tmplList.push(v);
4156
- }
4157
- else {
4158
- let condiFn = v[0];
4159
- let tmplFn = v[1];
4160
- conditionList.push(condiFn);
4161
- tmplList.push(tmplFn);
4162
- }
4163
- if (k === 'default') {
4164
- defaultFn = v;
4165
- }
4166
- });
4167
- let i = findIndex(conditionList, c => {
4168
- if (isFunction(c)) {
4169
- return c(value);
4170
- }
4171
- else {
4172
- return c == value;
4173
- }
4174
- });
4175
- if (oldArgs)
4176
- return [DirectiveUpdateTag.REPLACE, call(tmplList[i] ?? defaultFn)];
4177
- return [DirectiveUpdateTag.APPEND, call(tmplList[i] ?? defaultFn)];
4178
- };
4179
- }, [EnterPointType.TEXT, EnterPointType.SLOT]);
4180
-
4181
- export { CompElem, CssHelper, CssTemplate, DI_COMMENT_START_NODE_MAP, Decorator, DecoratorType, DecoratorWrapper, DirectiveUpdateTag, DomUtil, EnterPointType, ModelTriggerType, QueryCache, Template, TextOrSlotDirectiveExecutorMap, UpdatePoint, _getObservedAttrs, _getSuper, _toUpdatePath, bind, buildHTML, classes, computed, createRef, css, debounced, decorator, decoratorWithNoArgs, directive, event, forEach, getBooleanValue, getSlotComponent, html, htmlC, htmlD, ifElse, ifTrue, isBooleanProp, makeState, model, onced, prop, query, queryAll, show, showError, showTagError, showTagWarn, showWarn, slot, state, styles, sync, tag, throttled, updateDirective, watch, when };
7
+ import t,{toPath as e,some as s,isString as r,isUndefined as n,isBlank as o,closest as i,isObject as a,isFunction as l,startsWith as c,get as u,concat as h,toArray as d,isSymbol as p,isArray as f,size as g,eachRight as _,slice as m,defaults as v,isLowerCaseChar as y,merge as E,each as w,kebabCase as b,has as S,set as N,includes as T,find as C,debounce as k,throttle as M,once as P,remove as A,map as x,flatMap as R,test as D,assign as O,first as L,walkTree as I,isEmpty as V,filter as W,isNil as H,camelCase as U,isNull as B,isDefined as $,trim as j,isBoolean as F,parseJSON as z,cloneDeep as G,keys as X,groupBy as K,last as q,reject as Q,toString as Z,reduce as Y,compact as J,initial as tt,except as et,join as st,split as rt,isEqual as nt,replace as ot,replaceAll as it,snakeCase as at,bind as lt,isMatch as ct,clone as ut,findIndex as ht,call as dt}from"myfx";const pt="default",ft=/\s+\.?key\s*=/;var gt,_t;!function(t){t[t.RENDER=1]="RENDER",t[t.COMPUTED=2]="COMPUTED",t[t.DIRECTIVE=3]="DIRECTIVE"}(gt||(gt={})),function(t){t.Prod="prod",t.Dev="dev"}(_t||(_t={}));const mt=new Map,vt={},yt=new WeakMap,Et=new WeakMap,wt=new WeakMap,bt=new Map,St=new Map,Nt=new WeakMap,Tt=new WeakMap,Ct=new WeakMap,kt=new WeakMap,Mt=new WeakMap,Pt=new WeakMap,At=new WeakMap,xt=new WeakMap,Rt=new WeakMap,Dt=new WeakMap,Ot=new WeakMap,Lt=new WeakMap,It="__data_";function Vt(t){console.error("[CompElem]",t)}function Wt(t,e){console.error(`[CompElem <${t}>]`,e)}function Ht(...t){console.warn("[CompElem]",...t)}function Ut(t,e){console.warn(`[CompElem <${t}>]`,e)}function Bt(t){return e(t).join("-")}function $t(t){return Object.getPrototypeOf(t)}function jt(t){return t===Boolean||s(t,(t=>t===Boolean))}function Ft(t){let e=t;return r(t)&&/(?:^true$)|(?:^false$)/.test(e)?e="true"===e:(n(e)||o(e))&&(e=!0),e}const zt={getNodes(t,e){let s=t.nextSibling;if(!e)return[s];let r=[];for(;s&&s!==e;)r.push(s),s=s?.nextSibling;return r},insertBefore:function(t,e){if(!t.parentNode)return;let s=document.createDocumentFragment();s.append(...e),t.parentNode.insertBefore(s,t)},remove:function(t,e){if(t===e)return void t?.parentNode?.removeChild(t);let s=t.nextSibling;for(;s&&s!==e;)s?.parentNode?.removeChild(s),s=t.nextSibling},clear(t,e){if(!t)return;let s,r=document.createNodeIterator(t,NodeFilter.SHOW_COMMENT);for(r=document.createNodeIterator(t,NodeFilter.SHOW_COMMENT|NodeFilter.SHOW_ELEMENT);s=r.nextNode();)t!==s&&(s instanceof Comment||s instanceof Le&&s.destroy())}};function Gt(t,e){let s=i(t,(t=>t.host&&t.host instanceof Le),"parentNode");if(!s||s.host!==e)return s?s.host:void 0}function Xt(t,e,s){let r=s,n=t?t.call(r):Reflect.get(r[It],e);if(Yt.__collecting&&Yt.__varPathList.push(e),ee.has(n)){let t=re.get(n);return t||(t=new Set,re.set(n,t)),t.add(r.__thisRef),ee.get(n)}if(a(n)&&!l(n)&&!(n instanceof Node)&&!Object.isFrozen(n)){let t=xt.get(r.constructor),s=t?.has(e);n=s||"slots"===e?n:ne(n,r,e)}return n}function Kt(t,e,s){let r=s;if(!r.__inited)return void Reflect.set(r[It],t,e);let n=r[It][t],o=Rt.get(r.constructor),i=o?.get(t);if(i){if(!i.call(r,e,n,[t],e,n))return!0}else if(Object.is(n,e))return!0;qt(r,e,n,t),Qt(r,t),Zt(r,t),Reflect.set(r[It],t,e),r._notify(n,[t]);let a=At.get(r.constructor);a?.has(t)&&r.emit("update:"+t,{value:e})}function qt(t,e,s,r,n,o){let i=$t(t.constructor),a=Ct.get(t.constructor)??Ct.get(i),l=Tt.get(t.constructor)??Tt.get(i),p=Mt.get(t.constructor)??Mt.get(i),f=kt.get(t.constructor)??kt.get(i),g=Nt.get(t.constructor)??Nt.get(i);a?.forEach((i=>{(r===i||c(i,r+".")&&!Object.is(u(t._getPrivateData(),i),u(e,i))||c(r,i+".")&&l?.includes(i)&&!Object.is(u(t._getPrivateData(),i),u(e,i)))&&h(d(f[i]),d(p[i])).forEach((a=>{a&&!0!==g.get(i)&&(t._watchUpdateArgsInNextTick.set(a,{newValue:e,oldValue:s,chain:r.split("."),rootObjNew:n,rootObjOld:o,fullMatch:i===r}),t._watchUpdateSetInNextTick.add(a),g.has(i)&&g.set(i,!0))}))}))}function Qt(t,e){let s=Dt.get(t.constructor);s?.has(e)&&s.get(e)?.forEach((e=>{t._computedUpdateSetInNextTick.add(e)}))}function Zt(t,e){let s=Ot.get(t.constructor);if(!s)return;let r=e.split("."),n="";r.forEach((e=>{n=n?n+"."+e:e,s.has(n)&&(t._cssUpdateInNextTick=!0)}))}const Yt={popDirectiveQ(){return this.__varPathList.reduceRight(((t,e)=>(t.includes(e)||t.unshift(e),t)),[])},start(){this.__collecting=!0,this.__varPathList=[]},end(t,e){t&&e&&t._regSubViewDeps(Yt.popVarPathList(),e),this.__collecting=!1},popVarPathList(){let t=Array.from(new Set(this.__varPathList));return this.__varPathList=[],t},__varPathList:[],__collecting:!1},Jt=new WeakMap,te=new WeakMap,ee=new WeakMap,se=new WeakMap,re=new WeakMap;function ne(t,e,s){if(ee.has(t))return ee.get(t);if(se.has(t)){if(s){let r=Jt.get(e);r||(r=new WeakMap,Jt.set(e,r)),r.set(t,s);let n=re.get(t);n||(n=new Set,re.set(t,n)),n.values().some((t=>t.deref()===e))||n.add(new WeakRef(e))}return t}const r=new Proxy(t,{get(t,s,r){if(!s)return;const n=Reflect.get(t,s,r);if(p(s))return n;if(l(n))return n;if("length"===s&&f(t))return n;if(Yt.__collecting){let t=te.has(r)?h(te.get(r)):[];t.push(s);let e=t.join(".");Yt.__varPathList.push(e)}if(ee.has(n))return ee.get(n);let o=n;if(a(n)&&!l(n)&&!(n instanceof Node)&&!Object.isFrozen(n)){o=ne(n,e);let t=te.has(r)?h(te.get(r)):[];t.push(s),te.set(o,t),ee.set(n,o)}return o},set(t,s,r,n){if(!s)return!1;let o=t[s],i=te.get(n)??[],a=h(i,[s]),l=Rt.get(e.constructor),c=l?.get(a[0]),u=a.length>1,d=r,p=o;if(u&&(p=d=e._getPrivateData()[a[0]]),c){if(!c.call(e,d,p,a,r,o))return!0}else if(Object.is(o,r))return!0;let f=r,g=Reflect.set(t,s,f),_=re.get(n),m=a.join(".");return qt(e,f,o,m,d,p),Qt(e,m),Zt(e,m),oe(e,p,a),_?.forEach((t=>{let e=t.deref();if(!e)return;let s=e._wrapperProp[a[0]],r=a.join(".");r=r.replace(a[0],s),qt(e,f,o,r),Qt(e,r),Zt(e,r),oe(e,p,r.split("."))})),g}});if(te.has(r)||te.set(r,s?[s]:[]),ee.set(t,r),s&&(se.set(r,e),!Jt.has(e))){let t=new WeakMap;t.set(r,s),Jt.set(e,t)}return r}function oe(t,e,s,r,n){let o=g(s);_(s,(r=>{let n=m(s,0,o--);t._notify(e,n)}))}const ie=new Map;class ae{static nextSet=new Set;static nextPending=!1;static next;static flush(){ae.nextPending=!1;let t=Array.from(ae.nextSet);ae.nextSet.clear(),ie.clear(),t.forEach((t=>t())),t=null}static pushNext(t){ae.nextSet.add(t),ae.nextPending||(ae.nextPending=!0,ae.next())}}function le(t){if(1===arguments.length)return(e,s,r)=>{t.required=t.required||!1,t.attribute=!1!==t.attribute,ce(e,s,t,r)};let e=arguments[0],s=arguments[1],r=arguments[2];t={type:void 0,required:!1,attribute:!0},r&&"function"==typeof r.type&&(t=v(r,t),r=void 0),ce(e,s,t,r)}function ce(t,e,s,r){let n;if(y(e[0])||Vt(`Prop '${e}' must be in CamelCase`),!wt.has(t.constructor)){const e={};let s=t.constructor;for(;(s=$t(s))!==Le;)E(e,wt.get(s)??{});n=new Set,w(e,((t,e)=>{if(t.attribute){let t=b(e);n?.add(t)}})),St.set(t.constructor,n),wt.set(t.constructor,e)}if(r&&(r.get&&(s.getter=r.get),r.set&&(s.setter=r.set)),s.attribute){n||(n=St.get(t.constructor));let s=b(e);n?.add(s)}if(S(t.constructor,"observedAttributes")||(t.constructor.observedAttributes=[]),n&&(t.constructor.observedAttributes=d(n)),N(wt.get(t.constructor),e,s),s.hasChanged){let r=Rt.get(t.constructor);r||(r=new Map,Rt.set(t.constructor,r)),r.set(e,s.hasChanged)}if(s.sync){let s=At.get(t.constructor);s||(s=new Set,At.set(t.constructor,s)),s.add(e)}Reflect.defineProperty(t,e,{get(){return Xt(r?.get,e,this)},set(t){r?.set?r.set(t):Kt(e,t,this)}})}(()=>{const t=Promise.resolve(),e=ae.flush;ae.next=()=>{t.then(e)}})();const ue=new Set;function he(t){return St.get(t)??ue}const de=["resize","outside","mutate"],pe=new WeakMap,fe=[],ge=[],_e=[],me=new WeakSet,ve=new ResizeObserver((t=>{for(const e of t){const t=Array.isArray(e.contentBoxSize)?e.contentBoxSize[0]:e.contentBoxSize,s=Array.isArray(e.borderBoxSize)?e.borderBoxSize[0]:e.borderBoxSize;if(!me.has(e.target)){me.add(e.target);continue}let r=pe.get(e.target);r&&r({target:e.target,contentBoxSize:t,borderBoxSize:s,type:"resize"})}}));var ye;!function(t){t.Child="child",t.Tree="tree",t.Attr="attr",t.Char="char"}(ye||(ye={}));const Ee=new WeakMap,we=new MutationObserver((t=>{for(let e=0;e<t.length;e++){const s=t[e];let r=Ee.get(s.target);if(!r)return;let n={target:s.target},o=null;switch(s.type){case"subtree":n.type=ye.Tree,o=r[ye.Tree];break;case"childList":n.type=ye.Child,n.addedNodes=s.addedNodes,n.removedNodes=s.removedNodes,o=r[ye.Child];break;case"attributes":n.type=ye.Attr,n.attributeName=s.attributeName,n.oldValue=s.oldValue,o=r[ye.Attr];break;case"characterData":n.type=ye.Char,n.oldValue=s.oldValue,o=r[ye.Char]}o&&(n.type="mutate",o(n))}}));function be(e,s,r,n,o){if("resize"===e)return function(t,e){if(pe.has(t))return;pe.set(t,e),ve.observe(t);let s=ve;return(e=!1)=>{s.unobserve(t),pe.delete(t),e&&(s=t=null)}}(s,r);if("outside"===e)switch(n[0]){case"mousedown":return function(e,s){return fe.push([e,s]),(r=!1)=>{t.remove(fe,(t=>t[0]===e&&t[1]===s))}}(s,r);case"dblclick":return function(e,s){return _e.push([e,s]),(r=!1)=>{t.remove(_e,(t=>t[0]===e&&t[1]===s))}}(s,r);default:return function(e,s){return ge.push([e,s]),(r=!1)=>{t.remove(ge,(t=>t[0]===e&&t[1]===s))}}(s,r)}else if("mutate"===e)return function(t,e,s){let r=T(s,"child"),n=T(s,"attr"),o=T(s,"char"),i=T(s,"tree"),a=Ee.get(t);if(!a)return a={},Ee.set(t,a),r&&(a[ye.Child]=e),n&&(a[ye.Attr]=e),o&&(a[ye.Char]=e),i&&(a[ye.Tree]=e),we.observe(t,{childList:r,attributes:n,characterData:o,subtree:i}),(e=!1)=>{Ee.delete(t),e&&(t=null)}}(s,r,n)}document.addEventListener("mousedown",(t=>{let e=u(t.composedPath(),0,t.target);fe.forEach((([s,r])=>{s.contains(e)||s.contains(i(e,(t=>t instanceof ShadowRoot),"parentNode")?.host)||r({type:"outside",target:s,modifier:"mousedown",event:t})}))}),!1),document.addEventListener("click",(t=>{let e=u(t.composedPath(),0,t.target);ge.forEach((([s,r])=>{s.contains(e)||s.contains(i(e,(t=>t instanceof ShadowRoot),"parentNode")?.host)||r({type:"outside",target:s,modifier:"click",event:t})}))}),!1),document.addEventListener("dblclick",(t=>{let e=u(t.composedPath(),0,t.target);_e.forEach((([s,r])=>{s.contains(e)||s.contains(i(e,(t=>t instanceof ShadowRoot),"parentNode")?.host)||r({type:"outside",target:s,modifier:"dblclick",event:t})}))}),!1);const Se=/,|^(debounce:.+)|(debounce$)/,Ne=/,|^(throttle:.+)|(throttle$)/,Te={esc:"escape"},Ce=()=>{};function ke(t,e,s,r){let n,o=t.split("."),i=o.shift(),a=o.includes("once"),l=e??Ce;if(n=C(o,(t=>Se.test(t)))){let t=n.split(":");l=k(l,parseInt(t[1])||100)}if(n=C(o,(t=>Ne.test(t)))){let t=n.split(":");l=M(l,parseInt(t[1])||100)}if(a&&(l=P(l)),s instanceof Le&&!o.includes("native"))return s._addEvent(i,e);if(function(t){return de.includes(t)}(i))return be(i,s,l,o);let c=t=>{if(o.includes("prevent")&&t.preventDefault(),o.includes("stop")&&t.stopPropagation(),!o.includes("self")||t.target===t.currentTarget){if(t instanceof MouseEvent){if(o.includes("left")&&0!=t.button)return;if(o.includes("right")&&2!=t.button)return;if(o.includes("middle")&&1!=t.button)return}else if(t instanceof KeyboardEvent){if(A(o,(t=>"ctrl"==t))[0]&&!t.ctrlKey)return;if(A(o,(t=>"alt"==t))[0]&&!t.altKey)return;if(A(o,(t=>"shift"==t))[0]&&!t.shiftKey)return;if(A(o,(t=>"meta"==t))[0]&&!t.metaKey)return;let e=x(o,(t=>Te[t]||t));if(g(e)>0&&!e.includes(t.key.toLowerCase()))return}l(t)}},u={capture:o.includes("capture")||!1,passive:o.includes("passive")||!1};return s.addEventListener(i,c,u),(t=!1)=>{s.removeEventListener(i,c,u),t&&(s=null)}}const Me={boolean:Boolean,string:String,number:Number,object:Object,array:Array,function:Function,undefined:Object},Pe=new WeakMap;let Ae=[],xe=0;const Re=new WeakMap,De={},Oe="slots";class Le extends HTMLElement{static __l_globalRule=document.createElement("style");static defaults(t){Ae=R(t.css,(t=>{if(r(t)){let e=new CSSStyleSheet;return e.replaceSync(t),e}return t instanceof CSSStyleSheet?t:[]})),t.global,w(t,((t,e)=>{D(e[0],/[A-Z]/)}))}#t;#e={};__data_={};#s={};#r;__updateTree;_eventBindList;_listerners={};__docoEventMap;__updateSubViewDeps;_cssUpdateInNextTick=!1;_cssVarOldValueMap;__cssSheets;_watchUpdateSetInNextTick;_watchUpdateArgsInNextTick;_computedUpdateSetInNextTick;get[Symbol.toStringTag](){return this.constructor.name}get cid(){return this.#t}get attrs(){return this.#n}get props(){return this.#o}get renderRoot(){return this.#i?.deref()}get renderRoots(){return this.#a.flatMap((t=>t.deref()??[]))}get parentComponent(){return this.#l?.deref()}get wrapperComponent(){return this.__wrapperComponent?.deref()}get slots(){return De}get slotHooks(){return this.#c}get cssSheets(){return Pe.get(this.constructor)}get globalCssSheet(){return Le.__l_globalRule.sheet}get isMounted(){return this.#u}#n;#o;#i;#a;#l;__wrapperComponent;#h={};#c={};#d={};#u=!1;#p=!1;#f;static get css(){return[]}static get globalCss(){}static get hostCss(){}get cssVars(){return{}}__inited=!1;#g=!1;#_;__thisRef;constructor(...t){super(),this.#t=xe++,this.__updateTree=[],this.__thisRef=new WeakRef(this),this.#_=this.#m.bind(this),1===g(t)&&(this.#o={},O(this.#o,L(t))),Reflect.getOwnPropertyDescriptor(this.constructor.prototype,"slots")||Reflect.defineProperty(this.constructor.prototype,"slots",{get(){return Xt(void 0,"slots",this)},set(t){Kt("slots",t,this)}});let e=bt.get(this.constructor)??bt.get($t(this.constructor));e&&e.sort(((t,e)=>e.priority-t.priority)).forEach((t=>t.create(this))),this.#v=this.#y.bind(this)}insertStyleSheet(t){if(!this.#r)return null;let e;if(r(t)){e=new CSSStyleSheet;try{e.replaceSync(t)}catch(t){}}else{if(this.#r.adoptedStyleSheets.includes(t))return t;e=t}this.#r.adoptedStyleSheets=[...this.#r.adoptedStyleSheets,e];return(Pe.get(this.constructor)??[]).push(e),e}get rootComponent(){let t=this;for(;t.parentComponent;)t=t.parentComponent;return t}#v;connectedCallback(){let t=i(this.parentNode,(t=>t instanceof Le||t.host instanceof Le),"parentNode");this.#l=t?t instanceof Le?new WeakRef(t):new WeakRef(t.host):void 0,Le.__l_globalRule.parentNode||document.head.appendChild(Le.__l_globalRule);let e=u(this.constructor,"hostCss"),s=u(this.constructor,"hostCssSheet");if(e){s||(r(e)?(s=new CSSStyleSheet,s.replaceSync(e)):s=e,N(this.constructor,"hostCssSheet",s));let t=this.__wrapperComponent?.deref()?.shadowRoot??this.#l?.deref()?.shadowRoot??this.ownerDocument;this.__wrapperComponent&&!this.__wrapperComponent.deref()?.shadowRoot?.contains(this)&&(t=i(this,(t=>t instanceof HTMLDocument||t instanceof ShadowRoot),"parentNode")),t&&s&&!t.adoptedStyleSheets.includes(s)&&(t.adoptedStyleSheets=[...t.adoptedStyleSheets,s])}this.__init(),this.__bindEvents()}disconnectedCallback(){this.__unbindEvents()}__bindEvents(){let t=this._eventBindList;w(t,(t=>{let[e,s,r,n]=t;if(n)return;if(!r)return;let o=ke(e,s?s.bind(this):s,r);t[3]=o}));let e=mt.get(this.constructor);g(e)>0&&(this.__docoEventMap||(this.__docoEventMap=new Map),w(e,(({name:t,targetFn:e,fnName:s})=>{if(this.__docoEventMap.has(t+"@"+s))return;let r=e?e(this):this,n=u(this,s),o=ke(t,n?n.bind(this):n,r);this.__docoEventMap.set(t+"@"+s,o)})))}__unbindEvents(){w(this._eventBindList,(t=>{let[,,,e]=t;e&&e(),t[3]=null}));let t=[];w(this.__docoEventMap,((e,s)=>{e&&e(),t.push(s)})),t.forEach((t=>this.__docoEventMap.delete(t)))}beforeDestroyed(){}destroyed(){}get isDestroyed(){return this.#E}#E=!1;destroy(){if(this.#E)return;this.#E=!0;let t=bt.get(this.constructor)??bt.get($t(this.constructor));if(t&&t.sort(((t,e)=>e.priority-t.priority)).forEach((t=>{t.destroy(this)})),this.beforeDestroyed(),this.__unbindEvents(),this._listerners=null,this.__docoEventMap?.clear(),this.__docoEventMap=this._eventBindList=null,Lt.get(this)?.clear(),Lt.delete(this),this._watchUpdateArgsInNextTick?.clear(),this._watchUpdateSetInNextTick?.clear(),this._computedUpdateSetInNextTick?.clear(),this._computedUpdateSetInNextTick=null,this.__cssSheets=null,this.__updateSubViewDeps?.clear(),this.#l){let t=this.#l.deref();t&&I(t.__updateTree,(e=>{e.__destroyed||e.node?.deref()===this&&(e.destroy(t),A(e.parent?e.parent.children:t.__updateTree,(t=>t===e)))}))}w(this.__updateTree,(t=>t?.destroy(this))),w(this.#h,(t=>{Re.delete(t),t.remove()})),w(this.#d,(t=>{w(t,(t=>t.remove()))})),w(this.__data_.slots,((t,e)=>{w(t,(t=>t.remove()))})),this.#w.clear(),this.#d=this.#h=this.#w=this.#e=this.__data_.slots=null,this.remove(),this._wrapperProp=this.#b=this.#i=this.#a=this.#r=this.#s=this.#n=this.#o=this.#i=this.#a=this.#c=this.#v=this.__data_=this.__updateTree=this.#l=this._asyncDirectives=this.__wrapperComponent=null,this.destroyed()}__init(){if(this.__inited)return;if(this.#g)return;this.#g=!0;let t=u(this.constructor,"globalCss");V(t)||!r(t)||u(this.constructor,"_globalRuleInserted")||(Le.__l_globalRule.textContent+=t,N(this.constructor,"_globalRuleInserted",!0));let e=Pe.get(this.constructor),s=e??[];e||(w(u(this.constructor,"css"),(t=>{if(r(t)){let e=new CSSStyleSheet;e.replaceSync(t),s.push(e)}else l(t)||s.push(t)})),Pe.set(this.constructor,s));const n=this.#S();this.propsReady(n);for(const t in n){const e=n[t];this.__data_[t]=e}this.#N(),this.__data_.slots={},Reflect.defineProperty(this.__data_,"__isData",{enumerable:!1,value:!0});let i=$t(this.constructor);if(Ct.get(this.constructor)??Ct.get(i)){this._watchUpdateSetInNextTick=new Set,this._watchUpdateArgsInNextTick=new Map;let t=Nt.get(this.constructor)??Nt.get(i),e=Pt.get(this.constructor)??Pt.get(i);w(e,((e,s)=>{let r=u(this,s);e.forEach((t=>{t.call(this,r,void 0,s)})),t.has(s)&&t.set(s,!0)}))}let a=O({},yt.get(this.constructor),yt.get(i));if(a){this._computedUpdateSetInNextTick=new Set;let t=Dt.get(this.constructor);t?w(a,((t,e)=>{this[It][e]=t.call(this)})):(t=new Map,Dt.set(this.constructor,t),w(a,((e,s)=>{N(e,"key",s),Yt.start(),this[It][s]=e.call(this),Yt.end(),Yt.popVarPathList().forEach((s=>{let r=t.get(s);r||(r=new Set,t.set(s,r)),r.add(e)}))})))}Yt.start();let c=this.render();Yt.end();let h,d=Yt.popVarPathList();this.constructor.prototype._viewDeps||(this.constructor.prototype._viewDeps=d),null===c?(this.#a=[],this.#i=void 0):(this.#r=this.attachShadow({mode:"open"}),this.#r.adoptedStyleSheets=[...Ae,...Pe.get(this.constructor)??[]],h=function(t,e){let s,r=[];if(ns.has(e.constructor)){s=hs(r,ns.get(e.constructor),as(e,t),e)}else{let[n,o]=os(e,t);ns.set(e.constructor,n),s=hs(r,n,o,e)}return e.__updateTree=r,s}(c,this),h&&(this.#a=W(h,(t=>t.nodeType===Node.ELEMENT_NODE)).map((t=>new WeakRef(t))),this.#i=this.#a[0])),this.__inited=!0,this.#T(),w(this.#c,((t,e)=>{this.#C(e)}));const p=this;let f=bt.get(this.constructor)??bt.get($t(this.constructor));f&&f.sort(((t,e)=>e.priority-t.priority)).forEach((t=>{t.beforeMount(this,((t,e)=>(p.__data_[t]=e,p.__data_[t])))})),this.beforeMount(),setTimeout((()=>{if(!this.isDestroyed){if(this.#u=!0,this.#r){Yt.start();let t=this.cssVars;if(Yt.end(),!V(t)){this._cssVarOldValueMap={};let e=Ot.get(this.constructor);e||(e=new Set(Yt.popVarPathList()),Ot.set(this.constructor,e));let s="";w(t,((t,e)=>{let r="--"+b(e).replace(/^-+/,"");(o(t)||H(t))&&(t="initial"),this._cssVarOldValueMap[r]=t,s+=";"+r+":"+t})),this.style.cssText+=s}}h&&this.#r.append(...h),f&&f.forEach((t=>{t.mounted(this,((t,e)=>(p.__data_[t]=e,p.__data_[t])))})),this.#f&&this.#f.forEach((t=>ae.pushNext(t))),this.#p&&ae.pushNext(this.#v),this.__bindEvents(),this.mounted()}}),0)}propsReady(t){}render(){return null}beforeMount(){}mounted(){}#m(t){let e=t.currentTarget,s="";w(this.#h,((t,r)=>{if(t===e)return s=r,!1})),this.__inited&&this.#k(e,s===pt?"":s)}#k(t,e){this.#T();let s=u(this.#e[e],"props");s&&w(this.slots,((t,e)=>{t.filter((t=>t.nodeType===Node.ELEMENT_NODE)).forEach((t=>{t instanceof Le?t._updateProps(s):w(s,((e,s)=>{if(t instanceof HTMLSlotElement){let r=Re.get(t);if(r){let n=t.name||pt,o=r.#e[n];o||(o=r.#e[n]={props:{}}),o.props||(o.props={}),o.props[s]=e,r.#k(t,n)}}else t.setAttribute(s,e)}))}))})),this.slotChange(t,e)}slotChange(t,e){}attributeChangedCallback(t,e,s){if(!this.__inited)return;if(Object.is(s,e))return;"undefined"===s&&(s=null);let r=U(t);if(jt(wt.get(this.constructor)[r].type)){let t=!B(s)&&Ft(s);if(u(this,r)===t)return}this.#M(t,e,s)}shouldUpdate(t){return!0}updated(t){}_notify(t,e,s,r){let n=[];for(let o=0;o<e.length;o++){const i=e[o];n.push(i);let a=u(this,n),l=Bt(n);this.#s[l]={value:a,chain:l===Oe?[Oe]:n,oldValue:t,end:n.length===e.length,subNewValue:s,subOldValue:r}}this.isMounted?ae.pushNext(this.#v):this.#p=!0}#y(){if(g(this.#s)<1)return;if(!this.isMounted)return;const t=this.#s;if(this.#s={},!this.shouldUpdate(t))return;let e=bt.get(this.constructor)??bt.get($t(this.constructor));e&&e.sort(((t,e)=>e.priority-t.priority)).forEach((e=>{e.updated(this,t)}));let s=!1,r=new Set,n=this.constructor.prototype._viewDeps;if(w(t,((t,e)=>{if(!s&&n?.includes(e)&&(s=!0),this.__updateSubViewDeps?.has(e)){let t=this.__updateSubViewDeps.get(e);t&&(r=r.union(t))}})),this._watchUpdateSetInNextTick?.forEach((t=>{let{newValue:e,oldValue:s,chain:r,rootObjNew:n,rootObjOld:o,fullMatch:i}=this._watchUpdateArgsInNextTick.get(t),a=i?e:n,l=i?s:o;t.call(this,a,l,r,e,s)})),this._watchUpdateSetInNextTick?.clear(),this._watchUpdateArgsInNextTick?.clear(),this._computedUpdateSetInNextTick?.forEach((t=>{let e=u(t,"key"),s=this.__data_[e],r=t.call(this);(a(r)||r!==s)&&(this.__data_[e]=r,this._notify(s,[e]))})),this._computedUpdateSetInNextTick?.clear(),this._cssUpdateInNextTick){let t=this.cssVars;w(t,((t,e)=>{let s="--"+b(e).replace(/^-+/,"");this._cssVarOldValueMap[s]!=t&&((o(t)||H(t))&&(t="initial"),this._cssVarOldValueMap[s]=t,this.style.setProperty(s,t+""))}))}this.#i?.deref()&&(s&&ps(this.render(),this,this.__updateTree),g(r)>0&&r.forEach((t=>{fs(t,this,void 0)}))),this.#w.forEach((t=>{this.#C(t)})),this.updated(t)}#S(){let t=wt.get(this.constructor)??wt.get($t(this.constructor)),e=this.attributes,s=this.tagName,r=this.#o,o={};w(e,(({name:e,value:s})=>{if(e[0]===Xe||e[0]===Ke||e[0]===qe||e===Ye||"slot"===e)return;let r=U(e);t&&!t[r]&&(o[e]=s)})),this.#n=this.#n?O(this.#n,o):o;let i={};if(!t)return i;let l=Object.keys(t),c=l.length;for(let o=0;o<c;o++){const c=l[o],h=b(c),d=this.hasAttribute(h);let p,g=t[c],_=S(r,c),m=u(this,c);if(!("_defaultValue"in g)&&(g._defaultValue=m,!g.type)){n(m)&&Wt(s,"Prop '"+c+"' has neither propType nor defaultValue be used for type inference");let t=typeof m;f(m)&&(t="array");let e=Me[t];g.type=e}if(_)p=H(r[c])?m:r[c];else{p=m;let t=e.getNamedItem(h)||e.getNamedItem(Ke+h);t&&(_=!0,p=t.value)}if(g.required&&!_){Wt(s,"Prop '"+c+"' is required");break}p=this.#P(t,c,p,d),g.attribute&&$(p)&&!a(p)&&this.#A(g,c,p),this.__data_[c]=p,i[c]=p,delete this[c]}return i}#A(t,e,s){let r=b(e),n=j(s);jt(t.type)?(n=Ft(s),F(n)?n&&!this.hasAttribute(r)?this.toggleAttribute(r,!0):!n&&this.hasAttribute(r)&&this.toggleAttribute(r,!1):this.getAttribute(r)!==n&&this.setAttribute(r,n)):this.getAttribute(r)!==n&&this.setAttribute(r,n)}#x(t,e){let s=t;try{for(let r=0;r<e.length;r++){const n=e[r];s=n===Boolean?Ft(t):n===Number?Number(t):n===String?String(t):n===Object||n===Array?z(t):n===Date?new Date(t):new n(t)}}catch(e){Wt(this.tagName,"Convert attribute error with "+t)}return s}#P(t,e,n,o){let i=t[e];if(!i)return n;let a=i.isValid,l=i.type,c=f(l)?l:[l],u=i.converter,h=n;if(!s(c,(t=>t===String))&&r(h)&&!B(h))try{h=u?u(h):this.#x(h,c)}catch(t){Wt(this.tagName,`Convert attribute '${e}' error with `+h)}for(let t=0;t<c.length;t++){"Boolean"===c[t].name&&o&&(h=Ft(h))}if(H(h))return h;let d=typeof h,p=!$(h);for(let t=0;t<c.length;t++){const e=c[t];if(D(d,e.name,"i")||h instanceof e||Object.prototype.toString.call(h)===Object.prototype.toString.call(e.prototype)){p=!0;break}}return p||Wt(this.tagName,`Invalid prop '${e}'. expected '${c.map((t=>t.name||t))}' but got '${d}'`),a&&(a.call(this,h,this.__data_)||Wt(this.tagName,`Invalid prop '${e}'. IsValid() check failed`)),h}#N(){let t=Et.get(this.constructor)??Et.get($t(this.constructor));t&&w(t,((e,s)=>{let r=t[s],n=u(this,s);if(r){let t=r.prop;n=t?G(this.__data_[t]):u(this,s)}this.__data_[s]=n,delete this[s]}))}#b=k(this.propsReady,100);_updateProps(t){let e=wt.get(this.constructor);if(!e)return;let s=[];w(t,((t,r)=>{let n=U(r),o=e[n];o&&(t=this.#P(e,n,t),o.attribute&&$(t)&&!a(t)&&s.push([o,n,t]),N(this,n,t))})),O(this.#o,t),s.forEach((([t,e,s])=>{this.#A(t,e,s)})),this.#o&&this.#b(this.#o)}_wrapperProp={};_initProps(t,e){this.#o=E(this.#o||{},t),this.#n=E(this.#n||{},e),w(t,((t,e)=>{if(a(t)){let s=te.get(t);if(s){let t=s.join("-");this._wrapperProp[t]=e;let r=this.wrapperComponent?Et.get(this.wrapperComponent?.constructor):null,n=s[0];if(r&&r[n]){let t=wt.get(this.constructor);N(t,[e,"shallow"],r[n].shallow)}}}}))}_bindSlot(t,e,s){this.#h[e]||(this.#h[e]=t,Re.set(t,this));let r="slotchange",n=ke(r,this.#_,t);if(this._eventBindList.push([r,this.#_,t,n]),!V(s)){let t=this.#e[e];t||(t=this.#e[e]={}),t.props=s}}_bindSlotHook(t,e){this.#c[t]=e}#w=new Set;_updateSlot(t,e,s){let r=this.#h[t],n=this.#c[t];if(!n&&!r)return;let o=this.#e[t];if(e&&(o.props||(o.props={}),o.props[e]=s),n)this.#w.add(t);else{let t=r.assignedElements({flatten:!0});for(let r=0;r<t.length;r++){t[r].setAttribute(e,s+"")}}}#T(){if(!this.#i)return;let t=X(this.#h);if(V(t))return;const e=R(this.childNodes,(t=>t.nodeType===Node.COMMENT_NODE?[]:t instanceof HTMLSlotElement?t.assignedNodes({flatten:!0}):t));let s=K(e,(e=>{if(e.nodeType===Node.TEXT_NODE&&t.includes(pt))return pt;if(e instanceof Element){let s=e.getAttribute("slot")||pt;if(t.includes(s))return s}}));if(V(s))return void(this.slots={});w(s,((t,e)=>{if(e){for(;t.length>0;){let e=t[0];if(!(e.nodeType===Node.TEXT_NODE&&o(e.textContent)||e instanceof HTMLSlotElement&&V(e.assignedNodes({flatten:!0}))))break;t.shift()}for(;t.length>0;){let e=q(t);if(!(e.nodeType===Node.TEXT_NODE&&o(e.textContent)||e instanceof HTMLSlotElement&&V(e.assignedNodes({flatten:!0}))))break;t.pop()}}}));let r={};w(s,((t,e)=>{V(t)||(r[e]=t)})),this.slots=r}#C(t){let e=this.#c[t];if(!e)return;let s=this.#e[t];if(!this.__data_.slots)return;if(!this.__data_.slots[t])return;this.renderAsync(e,u(s,"props"));const r=this._asyncDirectives.get(e);let n=r?.buildView(e(u(s,"props"))),o=Q(d(n),(t=>t.nodeType===Node.COMMENT_NODE));if(o){let e=this.#d[t];if(!V(e))for(let t=0;t<e.length;t++){const s=e[t];s.parentNode?.removeChild(s)}this.#d[t]=o,this.append(...o),this.#w.clear()}}_asyncDirectives=new WeakMap;renderAsync(t,...e){}#M(t,e,s){if(!this.__inited)return;if(he(this.constructor).has(t)){let e=U(t);if(B(s)){let t=wt.get(this.constructor);t&&(s=t[e]._defaultValue)}this._updateProps({[e]:s})}}_regSubViewDeps(t,e){this.__updateSubViewDeps||(this.__updateSubViewDeps=new Map),t.forEach((t=>{let s=this.__updateSubViewDeps.get(t);s||(s=new Set,this.__updateSubViewDeps.set(t,s)),s.add(e)}))}_getPrivateData(){return this.__data_}emit(t,e={},s){s&&(e.event=s),e.target=this,S(this.#n,"emit-native")?this.dispatchEvent(new CustomEvent(t,{bubbles:!1,composed:!1,cancelable:!0,detail:e})):this._listerners[t]&&this._listerners[t](e)}_addEvent(t,e){this._listerners||(this._listerners={}),this._listerners[t]=e}nextTick(t){if(!this.isMounted)return this.#f||(this.#f=[]),void this.#f.push(t);ae.pushNext(t)}forceUpdate(){w(this.__data_,((t,e)=>{this.#s[e]={value:void 0,chain:void 0}})),this.#y()}}class Ie{strings;vars;constructor(t,e){this.strings=h(t),this.vars=e}getKey(){let t=this.vars,e="";return w(this.strings,((s,r)=>{if(ft.test(s))return e=Z(t[r]),!1})),e}getKeys(){let t=this.vars,e=[];for(let s=0;s<this.strings.length;s++){const r=this.strings[s];if(ft.test(r)){let r=Z(t[s]);e.push(r)}}return V(e)&&t.forEach((t=>{if(t instanceof Ie){let s=t.getKey();e.push(s)}})),e}append(t){let e=q(this.strings);return t.strings.forEach(((t,s)=>{0!=s?this.strings.push(t):this.strings[this.strings.length-1]=e+t})),this.vars=h(this.vars,t.vars),this}insert(t,e){let s=e.strings.shift();return this.strings[t]+=s,this.strings.splice(t+1,0,...e.strings),this.vars.splice(t,0,...e.vars),this}getHTML(t){let[e,s]=os(t,this),r=hs([],e,s,t);return Y(r,((t,e)=>t+(e.outerHTML??"")),"")}flatVars(t){let e=h(this.vars),s=this.strings.length-1,r=0;for(let n=0;n<=s;n++){let s=u(e,r,"");if(s instanceof Ie&&s.vars.length>0){let[n,o]=os(t,s);s=n,e.splice(r,1,...o),r+=o.length-1}r++}return e}destroy(){this.strings=this.vars=null}}var Ve,We;!function(t){t.ATTR="attr",t.PROP="prop",t.TEXT="text",t.CLASS="class",t.STYLE="style",t.SLOT="slot",t.TAG="tag"}(Ve||(Ve={})),function(t){t.NONE="NONE",t.REMOVE="REMOVE",t.REPLACE="REPLACE",t.UPDATE="UPDATE",t.APPEND="APPEND"}(We||(We={}));class He{key;varIndex;value;node;attrName;attrTmpl;isText=!1;isDirective=!1;isComponent=!1;isProp=!1;isToggleProp=!1;isPlaceholder;__destroyed=!1;directiveOldValue;children;parent;constructor(t,e,s,r){this.varIndex=t,e&&(this.node=e),s&&(this.attrName=s),r&&(this.attrTmpl=r)}static createFrom(t){let e=new He(t.varIndex,t.node,t.attrName,t.attrTmpl);return e.key=t.key,e.value=t.value,e.isText=t.isText,e.isDirective=t.isDirective,e.isComponent=t.isComponent,e.isProp=t.isProp,e.isToggleProp=t.isToggleProp,e.isPlaceholder=t.isPlaceholder,e}destroy(t){if(this.__destroyed)return;this.__destroyed=!0;let e=this.node,s=this.children;this.parent;if(this.node=this.value=this.directiveOldValue=this.children=this.parent=null,!e)return;let r=s;r?.forEach(((e,s)=>{e.destroy(t)})),e instanceof Le&&e.destroy(),t&&zt.clear(e.deref(),t),e.deref()?.remove()}insert(t){t.parent=this,this.children||(this.children=[]),this.children.push(t)}}const Ue=new WeakMap,Be=new Map;var $e;!function(t){t.AFTER_BEGIN="afterbegin"}($e||($e={}));let je={};function Fe(t,e,s,r,n,o,i,a){let l;if([Ve.TEXT,Ve.SLOT].includes(u(r,"__scope",""))?(Yt.start(),l=r(t,e,s,{renderComponent:n,slotComponent:o,varChain:i}),Yt.end(n,a)):l=r(t,e,s,{renderComponent:n,slotComponent:o,varChain:i}),!l)return;let[c,h]=l;if(c===We.NONE)return;let p=Ue.get(t),f=zt.getNodes(p,t),g=a.children;if(c===We.REMOVE){for(let t=0;t<f.length;t++){const e=f[t];e.remove(),e instanceof Le&&e.destroy()}g?.forEach(((t,e)=>{t.destroy(n)}))}else if(c===We.REPLACE){let e=[];for(let t=0;t<f.length;t++){const e=f[t];e.parentNode?.removeChild(e),e instanceof Le&&e.destroy()}g?.forEach(((t,e)=>{t.destroy(n)}));let s=ds(t,h,n,a,!0);e=d(s);let r=document.createDocumentFragment();r.append(...e),t.parentNode.insertBefore(r,t)}else if(c===We.UPDATE){let e,s={},r=[],o=[];if(h||(h=new Ie([],[])),V(f)){let e=ds(t,h,n,a,!0);return void p.after(...e)}let i={};h instanceof Ie&&h.vars.forEach((t=>{if(t instanceof Ie){const e=t.getKey();i[e]=t,s[e]=!0,o.push(e)}})),f=W(J(f),(t=>t.nodeType===Node.ELEMENT_NODE)),e=W(J(d(e)),(t=>t.nodeType===Node.ELEMENT_NODE));let l={},c="",u={};for(let t=0;t<f.length;t++){let e=f[t],s=e.getAttribute("key");if(!H(s)){if(l[s]){c=s;break}l[s]=e,r.push(s),u[s]=!0}}if(c)return void Vt(`${U(t.nodeValue)} - duplicate key '${c}'`);let _=s,m=[],v=[];w(u,((t,e)=>{_[e]||(v.push(e),delete u[e],A(r,(t=>t===e)))}));let y,E=!1;if(!V(o)){let t=-1,e=[],s=[],n=0,i=0;for(;i<o.length;i++){const a=o[i];let c=r.findIndex((t=>t===a));if(c<0){let t=o[i-1],e=t?l[t]||t:p;m.push({prevNode:e,newkey:a}),n++}else if(c>-1&&c!==i-n){if(t<0||1===Math.abs(t-c)){let t=q(e);e.push({nodeId:a,targetId:0===i?$e.AFTER_BEGIN:t?t.nodeId:o[i-1]})}else s.push({moveGroup:e,moveIndex:i+e.length}),e=[],e.push({nodeId:a,targetId:o[i-1]});t=c}}if(e.length>0&&s.push({moveGroup:e,moveIndex:i+e.length}),s.length>0){E=!0;let t=s.sort(((t,e)=>t.moveGroup.length-e.moveGroup.length));if(t.length<2){let{moveGroup:e}=t[0];if(e.length>1){let t=q(e).targetId;e[e.length-2].nodeId===t&&(e=tt(e))}e.forEach((({targetId:t,nodeId:e})=>{let s,r=l[e];t===$e.AFTER_BEGIN?(s=p,s.after(r)):l[t]&&(s=l[t],s.after(r))}))}else{let e=q(t).moveIndex;1===Math.abs(t[t.length-2].moveIndex-e)&&(t=tt(t)),t.forEach((({moveGroup:t})=>{t.forEach((({targetId:t,nodeId:e})=>{let s,r=l[e];t===$e.AFTER_BEGIN?(s=p,s.after(r)):(s=l[t],s.after(r))}))}))}}}if(v.forEach((t=>{let e=l[t];if(e&&e.parentNode){l[t]=null,e.remove();let s=A(g,(e=>e.key==t));s.forEach((t=>t.destroy(n)))}})),m.length>0&&(y=function(t,e,s,r,n,o){const i=[],a=[],l=[];let c,u=[];t.forEach((t=>{let s=q(u);s&&c===t.prevNode?(s.group||(s.group=[c]),s.group.push(t.newkey)):u.push(t),c=t.newkey;let r=t.newkey;l.push(r),i.push(""),a.push(e[r])})),i.push("");let h=ds(r,new Ie(i,a),s,o,!0),d=new Map;return h.forEach((t=>{const e=t.getAttribute("key");l.includes(e)&&(d.set(e,!0),n[e]=t)})),u}(m,i,n,t,je,a),y.forEach(((e,s)=>{let r=e.newkey,n=je[r],o=e.prevNode;if(e.group){let t=document.createDocumentFragment();t.append(...x(e.group,(t=>je[t]))),n=t}o===t?o.before(n):o===p?o.after(n):"string"==typeof o?je[o].after(n):o.after(n)})),je=null,je={}),h.vars[0]instanceof Ie){let t=[],e=[];w(h.vars,(s=>{e.push(...s.vars),t.push(...x(s.vars,(t=>"1")))})),t.push("1"),h=new Ie(t,e)}if(E||v.length>0||y){const t=K(g,(t=>t.key));let e=[],s=0;o.forEach((r=>{t[r]&&t[r].forEach((t=>{t.varIndex=s++,e.push(t)}))})),et(g,e).forEach((t=>t.destroy(n))),a.children=e}fs(a,n,h)}}let ze=0;function Ge(t,e){let s=t.name||"Di-"+ze++,r=Symbol.for(s);return(...n)=>{let o=t(...n);return(T(e,Ve.TEXT)||T(e,Ve.SLOT))&&Be.set(s,o),N(o,"__scope",e[0]),[r,n,o,t=>{},Yt.popDirectiveQ()]}}const Xe="@",Ke=".",qe="?",Qe="*",Ze=":",Ye="ref",Je="key",ts=/(<\/?)\s*([A-Z][A-Za-z0-9]*)([\s>])/gm,es=/\s+([\.?@*])?((?:[a-zA-Z]*[A-Z][^\s<>="']+))(?=[\s=>])/gm,ss=/<\s*[a-z0-9-]+([^>]*<\!--c_ui-pl_df-->)*[^>]*?(?<!-)>/gims,rs="slot-props",ns=new Map;function os(t,e){let s="",r=h(e.vars),n=e.strings.length-1,o=e.vars.length-1,i=0;for(let a=0;a<=n;a++){const n=e.strings[a];let l=u(r,i,"");if(l instanceof Ie){let[e,s]=os(t,l);l=e,r.splice(i,1,...s),i+=s.length-1}else l=a>o?"":ls;i++,s=s+n+l}let a=0;return s=s.replace(ss,((t,e)=>it(t,ls,(()=>ls.replace("--\x3e","")+a++)))),s=s.replace(_s,"$1><").trim(),s=is(s),[s,r]}function is(t){return r(t)?t=(t=t.replace(es,((t,e,s)=>` ${e??""}${b(s)}`))).replace(ts,((t,e,s,r)=>e+vt[s]+r)):t+""}function as(t,e){let s=h(e.vars),r=e.strings.length-1;for(let n=0;n<=r;n++){let r=u(e.vars,n,"");if(r instanceof Ie){let e=as(t,r);s.splice(n,1,...e)}}return s}const ls="\x3c!--c_ui-pl_df--\x3e",cs="\x3c!--c_ui-pl_df",us=/<!--c_ui-pl_df\d*(-->)?/;function hs(t,e,s,r){const n=document.createElement("div");n.innerHTML=e;let o=r._eventBindList;o||(o=r._eventBindList=[]);const i=document.createNodeIterator(n,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_COMMENT);let a,l,u=0,h=null,_="";for(;a=i.nextNode();){if(l&&!l.contains(a)&&(l=void 0),a instanceof HTMLElement||a instanceof SVGElement){a instanceof Le&&(l=a);let e={},n=d(a.attributes);for(let i=0;i<n.length;i++){const d=n[i];let{name:g,value:m}=d;if(g!==rs)if(c(g,cs)){let e=s[u];if(f(e)&&p(e[0])){let[,s,n,o,i]=e;o(Ve.TAG);let c=new He(u,new WeakRef(a));c.isDirective=!0,c.value=e,c.isComponent=!!l,t.push(c),h&&h?.contains(a)&&(c.key=_),u++,n(a,s,void 0,{renderComponent:r,slotComponent:l,varChain:i})}a.removeAttribute(g)}else if(g[0]!==Xe)if(g!==Ye)if(g!==Je){if(us.test(m)){let n=s[u],o=new He(u,new WeakRef(a),g.replace(/\.|\?|@/,""),m);if(o.isComponent=!!l,h&&h?.contains(a)&&(o.key=_),g[0]===Ke||g[0]===qe||g[0]===Qe){if(f(n)&&p(n[0])){let[,t,e,s,i]=n;s(Ve.PROP),e(a,t,void 0,{renderComponent:r,slotComponent:l,varChain:i,attrName:g.substring(1)}),o.value=n,o.isDirective=!0}else if(g[0]===qe){o.isToggleProp=!0,o.value=!!n;let t=g.substring(1);o.value&&a.setAttribute(t,n)}else if(g[0]===Qe){o.value=n;let t=g.substring(1);const[e,s]=t.split(Ze);let r=e;switch(s){case"camel":r=U(r);break;case"kebab":r=b(r);break;case"snake":r=at(r)}o.attrName=r,a.setAttribute(r,n)}else{let t=U(g.substring(1));o.value=n,o.isProp=!0,e[t]=n}a.removeAttribute(g),n=""}else{let t,e;if(o.value=n,f(n)&&p(n[0])){Ve.ATTR,"class"===g?Ve.CLASS:"style"===g&&Ve.STYLE;let[,s,r,i]=n;o.isDirective=!0,o.attrName=g,e=s,t=r,n=""}m=ot(m,us,n),d.value=m,$(m)&&a.setAttribute(g,m),t&&t(a,e,void 0,{renderComponent:r,slotComponent:l})}t.push(o),u++}}else{let e=s[u];a.setAttribute(g,e);let r=new He(u);r.isPlaceholder=!0,h&&h?.contains(a)&&(r.key=_),t.push(r),u++,h=a,_=e,t.length>0&&t.forEach((t=>{t.key=t.key??e}))}else{if(us.test(m)){let e=s[u],r=new He(u);r.isPlaceholder=!0,h&&h?.contains(a)&&(r.key=_),t.push(r),u++,e.__setRef(new WeakRef(a))}a.removeAttribute(g)}else{let e;if(us.test(m)){let r=new He(u);r.isPlaceholder=!0,h&&h?.contains(a)&&(r.key=_),t.push(r),e=s[u],u++}let r=g.substring(1);o.push([r,e,a]),a.removeAttribute(g)}}a instanceof Le?(m=r,a.__wrapperComponent=new WeakRef(m),g(e)>0&&a._initProps(e)):a instanceof HTMLSlotElement&&r._bindSlot(a,a.name||"default",e)}else{let e=a;if(`\x3c!--${e.nodeValue}--\x3e`!==ls)continue;let n=new He(u,new WeakRef(a));h&&h?.contains(a)&&(n.key=_),t.push(n),n.isComponent=!!l,n.isText=!0;let o=s[u];if(f(o)&&p(o[0])){const t=Symbol.keyFor(o[0]);let s;s=document.createComment(`compelem-${r.tagName}-${t}-start`),e.parentNode.insertBefore(s,e),e.nodeValue=`compelem-${r.tagName}-${t}-end`,e._diName=t,Ue.set(e,s),n.isDirective=!0,n.value=o;let i=l?Ve.SLOT:Ve.TEXT,[,a,c,u,h]=o;u(i),n.directiveOldValue=[a,h],Yt.start();let d=c(e,a,void 0,{renderComponent:r,slotComponent:l,varChain:h});if(Yt.end(r,n),d){let t=ds(e,d[1],r,n),s=t.length;t&&s>0&&zt.insertBefore(e,Array.from(t))}o=void 0}else n.value=o,n.node=null;if(u++,!n.isDirective){let t=Z(o??""),s=document.createTextNode(t);e.parentNode.insertBefore(s,e),e.remove(),a=s,n.node=new WeakRef(s)}}h&&!h.contains(a)&&h!==a&&(h=null,_="")}var m;return n.childNodes}function ds(t,e,s,r,n=!1){let[o,i]=os(s,e),a=[],l=hs(a,o,i,s);return n&&s.__bindEvents(),a.forEach((t=>{r.insert(t)})),l}function ps(t,e,s,r){if(o(st(t.strings)))return;let n=t.flatVars(e);for(let t=0;t<s.length;t++){const r=s[t];let o=r.varIndex;if(o<0)continue;if(r.isPlaceholder)continue;if(r.__destroyed)continue;let i=r.value,l=n,c=r.node.deref();if(!c)continue;let h=rt(o,"-");for(let e=0;e<h.length;e++){const s=h[e];l=u(l,s),l&&l.vars&&t<h.length-1&&(l=l.vars)}if(!a(i)&&i===l)continue;let d=c;if(r.isDirective){let[,t,s,,n]=r.value;if(!f(l))continue;let o=Gt(c,e),[,i]=l;Fe(c,i,t,s,e,o,n,r)}else if(r.isToggleProp){if(!!l===i)continue;d.toggleAttribute(r.attrName,!!l),N(d,r.attrName,!!l)}else if(r.isProp){if(!a(l)&&l===i)continue;c instanceof Le?c._updateProps({[r.attrName]:l}):c instanceof HTMLSlotElement&&e._updateSlot(c.getAttribute("name")||"default",r.attrName,l)}else if(r.attrName){if(!nt(i,l))switch(r.attrName){case"value":if(c instanceof HTMLInputElement){c.value=l;break}default:c.setAttribute(r.attrName,ot(r.attrTmpl,us,l+""))}}else if(r.isText){r.node.deref().textContent=Z(l??"")}r.value=l}}function fs(t,e,s,r){if(!t)return;let n=t.node.deref();const o=Be.get(n._diName);let i=Gt(n,e);const[a,l]=t.directiveOldValue;if(!s){let r=o(n,t.value[1],a,{renderComponent:e,slotComponent:i,varChain:l});if(!r)return;s=r[1]}if(s){if(s.vars[0]instanceof Ie){let t=[],e=[];w(s.vars,(s=>{e.push(...s.vars),t.push(...x(s.vars,(t=>"1")))})),t.push("1"),s=new Ie(t,e)}ps(s,e,t.children)}}function gs(t,...e){return new Ie(r(t)?[t]:t,e)}const _s=/([a-z0-9"'])\s*>\s*</gim;class ms{#R;get current(){return this.#R?.deref()}__setRef(t){this.#R=t}}function vs(){return new ms}var ys;!function(t){t.CLASS="class",t.FIELD="field",t.METHOD="method"}(ys||(ys={}));class Es{static get priority(){return 0}created(t,...e){}beforeMount(t,e,...s){}mounted(t,e,...s){}updated(t,e){}beforeDestroy(t,...e){}}class ws{metadata;decorator;key;priority=0;constructor(t,e,s){this.metadata=e,this.decorator=new s(...t),this.priority=u(s,"priority",0)}dispose(){this.metadata=null,this.decorator=null}create(t){let e,s=this.decorator.targets,r=this.metadata[1];a(r)&&$(u(r,"configurable"))?e=ys.METHOD:n(this.metadata[1])&&(e=ys.FIELD),!V(s)&&e&&s.includes(e)?this.decorator.created(t,...this.metadata):Vt(`Decorator '${this.decorator.constructor.name}' is out of targets, expect '${s.join(",")}' bug got '${e}'`)}beforeMount(t,e){this.decorator.beforeMount(t,e,...this.metadata)}mounted(t,e){this.decorator.mounted(t,e,...this.metadata)}updated(t,e){this.decorator.updated(t,e)}destroy(t){this.decorator.beforeDestroy(t,...this.metadata)}}function bs(t){return(...e)=>(...s)=>{let r=s[0].constructor,n=bt.get(r);if(!bt.has(r)){let t=Object.getPrototypeOf(r);n=t?h(bt.get(t)??[]):[],bt.set(r,n)}let o=new ws(e,s.splice(1),t);return n?.push(o),o}}function Ss(t){return(...e)=>{if(!e||e.length<1)return;let s=e[0].constructor,r=bt.get(s);if(!bt.has(s)){let t=Object.getPrototypeOf(s);r=t?h(bt.get(t)??[]):[],bt.set(s,r)}let n=new ws([],e.splice(1),t);return r?.push(n),n}}function Ns(t,e,s){return s.get||Vt(`Computed '${e}' must be a getter`),yt.has(t.constructor)||yt.set(t.constructor,{}),yt.get(t.constructor)[e]=s.get,delete t[e],Reflect.defineProperty(t,e,{get(){return Yt.__collecting&&Yt.__varPathList.push(e),Reflect.get(this[It],e)}}),Reflect.getOwnPropertyDescriptor(t,e)}const Ts=bs(class extends Es{static get priority(){return Number.MAX_VALUE}created(t,e,...s){let r=u(t,e);N(t,e,k(r,this.wait,this.immediate)),N(t,e+"_$__",r)}beforeDestroy(t,e){N(t,e,null),N(t,e+"_$__",null)}get targets(){return[ys.METHOD]}wait;immediate;constructor(t,e=!1){super(),this.wait=t,this.immediate=e}});function Cs(t,e){return(s,r,n)=>{if(!mt.has(s.constructor)){let t=[],e=s.constructor;for(;(e=$t(e))!==Le;)t=h(t,mt.get(e)??[]);mt.set(s.constructor,t)}mt.get(s.constructor)?.push({name:t,targetFn:e,fnName:r})}}const ks=bs(class extends Es{static get priority(){return Number.MAX_VALUE}created(t,e,s,...r){let n=lt(u(t,s),t);N(t,s,P(n)),N(t,s+"_$__",n)}beforeDestroy(t,e){N(t,e,null),N(t,e+"_$__",null)}get targets(){return[ys.METHOD]}});var Ms;!function(t){t.ONCE="once"}(Ms||(Ms={}));const Ps=new WeakMap;class As extends Es{static get priority(){return Number.MAX_VALUE}get targets(){return[ys.FIELD]}selector;cache;constructor(t,e){super(),this.selector=t,this.cache=e}static getKey(t){return t}getter(t){let e=t?.shadowRoot?.querySelector(this.selector),s=Ps.get(t);s||(s=new Map,Ps.set(t,s)),s.set(this.selector,e)}mounted(t,e,s,...r){const n=this;let o=new WeakRef(t);Reflect.defineProperty(t,s,{configurable:!0,get(){let t=o.deref();return Ps.has(t)&&Ps.get(t)?.has(n.selector)&&n.cache===Ms.ONCE||n.getter(t),Ps.get(t)?.get(n.selector)}})}beforeDestroy(t,e){Ps.get(t)?.clear(),Ps.delete(t)}updated(t,e){this.cache!==Ms.ONCE&&this.getter(t)}}const xs=bs(As),Rs=bs(class extends As{getter(t){let e=t.shadowRoot?.querySelectorAll(this.selector),s=Ps.get(t);s||(s=new Map,Ps.set(t,s)),s.set(this.selector,e)}});function Ds(t){if(1===arguments.length)return(e,s)=>{Os(e,s,t)};Os(arguments[0],arguments[1],{prop:""})}function Os(t,e,s){if(!Et.has(t.constructor)){const e={};let s=t.constructor;for(;(s=$t(s))!==Le;)E(e,Et.get(s)??{});Et.set(t.constructor,e)}if(s.shallow=s.shallow||!1,N(Et.get(t.constructor),e,s),s.hasChanged){let r=Rt.get(t.constructor);r||(r=new Map,Rt.set(t.constructor,r)),r.set(e,s.hasChanged)}if(s.shallow){let s=xt.get(t.constructor);s||(s=new Set,xt.set(t.constructor,s)),s.add(e)}Reflect.defineProperty(t.constructor.prototype,e,{get(){return Xt(void 0,e,this)},set(t){Kt(e,t,this)}})}function Ls(t,e,s){Os(t.prototype,e,s||{prop:""})}function Is(t){return e=>{e&&(vt[e.name]=t,customElements.define(t,e))}}const Vs=bs(class extends Es{static get priority(){return Number.MAX_VALUE}created(t,e,...s){let r=u(t,e);N(t,e,M(r,this.wait)),N(t,e+"_$__",r)}beforeDestroy(t,e){N(t,e,null),N(t,e+"_$__",null)}get targets(){return[ys.METHOD]}wait;constructor(t){super(),this.wait=t}});function Ws(t,e){return(s,r)=>{let n=Mt.get(s.constructor),o=kt.get(s.constructor),i=Nt.get(s.constructor),a=Tt.get(s.constructor),l=Ct.get(s.constructor),c=Pt.get(s.constructor);if(!l){l=[],Ct.set(s.constructor,l),a=[],Tt.set(s.constructor,a),i=new Map,Nt.set(s.constructor,i),n={},Mt.set(s.constructor,n),o={},kt.set(s.constructor,o),c={},Pt.set(s.constructor,c);let t=$t(s.constructor);for(;t;)Ct.has(t)&&(l.push(...Ct.get(t)),a.push(...Tt.get(t)),Nt.get(t)?.forEach(((t,e)=>{i.set(e,t)})),O(n,Mt.get(t)),O(o,kt.get(t)),O(c,Pt.get(t))),t=$t(t)}(f(t)?t:[t]).forEach((t=>{let h=s[r];u(e,"once",!1)&&i.set(t,!1);let d=u(e,"deep",!1);if(l.push(t),d?(n[t]=n[t]??new Set,n[t].add(h),a.push(t)):(o[t]=o[t]??new Set,o[t].add(h)),u(e,"immediate",!1)){let e=c[t];e||(e=c[t]=new Set),e.add(h)}}))}}const Hs=["key"],Us=Ge((function(t){return(t,[e],s)=>{let r=t;if(s)w(e,((t,e)=>{r.setAttribute(e,t)}));else if(r instanceof Le){let t={},s={},n=wt.get(r.constructor);w(e,((e,r)=>{if(Hs.includes(r))return;let o=U(r);(n?n[o]:void 0)?t[r]=e:s[r]=e+""})),r._initProps(t,s)}else w(e,((t,e)=>{r.setAttribute(e,t)}))}}),[Ve.TAG]),Bs=new WeakMap,$s=Ge((function(t){return(t,[e],s,{renderComponent:n})=>{let o=[];if(f(e)?o=J(e):a(e)?o=R(e,((t,e)=>t?e:[])):r(e)&&(o=e.split(" ")),o.length<1&&!s)return;let i=t;if(Bs.get(i)&&Bs.get(i).length===o.length&&ct(Bs.get(i),o))return;let l=Bs.get(i);w(l,(t=>{i.classList.remove(t)})),w(o,(t=>{i.classList.add(t)})),l=h(o),Bs.set(i,l)}}),[Ve.CLASS]),js=new WeakMap,Fs=new WeakMap,zs=Ge((function(t,e){return(t,e,s,{varChain:r})=>{let n=t,o=function(t,e,s){let r=x(t,((t,s)=>e(t,s)));if(r.length<1){let t=new Ie([],[]);return Fs.set(s,t),t}let n=[],o=[];const i=[],a=[];for(let t=0;t<r.length;t++){const e=r[t];let s=q(o),l=e.vars,c=!0,u=e.strings;for(let t=0;t<u.length;t++){const e=u[t];if(ft.test(e)){let e=l[t]+"";if(n.includes(e))return void Vt(`forEach - duplicate key '${e}'`);n.push(e),c=!1}0==t&&s?o[o.length-1]=s+e:o.push(e)}if(c)return void Vt("forEach - missing 'key' prop");let h=q(i);h&&u.length>0&&(i[i.length-1]=j(h)+u.shift()),i.push(""),a.push(e)}i.push("");let l=new Ie(i,a);return Fs.set(s,l),l}(e[0],e[1],n);if(s&&s[0]){const s=js.get(n);let r=Ue.get(t),i=zt.getNodes(r,t);if(V(i)&&(!e||V(e[0])))return[We.NONE,o];if(s&&ct(s,e[0])&&s.length===e[0].length)return[We.NONE,o]}return js.set(n,ut(e[0])),s?[We.UPDATE,o]:[We.APPEND,o]}}),[Ve.TEXT,Ve.SLOT]);let Gs=document.createElement("div");const Xs=Ge((function(t){return(t,e,s,{renderComponent:r,slotComponent:n})=>{s&&e[0]==s[0]||H(e[0])||(Gs.innerHTML=is(e[0]),t.after(...Gs.childNodes))}}),[Ve.TEXT,Ve.SLOT]),Ks=Ge((function(t){return(t,e,s,{renderComponent:r,slotComponent:n})=>{s&&e[0]==s[0]||H(e[0])||(t.innerHTML=is(e[0]))}}),[Ve.TAG]),qs=new WeakMap,Qs=Ge((function(t,e,s){return(t,[e,s,r],n,{renderComponent:o})=>{let i=t;if(n){if(!!e==!!n[0]){let t=qs.get(i);return[We.NONE,t.call(o,e)]}let t=e?s:r;return qs.set(i,t),[We.REPLACE,t.call(o,e)]}{let t=e?s:r;return qs.set(i,t),[We.APPEND,t.call(o,e)]}}}),[Ve.TEXT,Ve.SLOT]),Zs=Ge((function(t,e){return(t,[e,s],r)=>r?e===r[0]?[We.NONE,e?s():gs``]:e?[We.REPLACE,e?s():gs``]:[We.REMOVE]:[We.APPEND,e?s():gs``]}),[Ve.TEXT,Ve.SLOT]);var Ys;!function(t){t.CHANGE="change",t.INPUT="input"}(Ys||(Ys={}));const Js=Ge((function(t,s="value",n){return(t,[s,n,o],i,{varChain:l,renderComponent:c})=>{n=n??"value";const h=t;if(i){const t=i[0],e=s;let r=u(h,n);if(!a(e)&&Object.is(e,t)&&Object.is(r,e))return;if(h instanceof Le)h._updateProps({[n]:e});else if(h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement){if(h.setAttribute(n,e+""),h instanceof HTMLSelectElement){let t=C(h.querySelectorAll("option"),(t=>t.value==e));t&&(t.selected=!0)}}else if(h instanceof HTMLInputElement){if(h.value==e)return;switch(h.type){case"checkbox":case"radio":e?h.setAttribute("checked",""):h.removeAttribute("checked");break;case"text":case"email":case"number":case"password":case"search":case"tel":case"url":h.setAttribute(n,e+""),N(h,n,e);break;default:h.setAttribute(n,e+"")}}return}let d;d=r(o)?e(o)[0]:q(l);const p=rt(d,".")[0];p in c||c._wrapperProp[p]||Vt(`model - property '${p}' is not defined on the instance of `+c.tagName);let f=c._eventBindList;if(a(s)||j(s)||(s=""),h instanceof Le){h._initProps({[n]:s});let t="update:"+n;f.push([t,function(t){let e=this,s=e._wrapperProp[p];!(p in e)&&s&&u(e.wrapperComponent,p)===u(e,s)&&(e=e.wrapperComponent||e),N(e,d,t.value)},h])}else if(h instanceof HTMLTextAreaElement){h.setAttribute(n,s+"");let t="input";f.push([t,function(t){let e=t.target;N(this,d,e.value)},h])}else if(h instanceof HTMLInputElement){let t="",e="";switch(h.type){case"checkbox":case"radio":t="checked",e="change";break;default:t="value",e="input"}h.setAttribute(n??t,s+""),f.push([e,function(t){let e=t.target;N(this,d,e.value)},h])}else h instanceof HTMLSelectElement&&(h.setAttribute(n,s+""),f.push(["change",function(t){let e=t.target,s=this,r=s._wrapperProp[p];!(p in s)&&r&&u(s.wrapperComponent,p)===u(s,r)&&(s=s.wrapperComponent||s),N(s,d,e.value)},h]))}}),[Ve.TAG]),tr=new WeakMap,er=Ge((function(t,e){return(t,[e,s],r)=>{if(r&&e===r[0])return;let n=t;if(!tr.has(n)){let t=n.style.display;tr.set(n,"none"==t?"unset":t)}n.style.display=e?tr.get(n):"none",s&&s(n,e)}}),[Ve.TAG]),sr=Ge((function(t,e){return(t,[e,s],r,{renderComponent:n,slotComponent:o})=>{r||(e=e.bind(n),o._bindSlotHook(s||"default",e))}}),[Ve.SLOT]);class rr{static getCssText(t,e=!1){return r(t)?t:st(x(t,((t,s)=>s.startsWith("--")?s+":"+t+(e?" !important":""):b(s)+":"+t+(e?" !important":""))),";")+";"}static setStyle(t,e){if(r(t)&&!j(t))return;let s=rr.getCssText(t);e.style.cssText=s}}const nr=Ge((function(...t){return(t,e,s,{renderComponent:r})=>{let n=t,o=Y(e,((t,e)=>t+rr.getCssText(e)),""),i=J(o.split(";").map((t=>t.split(":")[0]))),a=J(n.style.cssText.split(";")),l=Q(a,(t=>i.some((e=>t.trim().startsWith(e)))));n.style.cssText=o+l.join(";")}}),[Ve.STYLE]),or=Ge((function(t){return(t,e,s,{renderComponent:r,varChain:n,attrName:o})=>{const i=t;if(s)return void(nt(e,s)||i._updateProps({[o]:e[0]}));let a=q(n);i._initProps({[o]:e[0]}),i.addEventListener("update:"+o,(t=>{N(r,a,t.detail.value)}))}}),[Ve.PROP]),ir=Ge((function(t,e){return(t,[e,s],r)=>{let n=()=>gs``,o=[],i=[];w(s,((t,e)=>{if(l(t))o.push(e),i.push(t);else{let e=t[0],s=t[1];o.push(e),i.push(s)}"default"===e&&(n=t)}));let a=ht(o,(t=>l(t)?t(e):t==e));return r?[We.REPLACE,dt(i[a]??n)]:[We.APPEND,dt(i[a]??n)]}}),[Ve.TEXT,Ve.SLOT]);export{Le as CompElem,rr as CssHelper,Ue as DI_COMMENT_START_NODE_MAP,Es as Decorator,ys as DecoratorType,ws as DecoratorWrapper,We as DirectiveUpdateTag,zt as DomUtil,Ve as EnterPointType,Ys as ModelTriggerType,Ms as QueryCache,Ie as Template,Be as TextOrSlotDirectiveExecutorMap,He as UpdatePoint,he as _getObservedAttrs,$t as _getSuper,Bt as _toUpdatePath,Us as bind,os as buildHTML,$s as classes,Ns as computed,vs as createRef,Ts as debounced,bs as decorator,Ss as decoratorWithNoArgs,Ge as directive,Cs as event,zs as forEach,Ft as getBooleanValue,Gt as getSlotComponent,gs as html,Xs as htmlC,Ks as htmlD,Qs as ifElse,Zs as ifTrue,jt as isBooleanProp,Ls as makeState,Js as model,ks as onced,le as prop,xs as query,Rs as queryAll,er as show,Vt as showError,Wt as showTagError,Ut as showTagWarn,Ht as showWarn,sr as slot,Ds as state,nr as styles,or as sync,Is as tag,Vs as throttled,Fe as updateDirective,Ws as watch,ir as when};