compelem 0.20.0 → 0.20.2

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