@htmlplus/element 3.2.5 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,3 +1,2120 @@
1
- export { B as Bind, C as Consumer, D as Debounce, m as Direction, E as Element, n as Event, H as Host, I as IsRTL, L as Listen, M as Method, p as Property, P as Provider, Q as Query, r as QueryAll, S as Slots, u as State, v as Style, W as Watch, c as classes, d as direction, a as dispatch, g as getConfig, h as host, i as isCSSColor, e as isRTL, j as off, o as on, q as query, f as queryAll, l as setConfig, s as slots, t as toCSSColor, b as toCSSUnit, k as toUnit } from './client-D1N1nBuh.js';
2
- import 'change-case';
3
- import './constants.js';
1
+ import { kebabCase, pascalCase } from 'change-case';
2
+ import { API_HOST, STATIC_TAG, API_STACKS, API_REQUEST, API_CONNECTED, LIFECYCLE_UPDATE, STATIC_STYLE, API_STYLE, LIFECYCLE_UPDATED, API_RENDER_COMPLETED, METHOD_RENDER, TYPE_BOOLEAN, TYPE_NUMBER, TYPE_NULL, TYPE_DATE, TYPE_ARRAY, TYPE_OBJECT, TYPE_UNDEFINED, TYPE_STRING, KEY, LIFECYCLE_CONNECTED, LIFECYCLE_DISCONNECTED, LIFECYCLE_CONSTRUCTED, LIFECYCLE_ADOPTED, LIFECYCLE_READY } from './constants.js';
3
+
4
+ /**
5
+ * Indicates the host of the element.
6
+ */
7
+ const host = (target) => {
8
+ try {
9
+ return target[API_HOST]();
10
+ }
11
+ catch {
12
+ return target;
13
+ }
14
+ };
15
+
16
+ const outsides = [];
17
+ /**
18
+ * TODO
19
+ */
20
+ const dispatch = (target, type, eventInitDict) => {
21
+ const event = new CustomEvent(type, eventInitDict);
22
+ host(target).dispatchEvent(event);
23
+ return event;
24
+ };
25
+ /**
26
+ * TODO
27
+ */
28
+ const on = (target, type, handler, options) => {
29
+ const element = host(target);
30
+ if (type != 'outside') {
31
+ return element.addEventListener(type, handler, options);
32
+ }
33
+ const callback = (event) => {
34
+ !event.composedPath().some((item) => item == element) && handler(event);
35
+ };
36
+ type = 'ontouchstart' in window.document.documentElement ? 'touchstart' : 'click';
37
+ on(document, type, callback, options);
38
+ outsides.push({
39
+ callback,
40
+ element,
41
+ handler,
42
+ options,
43
+ type
44
+ });
45
+ };
46
+ /**
47
+ * TODO
48
+ */
49
+ const off = (target, type, handler, options) => {
50
+ const element = host(target);
51
+ if (type != 'outside') {
52
+ return element.removeEventListener(type, handler, options);
53
+ }
54
+ const index = outsides.findIndex((outside) => {
55
+ return outside.element == element && outside.handler == handler && outside.options == options;
56
+ });
57
+ const outside = outsides[index];
58
+ if (!outside)
59
+ return;
60
+ off(document, outside.type, outside.callback, outside.options);
61
+ outsides.splice(index, 1);
62
+ };
63
+
64
+ const isEvent = (input) => {
65
+ return !!input?.match(/on[A-Z]\w+/g);
66
+ };
67
+
68
+ const toEvent = (input) => {
69
+ return input?.slice(2).toLowerCase();
70
+ };
71
+
72
+ const updateAttribute = (target, key, value) => {
73
+ const element = host(target);
74
+ if ([undefined, null, false].includes(value)) {
75
+ element.removeAttribute(key);
76
+ }
77
+ else {
78
+ element.setAttribute(key, value === true ? '' : value);
79
+ }
80
+ };
81
+
82
+ const symbol = Symbol();
83
+ const attributes$2 = (target, attributes) => {
84
+ const element = host(target);
85
+ const prev = element[symbol] || {};
86
+ const next = Object.assign({}, ...attributes);
87
+ const prevClass = (prev.class || '').split(' ');
88
+ const nextClass = (next.class || '').split(' ');
89
+ const newClass = element.className
90
+ .split(' ')
91
+ .filter((key) => !prevClass.includes(key) && !nextClass.includes(key))
92
+ .concat(nextClass)
93
+ .filter((key) => key)
94
+ .join(' ');
95
+ updateAttribute(element, 'class', newClass || undefined);
96
+ if (prev.style || next.style)
97
+ element.setAttribute('style', next.style || '');
98
+ for (const key in prev)
99
+ isEvent(key) && off(element, toEvent(key), prev[key]);
100
+ for (const key in next) {
101
+ if (['class', 'style'].includes(key))
102
+ continue;
103
+ if (isEvent(key))
104
+ on(element, toEvent(key), next[key]);
105
+ else
106
+ updateAttribute(element, kebabCase(key), next[key]);
107
+ }
108
+ element[symbol] = { ...next };
109
+ };
110
+
111
+ const call = (target, key, ...args) => {
112
+ return target[key]?.apply(target, args);
113
+ };
114
+
115
+ const typeOf = (input) => {
116
+ return Object.prototype.toString
117
+ .call(input)
118
+ .replace(/\[|\]|object| /g, '')
119
+ .toLowerCase();
120
+ };
121
+
122
+ /**
123
+ * TODO
124
+ */
125
+ const classes = (input, smart) => {
126
+ const result = [];
127
+ switch (typeOf(input)) {
128
+ case 'array': {
129
+ for (const item of input) {
130
+ result.push(classes(item, smart));
131
+ }
132
+ break;
133
+ }
134
+ case 'object': {
135
+ const keys = Object.keys(input);
136
+ for (const key of keys) {
137
+ const value = input[key];
138
+ const name = kebabCase(key);
139
+ const type = typeOf(value);
140
+ if (!smart) {
141
+ value && result.push(name);
142
+ continue;
143
+ }
144
+ switch (type) {
145
+ case 'boolean': {
146
+ value && result.push(`${name}`);
147
+ break;
148
+ }
149
+ case 'number':
150
+ case 'string': {
151
+ result.push(`${name}-${value}`);
152
+ break;
153
+ }
154
+ }
155
+ }
156
+ break;
157
+ }
158
+ case 'string': {
159
+ result.push(input);
160
+ break;
161
+ }
162
+ }
163
+ return result.filter((item) => item).join(' ');
164
+ };
165
+
166
+ const merge = (target, ...sources) => {
167
+ for (const source of sources) {
168
+ if (!source)
169
+ continue;
170
+ if (typeOf(source) != 'object') {
171
+ target = source;
172
+ continue;
173
+ }
174
+ for (const key of Object.keys(source)) {
175
+ if (target[key] instanceof Object &&
176
+ source[key] instanceof Object &&
177
+ target[key] !== source[key]) {
178
+ target[key] = merge(target[key], source[key]);
179
+ }
180
+ else {
181
+ target[key] = source[key];
182
+ }
183
+ }
184
+ }
185
+ return target;
186
+ };
187
+
188
+ /**
189
+ * TODO
190
+ */
191
+ const getConfig = (namespace) => {
192
+ return globalThis[`$htmlplus:${namespace}$`] || {};
193
+ };
194
+ /**
195
+ * TODO
196
+ */
197
+ const getConfigCreator = (namespace) => () => {
198
+ return getConfig(namespace);
199
+ };
200
+ /**
201
+ * TODO
202
+ */
203
+ const setConfig = (namespace, config, options) => {
204
+ const previous = options?.override ? {} : globalThis[`$htmlplus:${namespace}$`];
205
+ const next = merge({}, previous, config);
206
+ globalThis[`$htmlplus:${namespace}$`] = next;
207
+ };
208
+ /**
209
+ * TODO
210
+ */
211
+ const setConfigCreator = (namespace) => (config, options) => {
212
+ return setConfig(namespace, config, options);
213
+ };
214
+
215
+ const defineProperty = Object.defineProperty;
216
+
217
+ /**
218
+ * Indicates whether the [Direction](https://mdn.io/css-direction)
219
+ * of the element is `Right-To-Left` or `Left-To-Right`.
220
+ */
221
+ const direction = (target) => {
222
+ return getComputedStyle(host(target)).getPropertyValue('direction');
223
+ };
224
+
225
+ const getFramework = (target) => {
226
+ const element = host(target);
227
+ if ('_qc_' in element)
228
+ return 'qwik';
229
+ if ('_$owner' in element)
230
+ return 'solid';
231
+ if ('__svelte_meta' in element)
232
+ return 'svelte';
233
+ if ('__vnode' in element)
234
+ return 'vue';
235
+ const keys = Object.keys(element);
236
+ const has = (input) => keys.some((key) => key.startsWith(input));
237
+ if (has('_blazor'))
238
+ return 'blazor';
239
+ if (has('__react'))
240
+ return 'react';
241
+ if (has('__zone_symbol__'))
242
+ return 'angular';
243
+ };
244
+
245
+ const getTag = (target) => {
246
+ return target.constructor[STATIC_TAG] ?? target[STATIC_TAG];
247
+ };
248
+
249
+ const getNamespace = (target) => {
250
+ return getTag(target)?.split('-')?.at(0);
251
+ };
252
+
253
+ /**
254
+ * Determines whether the given input string is a valid
255
+ * [CSS Color](https://mdn.io/color-value) or not.
256
+ */
257
+ const isCSSColor = (input) => {
258
+ const option = new Option();
259
+ option.style.color = input;
260
+ return option.style.color !== '';
261
+ };
262
+
263
+ /**
264
+ * Indicates whether the direction of the element is `Right-To-Left` or not.
265
+ */
266
+ const isRTL = (target) => direction(target) == 'rtl';
267
+
268
+ /**
269
+ * Indicates whether the current code is running on a server.
270
+ */
271
+ const isServer = () => {
272
+ return !(typeof window != 'undefined' && window.document);
273
+ };
274
+
275
+ const shadowRoot = (target) => {
276
+ return host(target)?.shadowRoot;
277
+ };
278
+
279
+ /**
280
+ * Selects the first element in the shadow dom that matches a specified CSS selector.
281
+ */
282
+ function query(target, selectors) {
283
+ return shadowRoot(target)?.querySelector(selectors);
284
+ }
285
+
286
+ /**
287
+ * Selects all elements in the shadow dom that match a specified CSS selector.
288
+ */
289
+ function queryAll(target, selectors) {
290
+ return shadowRoot(target)?.querySelectorAll(selectors);
291
+ }
292
+
293
+ const task = (options) => {
294
+ let running, promise;
295
+ const run = () => {
296
+ if (options.canStart && !options.canStart())
297
+ return Promise.resolve(false);
298
+ if (!running)
299
+ promise = enqueue();
300
+ return promise;
301
+ };
302
+ const enqueue = async () => {
303
+ running = true;
304
+ try {
305
+ await promise;
306
+ }
307
+ catch (error) {
308
+ Promise.reject(error);
309
+ }
310
+ // TODO: maybe is optional
311
+ if (!running)
312
+ return promise;
313
+ try {
314
+ if (options.canRun && !options.canRun())
315
+ return (running = false);
316
+ options.handler();
317
+ running = false;
318
+ return true;
319
+ }
320
+ catch (error) {
321
+ running = false;
322
+ throw error;
323
+ }
324
+ };
325
+ return run;
326
+ };
327
+
328
+ class MapSet extends Map {
329
+ set(key, value) {
330
+ super.set(key, value);
331
+ return value;
332
+ }
333
+ }
334
+
335
+ class WeakMapSet extends WeakMap {
336
+ set(key, value) {
337
+ super.set(key, value);
338
+ return value;
339
+ }
340
+ }
341
+
342
+ /*! (c) Andrea Giammarchi - ISC */
343
+ const empty =
344
+ /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
345
+ const elements = /<([a-z]+[a-z0-9:._-]*)([^>]*?)(\/?)>/g;
346
+ const attributes$1 = /([^\s\\>"'=]+)\s*=\s*(['"]?)\x01/g;
347
+ const holes = /[\x01\x02]/g;
348
+
349
+ // \x01 Node.ELEMENT_NODE
350
+ // \x02 Node.ATTRIBUTE_NODE
351
+
352
+ /**
353
+ * Given a template, find holes as both nodes and attributes and
354
+ * return a string with holes as either comment nodes or named attributes.
355
+ * @param {string[]} template a template literal tag array
356
+ * @param {string} prefix prefix to use per each comment/attribute
357
+ * @param {boolean} svg enforces self-closing tags
358
+ * @returns {string} X/HTML with prefixed comments or attributes
359
+ */
360
+ var instrument = (template, prefix, svg) => {
361
+ let i = 0;
362
+ return template
363
+ .join('\x01')
364
+ .trim()
365
+ .replace(elements, (_, name, attrs, selfClosing) => {
366
+ let ml = name + attrs.replace(attributes$1, '\x02=$2$1').trimEnd();
367
+ if (selfClosing.length) ml += svg || empty.test(name) ? ' /' : '></' + name;
368
+ return '<' + ml + '>';
369
+ })
370
+ .replace(holes, (hole) => (hole === '\x01' ? '<!--' + prefix + i++ + '-->' : prefix + i++));
371
+ };
372
+
373
+ const ELEMENT_NODE = 1;
374
+ const nodeType = 111;
375
+
376
+ const remove = ({ firstChild, lastChild }) => {
377
+ const range = document.createRange();
378
+ range.setStartAfter(firstChild);
379
+ range.setEndAfter(lastChild);
380
+ range.deleteContents();
381
+ return firstChild;
382
+ };
383
+
384
+ const diffable = (node, operation) =>
385
+ node.nodeType === nodeType
386
+ ? 1 / operation < 0
387
+ ? operation
388
+ ? remove(node)
389
+ : node.lastChild
390
+ : operation
391
+ ? node.valueOf()
392
+ : node.firstChild
393
+ : node;
394
+ const persistent = (fragment) => {
395
+ const { firstChild, lastChild } = fragment;
396
+ if (firstChild === lastChild) return lastChild || fragment;
397
+ const { childNodes } = fragment;
398
+ const nodes = [...childNodes];
399
+ return {
400
+ ELEMENT_NODE,
401
+ nodeType,
402
+ firstChild,
403
+ lastChild,
404
+ valueOf() {
405
+ if (childNodes.length !== nodes.length) fragment.append(...nodes);
406
+ return fragment;
407
+ }
408
+ };
409
+ };
410
+
411
+ const { isArray: isArray$1 } = Array;
412
+
413
+ const aria = (node) => (values) => {
414
+ for (const key in values) {
415
+ const name = key === 'role' ? key : `aria-${key}`;
416
+ const value = values[key];
417
+ if (value == null) node.removeAttribute(name);
418
+ else node.setAttribute(name, value);
419
+ }
420
+ };
421
+
422
+ const attribute = (node, name) => {
423
+ let oldValue,
424
+ orphan = true;
425
+ const attributeNode = document.createAttributeNS(null, name);
426
+ return (newValue) => {
427
+ if (oldValue !== newValue) {
428
+ oldValue = newValue;
429
+ if (oldValue == null) {
430
+ if (!orphan) {
431
+ node.removeAttributeNode(attributeNode);
432
+ orphan = true;
433
+ }
434
+ } else {
435
+ const value = newValue;
436
+ if (value == null) {
437
+ if (!orphan) node.removeAttributeNode(attributeNode);
438
+ orphan = true;
439
+ } else {
440
+ attributeNode.value = value;
441
+ if (orphan) {
442
+ node.setAttributeNodeNS(attributeNode);
443
+ orphan = false;
444
+ }
445
+ }
446
+ }
447
+ }
448
+ };
449
+ };
450
+
451
+ const boolean = (node, key, oldValue) => (newValue) => {
452
+ if (oldValue !== !!newValue) {
453
+ // when IE won't be around anymore ...
454
+ // node.toggleAttribute(key, oldValue = !!newValue);
455
+ if ((oldValue = !!newValue)) node.setAttribute(key, '');
456
+ else node.removeAttribute(key);
457
+ }
458
+ };
459
+
460
+ const data =
461
+ ({ dataset }) =>
462
+ (values) => {
463
+ for (const key in values) {
464
+ const value = values[key];
465
+ if (value == null) delete dataset[key];
466
+ else dataset[key] = value;
467
+ }
468
+ };
469
+
470
+ const event = (node, name) => {
471
+ let oldValue,
472
+ lower,
473
+ type = name.slice(2);
474
+ if (!(name in node) && (lower = name.toLowerCase()) in node) type = lower.slice(2);
475
+ return (newValue) => {
476
+ const info = isArray$1(newValue) ? newValue : [newValue, false];
477
+ if (oldValue !== info[0]) {
478
+ if (oldValue) node.removeEventListener(type, oldValue, info[1]);
479
+ if ((oldValue = info[0])) node.addEventListener(type, oldValue, info[1]);
480
+ }
481
+ };
482
+ };
483
+
484
+ const ref = (node) => {
485
+ let oldValue;
486
+ return (value) => {
487
+ if (oldValue !== value) {
488
+ oldValue = value;
489
+ if (typeof value === 'function') value(node);
490
+ else value.current = node;
491
+ }
492
+ };
493
+ };
494
+
495
+ const setter = (node, key) =>
496
+ key === 'dataset'
497
+ ? data(node)
498
+ : (value) => {
499
+ node[key] = value;
500
+ };
501
+
502
+ const text = (node) => {
503
+ let oldValue;
504
+ return (newValue) => {
505
+ if (oldValue != newValue) {
506
+ oldValue = newValue;
507
+ node.textContent = newValue == null ? '' : newValue;
508
+ }
509
+ };
510
+ };
511
+
512
+ /**
513
+ * ISC License
514
+ *
515
+ * Copyright (c) 2020, Andrea Giammarchi, @WebReflection
516
+ *
517
+ * Permission to use, copy, modify, and/or distribute this software for any
518
+ * purpose with or without fee is hereby granted, provided that the above
519
+ * copyright notice and this permission notice appear in all copies.
520
+ *
521
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
522
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
523
+ * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
524
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
525
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
526
+ * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
527
+ * PERFORMANCE OF THIS SOFTWARE.
528
+ */
529
+
530
+ /**
531
+ * @param {Node} parentNode The container where children live
532
+ * @param {Node[]} a The list of current/live children
533
+ * @param {Node[]} b The list of future children
534
+ * @param {(entry: Node, action: number) => Node} get
535
+ * The callback invoked per each entry related DOM operation.
536
+ * @param {Node} [before] The optional node used as anchor to insert before.
537
+ * @returns {Node[]} The same list of future children.
538
+ */
539
+ var udomdiff = (parentNode, a, b, get, before) => {
540
+ const bLength = b.length;
541
+ let aEnd = a.length;
542
+ let bEnd = bLength;
543
+ let aStart = 0;
544
+ let bStart = 0;
545
+ let map = null;
546
+ while (aStart < aEnd || bStart < bEnd) {
547
+ // append head, tail, or nodes in between: fast path
548
+ if (aEnd === aStart) {
549
+ // we could be in a situation where the rest of nodes that
550
+ // need to be added are not at the end, and in such case
551
+ // the node to `insertBefore`, if the index is more than 0
552
+ // must be retrieved, otherwise it's gonna be the first item.
553
+ const node =
554
+ bEnd < bLength
555
+ ? bStart
556
+ ? get(b[bStart - 1], -0).nextSibling
557
+ : get(b[bEnd - bStart], 0)
558
+ : before;
559
+ while (bStart < bEnd) parentNode.insertBefore(get(b[bStart++], 1), node);
560
+ }
561
+ // remove head or tail: fast path
562
+ else if (bEnd === bStart) {
563
+ while (aStart < aEnd) {
564
+ // remove the node only if it's unknown or not live
565
+ if (!map || !map.has(a[aStart])) parentNode.removeChild(get(a[aStart], -1));
566
+ aStart++;
567
+ }
568
+ }
569
+ // same node: fast path
570
+ else if (a[aStart] === b[bStart]) {
571
+ aStart++;
572
+ bStart++;
573
+ }
574
+ // same tail: fast path
575
+ else if (a[aEnd - 1] === b[bEnd - 1]) {
576
+ aEnd--;
577
+ bEnd--;
578
+ }
579
+ // The once here single last swap "fast path" has been removed in v1.1.0
580
+ // https://github.com/WebReflection/udomdiff/blob/single-final-swap/esm/index.js#L69-L85
581
+ // reverse swap: also fast path
582
+ else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
583
+ // this is a "shrink" operation that could happen in these cases:
584
+ // [1, 2, 3, 4, 5]
585
+ // [1, 4, 3, 2, 5]
586
+ // or asymmetric too
587
+ // [1, 2, 3, 4, 5]
588
+ // [1, 2, 3, 5, 6, 4]
589
+ const node = get(a[--aEnd], -1).nextSibling;
590
+ parentNode.insertBefore(get(b[bStart++], 1), get(a[aStart++], -1).nextSibling);
591
+ parentNode.insertBefore(get(b[--bEnd], 1), node);
592
+ // mark the future index as identical (yeah, it's dirty, but cheap 👍)
593
+ // The main reason to do this, is that when a[aEnd] will be reached,
594
+ // the loop will likely be on the fast path, as identical to b[bEnd].
595
+ // In the best case scenario, the next loop will skip the tail,
596
+ // but in the worst one, this node will be considered as already
597
+ // processed, bailing out pretty quickly from the map index check
598
+ a[aEnd] = b[bEnd];
599
+ }
600
+ // map based fallback, "slow" path
601
+ else {
602
+ // the map requires an O(bEnd - bStart) operation once
603
+ // to store all future nodes indexes for later purposes.
604
+ // In the worst case scenario, this is a full O(N) cost,
605
+ // and such scenario happens at least when all nodes are different,
606
+ // but also if both first and last items of the lists are different
607
+ if (!map) {
608
+ map = new Map();
609
+ let i = bStart;
610
+ while (i < bEnd) map.set(b[i], i++);
611
+ }
612
+ // if it's a future node, hence it needs some handling
613
+ if (map.has(a[aStart])) {
614
+ // grab the index of such node, 'cause it might have been processed
615
+ const index = map.get(a[aStart]);
616
+ // if it's not already processed, look on demand for the next LCS
617
+ if (bStart < index && index < bEnd) {
618
+ let i = aStart;
619
+ // counts the amount of nodes that are the same in the future
620
+ let sequence = 1;
621
+ while (++i < aEnd && i < bEnd && map.get(a[i]) === index + sequence) sequence++;
622
+ // effort decision here: if the sequence is longer than replaces
623
+ // needed to reach such sequence, which would brings again this loop
624
+ // to the fast path, prepend the difference before a sequence,
625
+ // and move only the future list index forward, so that aStart
626
+ // and bStart will be aligned again, hence on the fast path.
627
+ // An example considering aStart and bStart are both 0:
628
+ // a: [1, 2, 3, 4]
629
+ // b: [7, 1, 2, 3, 6]
630
+ // this would place 7 before 1 and, from that time on, 1, 2, and 3
631
+ // will be processed at zero cost
632
+ if (sequence > index - bStart) {
633
+ const node = get(a[aStart], 0);
634
+ while (bStart < index) parentNode.insertBefore(get(b[bStart++], 1), node);
635
+ }
636
+ // if the effort wasn't good enough, fallback to a replace,
637
+ // moving both source and target indexes forward, hoping that some
638
+ // similar node will be found later on, to go back to the fast path
639
+ else {
640
+ parentNode.replaceChild(get(b[bStart++], 1), get(a[aStart++], -1));
641
+ }
642
+ }
643
+ // otherwise move the source forward, 'cause there's nothing to do
644
+ else aStart++;
645
+ }
646
+ // this node has no meaning in the future list, so it's more than safe
647
+ // to remove it, and check the next live node out instead, meaning
648
+ // that only the live list index should be forwarded
649
+ else parentNode.removeChild(get(a[aStart++], -1));
650
+ }
651
+ }
652
+ return b;
653
+ };
654
+
655
+ const { isArray, prototype } = Array;
656
+ const { indexOf } = prototype;
657
+
658
+ const {
659
+ createDocumentFragment,
660
+ createElement,
661
+ createElementNS,
662
+ createTextNode,
663
+ createTreeWalker,
664
+ importNode
665
+ } = new Proxy(typeof window == 'undefined' ? {} : window.document, {
666
+ get: (target, method) => (target[method] || function () {}).bind(target)
667
+ });
668
+
669
+ const createHTML = (html) => {
670
+ const template = createElement('template');
671
+ template.innerHTML = html;
672
+ return template.content;
673
+ };
674
+
675
+ let xml;
676
+ const createSVG = (svg) => {
677
+ if (!xml) xml = createElementNS('http://www.w3.org/2000/svg', 'svg');
678
+ xml.innerHTML = svg;
679
+ const content = createDocumentFragment();
680
+ content.append(...xml.childNodes);
681
+ return content;
682
+ };
683
+
684
+ const createContent = (text, svg) => (svg ? createSVG(text) : createHTML(text));
685
+
686
+ // from a generic path, retrieves the exact targeted node
687
+ const reducePath = ({ childNodes }, i) => childNodes[i];
688
+
689
+ // this helper avoid code bloat around handleAnything() callback
690
+ const diff = (comment, oldNodes, newNodes) =>
691
+ udomdiff(
692
+ comment.parentNode,
693
+ // TODO: there is a possible edge case where a node has been
694
+ // removed manually, or it was a keyed one, attached
695
+ // to a shared reference between renders.
696
+ // In this case udomdiff might fail at removing such node
697
+ // as its parent won't be the expected one.
698
+ // The best way to avoid this issue is to filter oldNodes
699
+ // in search of those not live, or not in the current parent
700
+ // anymore, but this would require both a change to uwire,
701
+ // exposing a parentNode from the firstChild, as example,
702
+ // but also a filter per each diff that should exclude nodes
703
+ // that are not in there, penalizing performance quite a lot.
704
+ // As this has been also a potential issue with domdiff,
705
+ // and both lighterhtml and hyperHTML might fail with this
706
+ // very specific edge case, I might as well document this possible
707
+ // "diffing shenanigan" and call it a day.
708
+ oldNodes,
709
+ newNodes,
710
+ diffable,
711
+ comment
712
+ );
713
+
714
+ // if an interpolation represents a comment, the whole
715
+ // diffing will be related to such comment.
716
+ // This helper is in charge of understanding how the new
717
+ // content for such interpolation/hole should be updated
718
+ const handleAnything = (comment) => {
719
+ let oldValue,
720
+ text,
721
+ nodes = [];
722
+ const anyContent = (newValue) => {
723
+ switch (typeof newValue) {
724
+ // primitives are handled as text content
725
+ case 'string':
726
+ case 'number':
727
+ case 'boolean':
728
+ if (oldValue !== newValue) {
729
+ oldValue = newValue;
730
+ if (!text) text = createTextNode('');
731
+ text.data = newValue;
732
+ nodes = diff(comment, nodes, [text]);
733
+ }
734
+ break;
735
+ // null, and undefined are used to cleanup previous content
736
+ case 'object':
737
+ case 'undefined':
738
+ if (newValue == null) {
739
+ if (oldValue != newValue) {
740
+ oldValue = newValue;
741
+ nodes = diff(comment, nodes, []);
742
+ }
743
+ break;
744
+ }
745
+ // arrays and nodes have a special treatment
746
+ if (isArray(newValue)) {
747
+ oldValue = newValue;
748
+ // arrays can be used to cleanup, if empty
749
+ if (newValue.length === 0) nodes = diff(comment, nodes, []);
750
+ // or diffed, if these contains nodes or "wires"
751
+ else if (typeof newValue[0] === 'object') nodes = diff(comment, nodes, newValue);
752
+ // in all other cases the content is stringified as is
753
+ else anyContent(String(newValue));
754
+ break;
755
+ }
756
+ // if the new value is a DOM node, or a wire, and it's
757
+ // different from the one already live, then it's diffed.
758
+ // if the node is a fragment, it's appended once via its childNodes
759
+ // There is no `else` here, meaning if the content
760
+ // is not expected one, nothing happens, as easy as that.
761
+ if (oldValue !== newValue && 'ELEMENT_NODE' in newValue) {
762
+ oldValue = newValue;
763
+ nodes = diff(
764
+ comment,
765
+ nodes,
766
+ newValue.nodeType === 11 ? [...newValue.childNodes] : [newValue]
767
+ );
768
+ }
769
+ break;
770
+ case 'function':
771
+ anyContent(newValue(comment));
772
+ break;
773
+ }
774
+ };
775
+ return anyContent;
776
+ };
777
+
778
+ // attributes can be:
779
+ // * ref=${...} for hooks and other purposes
780
+ // * aria=${...} for aria attributes
781
+ // * ?boolean=${...} for boolean attributes
782
+ // * .dataset=${...} for dataset related attributes
783
+ // * .setter=${...} for Custom Elements setters or nodes with setters
784
+ // such as buttons, details, options, select, etc
785
+ // * @event=${...} to explicitly handle event listeners
786
+ // * onevent=${...} to automatically handle event listeners
787
+ // * generic=${...} to handle an attribute just like an attribute
788
+ const handleAttribute = (node, name /*, svg*/) => {
789
+ switch (name[0]) {
790
+ case '?':
791
+ return boolean(node, name.slice(1), false);
792
+ case '.':
793
+ return setter(node, name.slice(1));
794
+ case '@':
795
+ return event(node, 'on' + name.slice(1));
796
+ case 'o':
797
+ if (name[1] === 'n') return event(node, name);
798
+ }
799
+
800
+ switch (name) {
801
+ case 'ref':
802
+ return ref(node);
803
+ case 'aria':
804
+ return aria(node);
805
+ }
806
+
807
+ return attribute(node, name /*, svg*/);
808
+ };
809
+
810
+ // each mapped update carries the update type and its path
811
+ // the type is either node, attribute, or text, while
812
+ // the path is how to retrieve the related node to update.
813
+ // In the attribute case, the attribute name is also carried along.
814
+ function handlers(options) {
815
+ const { type, path } = options;
816
+ const node = path.reduceRight(reducePath, this);
817
+ return type === 'node'
818
+ ? handleAnything(node)
819
+ : type === 'attr'
820
+ ? handleAttribute(node, options.name /*, options.svg*/)
821
+ : text(node);
822
+ }
823
+
824
+ // from a fragment container, create an array of indexes
825
+ // related to its child nodes, so that it's possible
826
+ // to retrieve later on exact node via reducePath
827
+ const createPath = (node) => {
828
+ const path = [];
829
+ let { parentNode } = node;
830
+ while (parentNode) {
831
+ path.push(indexOf.call(parentNode.childNodes, node));
832
+ node = parentNode;
833
+ ({ parentNode } = node);
834
+ }
835
+ return path;
836
+ };
837
+
838
+ // the prefix is used to identify either comments, attributes, or nodes
839
+ // that contain the related unique id. In the attribute cases
840
+ // isµX="attribute-name" will be used to map current X update to that
841
+ // attribute name, while comments will be like <!--isµX-->, to map
842
+ // the update to that specific comment node, hence its parent.
843
+ // style and textarea will have <!--isµX--> text content, and are handled
844
+ // directly through text-only updates.
845
+ const prefix = 'isµ';
846
+
847
+ // Template Literals are unique per scope and static, meaning a template
848
+ // should be parsed once, and once only, as it will always represent the same
849
+ // content, within the exact same amount of updates each time.
850
+ // This cache relates each template to its unique content and updates.
851
+ const cache$1 = new WeakMapSet();
852
+
853
+ // a RegExp that helps checking nodes that cannot contain comments
854
+ const textOnly = /^(?:textarea|script|style|title|plaintext|xmp)$/;
855
+
856
+ const createCache = () => ({
857
+ stack: [], // each template gets a stack for each interpolation "hole"
858
+
859
+ entry: null, // each entry contains details, such as:
860
+ // * the template that is representing
861
+ // * the type of node it represents (html or svg)
862
+ // * the content fragment with all nodes
863
+ // * the list of updates per each node (template holes)
864
+ // * the "wired" node or fragment that will get updates
865
+ // if the template or type are different from the previous one
866
+ // the entry gets re-created each time
867
+
868
+ wire: null // each rendered node represent some wired content and
869
+ // this reference to the latest one. If different, the node
870
+ // will be cleaned up and the new "wire" will be appended
871
+ });
872
+
873
+ // the entry stored in the rendered node cache, and per each "hole"
874
+ const createEntry = (type, template) => {
875
+ const { content, updates } = mapUpdates(type, template);
876
+ return { type, template, content, updates, wire: null };
877
+ };
878
+
879
+ // a template is instrumented to be able to retrieve where updates are needed.
880
+ // Each unique template becomes a fragment, cloned once per each other
881
+ // operation based on the same template, i.e. data => html`<p>${data}</p>`
882
+ const mapTemplate = (type, template) => {
883
+ const svg = type === 'svg';
884
+ const text = instrument(template, prefix, svg);
885
+ const content = createContent(text, svg);
886
+ // once instrumented and reproduced as fragment, it's crawled
887
+ // to find out where each update is in the fragment tree
888
+ const tw = createTreeWalker(content, 1 | 128);
889
+ const nodes = [];
890
+ const length = template.length - 1;
891
+ let i = 0;
892
+ // updates are searched via unique names, linearly increased across the tree
893
+ // <div isµ0="attr" isµ1="other"><!--isµ2--><style><!--isµ3--</style></div>
894
+ let search = `${prefix}${i}`;
895
+ while (i < length) {
896
+ const node = tw.nextNode();
897
+ // if not all updates are bound but there's nothing else to crawl
898
+ // it means that there is something wrong with the template.
899
+ if (!node) throw `bad template: ${text}`;
900
+ // if the current node is a comment, and it contains isµX
901
+ // it means the update should take care of any content
902
+ if (node.nodeType === 8) {
903
+ // The only comments to be considered are those
904
+ // which content is exactly the same as the searched one.
905
+ if (node.data === search) {
906
+ nodes.push({ type: 'node', path: createPath(node) });
907
+ search = `${prefix}${++i}`;
908
+ }
909
+ } else {
910
+ // if the node is not a comment, loop through all its attributes
911
+ // named isµX and relate attribute updates to this node and the
912
+ // attribute name, retrieved through node.getAttribute("isµX")
913
+ // the isµX attribute will be removed as irrelevant for the layout
914
+ // let svg = -1;
915
+ while (node.hasAttribute(search)) {
916
+ nodes.push({
917
+ type: 'attr',
918
+ path: createPath(node),
919
+ name: node.getAttribute(search)
920
+ });
921
+ node.removeAttribute(search);
922
+ search = `${prefix}${++i}`;
923
+ }
924
+ // if the node was a style, textarea, or others, check its content
925
+ // and if it is <!--isµX--> then update tex-only this node
926
+ if (textOnly.test(node.localName) && node.textContent.trim() === `<!--${search}-->`) {
927
+ node.textContent = '';
928
+ nodes.push({ type: 'text', path: createPath(node) });
929
+ search = `${prefix}${++i}`;
930
+ }
931
+ }
932
+ }
933
+ // once all nodes to update, or their attributes, are known, the content
934
+ // will be cloned in the future to represent the template, and all updates
935
+ // related to such content retrieved right away without needing to re-crawl
936
+ // the exact same template, and its content, more than once.
937
+ return { content, nodes };
938
+ };
939
+
940
+ // if a template is unknown, perform the previous mapping, otherwise grab
941
+ // its details such as the fragment with all nodes, and updates info.
942
+ const mapUpdates = (type, template) => {
943
+ const { content, nodes } =
944
+ cache$1.get(template) || cache$1.set(template, mapTemplate(type, template));
945
+ // clone deeply the fragment
946
+ const fragment = importNode(content, true);
947
+ // and relate an update handler per each node that needs one
948
+ const updates = nodes.map(handlers, fragment);
949
+ // return the fragment and all updates to use within its nodes
950
+ return { content: fragment, updates };
951
+ };
952
+
953
+ // as html and svg can be nested calls, but no parent node is known
954
+ // until rendered somewhere, the unroll operation is needed to
955
+ // discover what to do with each interpolation, which will result
956
+ // into an update operation.
957
+ const unroll = (info, { type, template, values }) => {
958
+ // interpolations can contain holes and arrays, so these need
959
+ // to be recursively discovered
960
+ const length = unrollValues(info, values);
961
+ let { entry } = info;
962
+ // if the cache entry is either null or different from the template
963
+ // and the type this unroll should resolve, create a new entry
964
+ // assigning a new content fragment and the list of updates.
965
+ if (!entry || entry.template !== template || entry.type !== type)
966
+ info.entry = entry = createEntry(type, template);
967
+ const { content, updates, wire } = entry;
968
+ // even if the fragment and its nodes is not live yet,
969
+ // it is already possible to update via interpolations values.
970
+ for (let i = 0; i < length; i++) updates[i](values[i]);
971
+ // if the entry was new, or representing a different template or type,
972
+ // create a new persistent entity to use during diffing.
973
+ // This is simply a DOM node, when the template has a single container,
974
+ // as in `<p></p>`, or a "wire" in `<p></p><p></p>` and similar cases.
975
+ return wire || (entry.wire = persistent(content));
976
+ };
977
+
978
+ // the stack retains, per each interpolation value, the cache
979
+ // related to each interpolation value, or null, if the render
980
+ // was conditional and the value is not special (Array or Hole)
981
+ const unrollValues = ({ stack }, values) => {
982
+ const { length } = values;
983
+ for (let i = 0; i < length; i++) {
984
+ const hole = values[i];
985
+ // each Hole gets unrolled and re-assigned as value
986
+ // so that domdiff will deal with a node/wire, not with a hole
987
+ if (hole instanceof Hole) values[i] = unroll(stack[i] || (stack[i] = createCache()), hole);
988
+ // arrays are recursively resolved so that each entry will contain
989
+ // also a DOM node or a wire, hence it can be diffed if/when needed
990
+ else if (isArray(hole)) unrollValues(stack[i] || (stack[i] = createCache()), hole);
991
+ // if the value is nothing special, the stack doesn't need to retain data
992
+ // this is useful also to cleanup previously retained data, if the value
993
+ // was a Hole, or an Array, but not anymore, i.e.:
994
+ // const update = content => html`<div>${content}</div>`;
995
+ // update(listOfItems); update(null); update(html`hole`)
996
+ else stack[i] = null;
997
+ }
998
+ if (length < stack.length) stack.splice(length);
999
+ return length;
1000
+ };
1001
+
1002
+ /**
1003
+ * Holds all details wrappers needed to render the content further on.
1004
+ * @constructor
1005
+ * @param {string} type The hole type, either `html` or `svg`.
1006
+ * @param {string[]} template The template literals used to the define the content.
1007
+ * @param {Array} values Zero, one, or more interpolated values to render.
1008
+ */
1009
+ class Hole {
1010
+ constructor(type, template, values) {
1011
+ this.type = type;
1012
+ this.template = template;
1013
+ this.values = values;
1014
+ }
1015
+ }
1016
+
1017
+ // both `html` and `svg` template literal tags are polluted
1018
+ // with a `for(ref[, id])` and a `node` tag too
1019
+ const tag = (type) => {
1020
+ // both `html` and `svg` tags have their own cache
1021
+ const keyed = new WeakMapSet();
1022
+ // keyed operations always re-use the same cache and unroll
1023
+ // the template and its interpolations right away
1024
+ const fixed =
1025
+ (cache) =>
1026
+ (template, ...values) =>
1027
+ unroll(cache, { type, template, values });
1028
+ return Object.assign(
1029
+ // non keyed operations are recognized as instance of Hole
1030
+ // during the "unroll", recursively resolved and updated
1031
+ (template, ...values) => new Hole(type, template, values),
1032
+ {
1033
+ // keyed operations need a reference object, usually the parent node
1034
+ // which is showing keyed results, and optionally a unique id per each
1035
+ // related node, handy with JSON results and mutable list of objects
1036
+ // that usually carry a unique identifier
1037
+ for(ref, id) {
1038
+ const memo = keyed.get(ref) || keyed.set(ref, new MapSet());
1039
+ return memo.get(id) || memo.set(id, fixed(createCache()));
1040
+ },
1041
+ // it is possible to create one-off content out of the box via node tag
1042
+ // this might return the single created node, or a fragment with all
1043
+ // nodes present at the root level and, of course, their child nodes
1044
+ node: (template, ...values) =>
1045
+ unroll(createCache(), new Hole(type, template, values)).valueOf()
1046
+ }
1047
+ );
1048
+ };
1049
+
1050
+ // each rendered node gets its own cache
1051
+ const cache = new WeakMapSet();
1052
+
1053
+ // rendering means understanding what `html` or `svg` tags returned
1054
+ // and it relates a specific node to its own unique cache.
1055
+ // Each time the content to render changes, the node is cleaned up
1056
+ // and the new new content is appended, and if such content is a Hole
1057
+ // then it's "unrolled" to resolve all its inner nodes.
1058
+ const render = (where, what) => {
1059
+ const hole = typeof what === 'function' ? what() : what;
1060
+ const info = cache.get(where) || cache.set(where, createCache());
1061
+ const wire = hole instanceof Hole ? unroll(info, hole) : hole;
1062
+ if (wire !== info.wire) {
1063
+ info.wire = wire;
1064
+ // valueOf() simply returns the node itself, but in case it was a "wire"
1065
+ // it will eventually re-append all nodes to its fragment so that such
1066
+ // fragment can be re-appended many times in a meaningful way
1067
+ // (wires are basically persistent fragments facades with special behavior)
1068
+ where.replaceChildren(wire.valueOf());
1069
+ }
1070
+ return where;
1071
+ };
1072
+
1073
+ const html$1 = tag('html');
1074
+ tag('svg');
1075
+
1076
+ /**
1077
+ * Updates the DOM with a scheduled task.
1078
+ * @param target The element instance.
1079
+ * @param name Property/State name.
1080
+ * @param previous The previous value of Property/State.
1081
+ * @param callback Invoked when the rendering phase is completed.
1082
+ */
1083
+ const requestUpdate = (target, name, previous, callback) => {
1084
+ // Creates/Gets a stacks.
1085
+ const stacks = (target[API_STACKS] ||= new Map());
1086
+ // Creates/Updates a stack.
1087
+ const stack = stacks.get(name) || { callbacks: [], previous };
1088
+ // Adds the callback to the stack, if exists.
1089
+ callback && stack.callbacks.push(callback);
1090
+ // Stores the stack.
1091
+ stacks.set(name, stack);
1092
+ // Defines a handler.
1093
+ const handler = () => {
1094
+ // Skips the rendering phase if DOM isn't ready.
1095
+ if (!target[API_CONNECTED])
1096
+ return;
1097
+ // Calculates the states to pass into lifecycles' callbacks.
1098
+ const states = new Map(Array.from(stacks)
1099
+ .filter((stack) => stack[0])
1100
+ .map((stack) => [stack[0], stack[1].previous]));
1101
+ // Calls the lifecycle's callback before the rendering phase.
1102
+ call(target, LIFECYCLE_UPDATE, states);
1103
+ // Renders template to the DOM.
1104
+ render(shadowRoot(target), () => call(target, METHOD_RENDER) ?? null);
1105
+ // Invokes requests' callback.
1106
+ stacks.forEach((state) => {
1107
+ state.callbacks.forEach((callback, index, callbacks) => {
1108
+ callback(callbacks.length - 1 != index);
1109
+ });
1110
+ });
1111
+ // TODO
1112
+ (() => {
1113
+ const raw = target.constructor[STATIC_STYLE];
1114
+ if (!raw)
1115
+ return;
1116
+ const regex1 = /this-([\w-]+)(?:-([\w-]+))?/g;
1117
+ const regex2 = /(\s*\w+\s*:\s*(undefined|null)\s*;?)/g;
1118
+ const regex3 = /global\s+[^{]+\{[^{}]*\{[^{}]*\}[^{}]*\}|global\s+[^{]+\{[^{}]*\}/g;
1119
+ const hasGlobal = raw.includes('global');
1120
+ const hasVariable = raw.includes('this-');
1121
+ let localSheet = target[API_STYLE];
1122
+ let globalSheet = target.constructor[API_STYLE];
1123
+ if (!hasVariable && localSheet)
1124
+ return;
1125
+ const parsed = raw
1126
+ .replace(regex1, (match, key) => {
1127
+ let value = target;
1128
+ for (const section of key.split('-')) {
1129
+ value = value?.[section];
1130
+ }
1131
+ return value;
1132
+ })
1133
+ .replace(regex2, '');
1134
+ if (!localSheet) {
1135
+ localSheet = new CSSStyleSheet();
1136
+ target[API_STYLE] = localSheet;
1137
+ shadowRoot(target).adoptedStyleSheets.push(localSheet);
1138
+ }
1139
+ const localStyle = parsed.replace(regex3, '');
1140
+ localSheet.replaceSync(localStyle);
1141
+ if (!hasGlobal || globalSheet)
1142
+ return;
1143
+ if (!globalSheet) {
1144
+ globalSheet = new CSSStyleSheet();
1145
+ target.constructor[API_STYLE] = globalSheet;
1146
+ document.adoptedStyleSheets.push(globalSheet);
1147
+ }
1148
+ const globalStyle = parsed
1149
+ ?.match(regex3)
1150
+ ?.join('')
1151
+ ?.replaceAll('global', '')
1152
+ ?.replaceAll(':host', getTag(target));
1153
+ globalSheet.replaceSync(globalStyle);
1154
+ })();
1155
+ // Calls the lifecycle's callback after the rendering phase.
1156
+ call(target, LIFECYCLE_UPDATED, states);
1157
+ // Clears stacks.
1158
+ stacks.clear();
1159
+ // TODO: related to the @Watch decorator.
1160
+ target[API_RENDER_COMPLETED] = true;
1161
+ };
1162
+ // Creates/Gets a micro task function.
1163
+ target[API_REQUEST] ||= task({ handler });
1164
+ // Calls the micro task.
1165
+ call(target, API_REQUEST);
1166
+ };
1167
+
1168
+ /**
1169
+ * Returns the slots name.
1170
+ */
1171
+ const slots = (target) => {
1172
+ const element = host(target);
1173
+ const slots = {};
1174
+ const children = Array.from(element.childNodes);
1175
+ for (const child of children) {
1176
+ if (child.nodeName == '#comment')
1177
+ continue;
1178
+ const name = child['slot'] || (child.nodeValue?.trim() && 'default') || ('slot' in child && 'default');
1179
+ if (!name)
1180
+ continue;
1181
+ slots[name] = true;
1182
+ }
1183
+ return slots;
1184
+ };
1185
+
1186
+ /**
1187
+ * Converts a JavaScript object containing CSS styles to a CSS string.
1188
+ */
1189
+ const styles$1 = (input) => {
1190
+ return Object.keys(input)
1191
+ .filter((key) => input[key] !== undefined && input[key] !== null)
1192
+ .map((key) => `${key.startsWith('--') ? '--' : ''}${kebabCase(key)}: ${input[key]}`)
1193
+ .join('; ');
1194
+ };
1195
+
1196
+ const toCSSColor = (input) => {
1197
+ return isCSSColor(input) ? input : undefined;
1198
+ };
1199
+
1200
+ const toCSSUnit = (input) => {
1201
+ if (input == null || input === '') {
1202
+ return;
1203
+ }
1204
+ if (typeof input === 'number' || !isNaN(Number(input))) {
1205
+ return `${input}px`;
1206
+ }
1207
+ if (/^\d+(\.\d+)?(px|pt|cm|mm|in|em|rem|%|vw|vh)$/.test(input)) {
1208
+ return input;
1209
+ }
1210
+ };
1211
+
1212
+ function toDecorator(util, ...args) {
1213
+ return function (target, key) {
1214
+ defineProperty(target, key, {
1215
+ get() {
1216
+ return util(this, ...args);
1217
+ }
1218
+ });
1219
+ };
1220
+ }
1221
+
1222
+ const toProperty = (input, type) => {
1223
+ if (type === undefined)
1224
+ return input;
1225
+ const string = `${input}`;
1226
+ if (TYPE_BOOLEAN & type || type === Boolean) {
1227
+ if (string === '')
1228
+ return true;
1229
+ if (string === 'true')
1230
+ return true;
1231
+ if (string === 'false')
1232
+ return false;
1233
+ }
1234
+ if (TYPE_NUMBER & type || type === Number) {
1235
+ if (string != '' && !isNaN(input)) {
1236
+ return parseFloat(input);
1237
+ }
1238
+ }
1239
+ if (TYPE_NULL & type || type === null) {
1240
+ if (string === 'null') {
1241
+ return null;
1242
+ }
1243
+ }
1244
+ if (TYPE_DATE & type || type === Date) {
1245
+ const value = new Date(input);
1246
+ if (value.toString() != 'Invalid Date') {
1247
+ return value;
1248
+ }
1249
+ }
1250
+ if (TYPE_ARRAY & type || type === Array) {
1251
+ try {
1252
+ const value = JSON.parse(input);
1253
+ if (typeOf(value) == 'array') {
1254
+ return value;
1255
+ }
1256
+ }
1257
+ catch { }
1258
+ }
1259
+ if (TYPE_OBJECT & type || type === Object) {
1260
+ try {
1261
+ const value = JSON.parse(input);
1262
+ if (typeOf(value) == 'object') {
1263
+ return value;
1264
+ }
1265
+ }
1266
+ catch { }
1267
+ }
1268
+ if (TYPE_UNDEFINED & type || type === undefined) {
1269
+ if (string === 'undefined') {
1270
+ return undefined;
1271
+ }
1272
+ }
1273
+ if (TYPE_STRING & type || type === String) {
1274
+ return input;
1275
+ }
1276
+ // TODO
1277
+ // if (CONSTANTS.TYPE_BIGINT & type || type === BigInt) { }
1278
+ // if (CONSTANTS.TYPE_ENUM & type || type === TODO) { }
1279
+ // if (CONSTANTS.TYPE_FUNCTION & type || type === Function) { }
1280
+ try {
1281
+ // TODO
1282
+ return JSON.parse(input);
1283
+ }
1284
+ catch {
1285
+ return input;
1286
+ }
1287
+ };
1288
+
1289
+ /**
1290
+ * Converts a value to a unit.
1291
+ */
1292
+ const toUnit = (input, unit = 'px') => {
1293
+ if (input === null || input === undefined || input === '')
1294
+ return input;
1295
+ if (isNaN(+input))
1296
+ return String(input);
1297
+ return Number(input) + unit;
1298
+ };
1299
+
1300
+ const wrapMethod = (mode, target, key, handler) => {
1301
+ // Gets the original function
1302
+ const original = target[key];
1303
+ // Validate target property
1304
+ if (original && typeof original !== 'function') {
1305
+ throw new TypeError(`Property ${String(key)} is not a function`);
1306
+ }
1307
+ // Creates new function
1308
+ function wrapped(...args) {
1309
+ // Calls the handler before the original
1310
+ if (mode == 'before') {
1311
+ handler.apply(this, args);
1312
+ }
1313
+ // Calls the original
1314
+ const result = original?.apply(this, args);
1315
+ // Calls the handler after the original
1316
+ if (mode == 'after') {
1317
+ handler.apply(this, args);
1318
+ }
1319
+ // Returns the result
1320
+ return result;
1321
+ }
1322
+ // Replaces the wrapped with the original one
1323
+ target[key] = wrapped;
1324
+ };
1325
+
1326
+ /**
1327
+ * Used to bind a method of a class to the current context,
1328
+ * making it easier to reference `this` within the method.
1329
+ */
1330
+ function Bind() {
1331
+ return function (target, key, descriptor) {
1332
+ const original = descriptor.value;
1333
+ return {
1334
+ configurable: true,
1335
+ get() {
1336
+ const next = original.bind(this);
1337
+ defineProperty(this, key, {
1338
+ value: next,
1339
+ configurable: true,
1340
+ writable: true
1341
+ });
1342
+ return next;
1343
+ }
1344
+ };
1345
+ };
1346
+ }
1347
+
1348
+ function Provider(namespace) {
1349
+ return function (target, key) {
1350
+ const symbol = Symbol();
1351
+ const [MAIN, SUB] = namespace.split('.');
1352
+ const prefix = `${KEY}:${MAIN}`;
1353
+ const cleanups = (instance) => {
1354
+ return (instance[symbol] ||= new Map());
1355
+ };
1356
+ const update = (instance) => {
1357
+ const options = {};
1358
+ options.detail = instance[key];
1359
+ dispatch(instance, `${prefix}:update`, options);
1360
+ if (!SUB)
1361
+ return;
1362
+ options.bubbles = true;
1363
+ dispatch(instance, `${prefix}:${instance[SUB]}:update`, options);
1364
+ };
1365
+ // TODO
1366
+ wrapMethod('after', target, LIFECYCLE_CONNECTED, function () {
1367
+ const cleanup = () => {
1368
+ off(this, `${prefix}:presence`, onPresence);
1369
+ cleanups(this).delete(prefix);
1370
+ };
1371
+ const onPresence = (event) => {
1372
+ event.stopPropagation();
1373
+ event.detail(this, this[key]);
1374
+ };
1375
+ on(this, `${prefix}:presence`, onPresence);
1376
+ cleanups(this).set(prefix, cleanup);
1377
+ });
1378
+ wrapMethod('after', target, LIFECYCLE_UPDATE, function (states) {
1379
+ update(this);
1380
+ if (cleanups(this).size && !states.has(SUB))
1381
+ return;
1382
+ cleanups(this).get(`${prefix}:${states.get(SUB)}`)?.();
1383
+ const type = `${prefix}:${this[SUB]}`;
1384
+ const cleanup = () => {
1385
+ off(window, `${type}:presence`, onPresence);
1386
+ cleanups(this).delete(type);
1387
+ dispatch(window, `${type}:disconnect`);
1388
+ };
1389
+ const onPresence = () => {
1390
+ update(this);
1391
+ };
1392
+ on(window, `${type}:presence`, onPresence);
1393
+ cleanups(this).set(type, cleanup);
1394
+ });
1395
+ wrapMethod('after', target, LIFECYCLE_DISCONNECTED, function () {
1396
+ cleanups(this).forEach((cleanup) => cleanup());
1397
+ });
1398
+ };
1399
+ }
1400
+ function Consumer(namespace) {
1401
+ return function (target, key) {
1402
+ const symbol = Symbol();
1403
+ const [MAIN, SUB] = namespace.split('.');
1404
+ const prefix = `${KEY}:${MAIN}`;
1405
+ const cleanups = (instance) => {
1406
+ return (instance[symbol] ||= new Map());
1407
+ };
1408
+ const update = (instance, state) => {
1409
+ instance[key] = state;
1410
+ };
1411
+ // TODO
1412
+ wrapMethod('after', target, LIFECYCLE_CONNECTED, function () {
1413
+ // TODO
1414
+ if (SUB && this[SUB])
1415
+ return;
1416
+ // TODO
1417
+ let connected;
1418
+ const options = {
1419
+ bubbles: true
1420
+ };
1421
+ options.detail = (parent, state) => {
1422
+ // TODO
1423
+ connected = true;
1424
+ update(this, state);
1425
+ const cleanup = () => {
1426
+ off(parent, `${prefix}:update`, onUpdate);
1427
+ cleanups(this).delete(prefix);
1428
+ update(this, undefined);
1429
+ };
1430
+ const onUpdate = (event) => {
1431
+ update(this, event.detail);
1432
+ };
1433
+ on(parent, `${prefix}:update`, onUpdate);
1434
+ cleanups(this).set(prefix, cleanup);
1435
+ };
1436
+ dispatch(this, `${prefix}:presence`, options);
1437
+ // TODO: When the `Provider` element is activated after the `Consumer` element.
1438
+ !connected && setTimeout(() => dispatch(this, `${prefix}:presence`, options));
1439
+ });
1440
+ wrapMethod('after', target, LIFECYCLE_UPDATE, function (states) {
1441
+ if (cleanups(this).size && !states.has(SUB))
1442
+ return;
1443
+ cleanups(this).get(`${prefix}:${states.get(SUB)}`)?.();
1444
+ const type = `${prefix}:${this[SUB]}`;
1445
+ const cleanup = () => {
1446
+ off(window, `${type}:disconnect`, onDisconnect);
1447
+ off(window, `${type}:update`, onUpdate);
1448
+ cleanups(this).delete(type);
1449
+ update(this, undefined);
1450
+ };
1451
+ const onDisconnect = () => {
1452
+ update(this, undefined);
1453
+ };
1454
+ const onUpdate = (event) => {
1455
+ update(this, event.detail);
1456
+ };
1457
+ on(window, `${type}:disconnect`, onDisconnect);
1458
+ on(window, `${type}:update`, onUpdate);
1459
+ cleanups(this).set(type, cleanup);
1460
+ dispatch(window, `${type}:presence`);
1461
+ });
1462
+ wrapMethod('after', target, LIFECYCLE_DISCONNECTED, function () {
1463
+ cleanups(this).forEach((cleanup) => cleanup());
1464
+ });
1465
+ };
1466
+ }
1467
+
1468
+ /**
1469
+ * A method decorator that applies debounce behavior to a class method.
1470
+ * Ensures that the method executes only after the specified delay,
1471
+ * resetting the timer if called again within the delay period.
1472
+ *
1473
+ * @param {number} delay - The debounce delay in milliseconds.
1474
+ */
1475
+ function Debounce(delay = 0) {
1476
+ return function (target, key, descriptor) {
1477
+ const KEY = Symbol();
1478
+ const original = descriptor.value;
1479
+ function clear() {
1480
+ if (!Object.hasOwn(this, KEY))
1481
+ return;
1482
+ clearTimeout(this[KEY]);
1483
+ delete this[KEY];
1484
+ }
1485
+ function debounced(...args) {
1486
+ clear.call(this);
1487
+ this[KEY] = window.setTimeout(() => {
1488
+ clear.call(this);
1489
+ original.apply(this, args);
1490
+ }, delay);
1491
+ }
1492
+ descriptor.value = debounced;
1493
+ return Bind()(target, key, descriptor);
1494
+ };
1495
+ }
1496
+
1497
+ /**
1498
+ * Indicates whether the [Direction](https://mdn.io/css-direction)
1499
+ * of the element is `Right-To-Left` or `Left-To-Right`.
1500
+ */
1501
+ function Direction() {
1502
+ return toDecorator(direction);
1503
+ }
1504
+
1505
+ /**
1506
+ * The class marked with this decorator is considered a
1507
+ * [Custom Element](https://mdn.io/using-custom-elements),
1508
+ * and its name, in kebab-case, serves as the element name.
1509
+ */
1510
+ function Element() {
1511
+ return function (constructor) {
1512
+ if (isServer())
1513
+ return;
1514
+ const tag = getTag(constructor);
1515
+ if (customElements.get(tag))
1516
+ return;
1517
+ customElements.define(tag, proxy(constructor));
1518
+ };
1519
+ }
1520
+ const proxy = (constructor) => {
1521
+ return class Plus extends HTMLElement {
1522
+ #instance;
1523
+ static formAssociated = constructor['formAssociated'];
1524
+ static observedAttributes = constructor['observedAttributes'];
1525
+ constructor() {
1526
+ super();
1527
+ this.attachShadow({
1528
+ mode: 'open',
1529
+ delegatesFocus: constructor['delegatesFocus'],
1530
+ slotAssignment: constructor['slotAssignment']
1531
+ });
1532
+ this.#instance = new constructor();
1533
+ this.#instance[API_HOST] = () => this;
1534
+ call(this.#instance, LIFECYCLE_CONSTRUCTED);
1535
+ }
1536
+ adoptedCallback() {
1537
+ call(this.#instance, LIFECYCLE_ADOPTED);
1538
+ }
1539
+ attributeChangedCallback(key, prev, next) {
1540
+ if (prev != next) {
1541
+ this.#instance['RAW:' + key] = next;
1542
+ }
1543
+ }
1544
+ connectedCallback() {
1545
+ // TODO: experimental for global config
1546
+ (() => {
1547
+ const namespace = getNamespace(this.#instance);
1548
+ const tag = getTag(this.#instance);
1549
+ const properties = getConfig(namespace).elements?.[tag]?.properties;
1550
+ if (!properties)
1551
+ return;
1552
+ const defaults = Object.fromEntries(Object.entries(properties).map(([key, value]) => [key, value?.default]));
1553
+ Object.assign(this, defaults);
1554
+ })();
1555
+ // TODO
1556
+ (() => {
1557
+ const key = Object.keys(this).find((key) => key.startsWith('__reactProps'));
1558
+ const props = this[key];
1559
+ if (!props)
1560
+ return;
1561
+ for (const [key, value] of Object.entries(props)) {
1562
+ if (this[key] != undefined)
1563
+ continue;
1564
+ if (key == 'children')
1565
+ continue;
1566
+ if (typeof value != 'object')
1567
+ continue;
1568
+ this[key] = value;
1569
+ }
1570
+ })();
1571
+ this.#instance[API_CONNECTED] = true;
1572
+ call(this.#instance, LIFECYCLE_CONNECTED);
1573
+ requestUpdate(this.#instance, undefined, undefined, () => {
1574
+ call(this.#instance, LIFECYCLE_READY);
1575
+ });
1576
+ }
1577
+ disconnectedCallback() {
1578
+ call(this.#instance, LIFECYCLE_DISCONNECTED);
1579
+ }
1580
+ };
1581
+ };
1582
+
1583
+ /**
1584
+ * Provides the capability to dispatch a [CustomEvent](https://mdn.io/custom-event)
1585
+ * from an element.
1586
+ *
1587
+ * @param options An object that configures options for the event dispatcher.
1588
+ */
1589
+ function Event(options = {}) {
1590
+ return function (target, key) {
1591
+ target[key] = function (detail) {
1592
+ const element = host(this);
1593
+ const framework = getFramework(this);
1594
+ options.bubbles ??= false;
1595
+ let type = String(key);
1596
+ switch (framework) {
1597
+ // TODO: Experimental
1598
+ case 'blazor':
1599
+ options.bubbles = true;
1600
+ type = pascalCase(type);
1601
+ try {
1602
+ window['Blazor'].registerCustomEventType(type, {
1603
+ createEventArgs: (event) => ({
1604
+ detail: event.detail
1605
+ })
1606
+ });
1607
+ }
1608
+ catch { }
1609
+ break;
1610
+ case 'qwik':
1611
+ case 'solid':
1612
+ type = pascalCase(type).toLowerCase();
1613
+ break;
1614
+ case 'react':
1615
+ case 'preact':
1616
+ type = pascalCase(type);
1617
+ break;
1618
+ default:
1619
+ type = kebabCase(type);
1620
+ break;
1621
+ }
1622
+ let event;
1623
+ const resolver = getConfig(getNamespace(target)).event?.resolver;
1624
+ event ||= resolver?.({ detail, element, framework, options, type });
1625
+ event && element.dispatchEvent(event);
1626
+ event ||= dispatch(this, type, { ...options, detail });
1627
+ return event;
1628
+ };
1629
+ };
1630
+ }
1631
+
1632
+ /**
1633
+ * Indicates the host of the element.
1634
+ */
1635
+ function Host() {
1636
+ return toDecorator(host);
1637
+ }
1638
+
1639
+ /**
1640
+ * Indicates whether the direction of the element is `Right-To-Left` or not.
1641
+ */
1642
+ function IsRTL() {
1643
+ return toDecorator(isRTL);
1644
+ }
1645
+
1646
+ /**
1647
+ * Will be called whenever the specified event is delivered to the target
1648
+ * [More](https://mdn.io/add-event-listener).
1649
+ *
1650
+ * @param type A case-sensitive string representing the [Event Type](https://mdn.io/events) to listen for.
1651
+ * @param options An object that configures
1652
+ * [options](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#options)
1653
+ * for the event listener.
1654
+ */
1655
+ function Listen(type, options) {
1656
+ return function (target, key, descriptor) {
1657
+ const element = (instance) => {
1658
+ switch (options?.target) {
1659
+ case 'body':
1660
+ return window.document.body;
1661
+ case 'document':
1662
+ return window.document;
1663
+ case 'window':
1664
+ return window;
1665
+ case 'host':
1666
+ return instance;
1667
+ default:
1668
+ return instance;
1669
+ }
1670
+ };
1671
+ wrapMethod('before', target, LIFECYCLE_CONNECTED, function () {
1672
+ on(element(this), type, this[key], options);
1673
+ });
1674
+ wrapMethod('before', target, LIFECYCLE_DISCONNECTED, function () {
1675
+ off(element(this), type, this[key], options);
1676
+ });
1677
+ return Bind()(target, key, descriptor);
1678
+ };
1679
+ }
1680
+
1681
+ /**
1682
+ * Provides a way to encapsulate functionality within an element
1683
+ * and invoke it as needed, both internally and externally.
1684
+ */
1685
+ function Method() {
1686
+ return function (target, key, descriptor) {
1687
+ wrapMethod('before', target, LIFECYCLE_CONSTRUCTED, function () {
1688
+ host(this)[key] = this[key].bind(this);
1689
+ });
1690
+ };
1691
+ }
1692
+
1693
+ const CONTAINER_DATA = Symbol();
1694
+ const getContainers = (breakpoints) => {
1695
+ return Object.entries(breakpoints || {}).reduce((result, [key, breakpoint]) => {
1696
+ if (breakpoint.type !== 'container')
1697
+ return result;
1698
+ result[key] = {
1699
+ min: breakpoint.min,
1700
+ max: breakpoint.max
1701
+ };
1702
+ return result;
1703
+ }, {});
1704
+ };
1705
+ const getMedias = (breakpoints) => {
1706
+ return Object.entries(breakpoints || {}).reduce((result, [key, breakpoint]) => {
1707
+ if (breakpoint.type !== 'media')
1708
+ return result;
1709
+ const parts = [];
1710
+ const min = 'min' in breakpoint ? breakpoint.min : undefined;
1711
+ const max = 'max' in breakpoint ? breakpoint.max : undefined;
1712
+ if (min !== undefined)
1713
+ parts.push(`(min-width: ${min}px)`);
1714
+ if (max !== undefined)
1715
+ parts.push(`(max-width: ${max}px)`);
1716
+ const query = parts.join(' and ');
1717
+ if (query)
1718
+ result[key] = query;
1719
+ return result;
1720
+ }, {});
1721
+ };
1722
+ const matchContainer = (element, container) => {
1723
+ const $element = element;
1724
+ const getData = () => {
1725
+ if ($element[CONTAINER_DATA])
1726
+ return $element[CONTAINER_DATA];
1727
+ const listeners = new Set();
1728
+ const observer = new ResizeObserver(() => {
1729
+ listeners.forEach((listener) => listener());
1730
+ });
1731
+ observer.observe(element);
1732
+ $element[CONTAINER_DATA] = { listeners, observer };
1733
+ return $element[CONTAINER_DATA];
1734
+ };
1735
+ const getMatches = () => {
1736
+ const width = element.offsetWidth;
1737
+ const matches = (container.min === undefined || width >= container.min) &&
1738
+ (container.max === undefined || width <= container.max);
1739
+ return matches;
1740
+ };
1741
+ const addEventListener = (type, listener) => {
1742
+ getData().listeners.add(listener);
1743
+ };
1744
+ const removeEventListener = (type, listener) => {
1745
+ const data = getData();
1746
+ data.listeners.delete(listener);
1747
+ if (data.listeners.size !== 0)
1748
+ return;
1749
+ data.observer.disconnect();
1750
+ delete $element[CONTAINER_DATA];
1751
+ };
1752
+ return {
1753
+ get matches() {
1754
+ return getMatches();
1755
+ },
1756
+ addEventListener,
1757
+ removeEventListener
1758
+ };
1759
+ };
1760
+ function Overrides() {
1761
+ return function (target, key) {
1762
+ const DISPOSERS = Symbol();
1763
+ const breakpoints = getConfig(getNamespace(target)).breakpoints || {};
1764
+ const containers = getContainers(breakpoints);
1765
+ const medias = getMedias(breakpoints);
1766
+ wrapMethod('after', target, LIFECYCLE_UPDATE, function (states) {
1767
+ if (!states.has(key))
1768
+ return;
1769
+ const disposers = (this[DISPOSERS] ??= new Map());
1770
+ const overrides = this[key] || {};
1771
+ const activeKeys = new Set(disposers.keys());
1772
+ const overrideKeys = Object.keys(overrides);
1773
+ const containerKeys = overrideKeys.filter((breakpoint) => breakpoint in containers);
1774
+ const mediaKeys = overrideKeys.filter((breakpoint) => breakpoint in medias);
1775
+ let timeout;
1776
+ let next = {};
1777
+ const apply = (key) => {
1778
+ clearTimeout(timeout);
1779
+ Object.assign(next, overrides[key]);
1780
+ timeout = setTimeout(() => {
1781
+ Object.assign(host(this), overrides[key]);
1782
+ next = {};
1783
+ }, 0);
1784
+ };
1785
+ for (const overrideKey of overrideKeys) {
1786
+ if (activeKeys.delete(overrideKey))
1787
+ continue;
1788
+ const breakpoint = breakpoints[overrideKey];
1789
+ if (!breakpoint)
1790
+ continue;
1791
+ switch (breakpoint.type) {
1792
+ case 'container': {
1793
+ const container = containers[overrideKey];
1794
+ if (!container)
1795
+ break;
1796
+ const containerQueryList = matchContainer(host(this), container);
1797
+ const change = () => {
1798
+ for (const containerKey of containerKeys) {
1799
+ if (matchContainer(host(this), containers[containerKey]).matches) {
1800
+ apply(containerKey);
1801
+ }
1802
+ }
1803
+ };
1804
+ containerQueryList.addEventListener('change', change);
1805
+ const disposer = () => {
1806
+ containerQueryList.removeEventListener('change', change);
1807
+ };
1808
+ disposers.set(overrideKey, disposer);
1809
+ if (!containerQueryList.matches)
1810
+ break;
1811
+ change();
1812
+ break;
1813
+ }
1814
+ case 'media': {
1815
+ const media = medias[overrideKey];
1816
+ if (!media)
1817
+ break;
1818
+ const mediaQueryList = window.matchMedia(media);
1819
+ const change = () => {
1820
+ for (const mediaKey of mediaKeys) {
1821
+ if (window.matchMedia(medias[mediaKey]).matches) {
1822
+ apply(mediaKey);
1823
+ }
1824
+ }
1825
+ };
1826
+ mediaQueryList.addEventListener('change', change);
1827
+ const disposer = () => {
1828
+ mediaQueryList.removeEventListener('change', change);
1829
+ };
1830
+ disposers.set(overrideKey, disposer);
1831
+ if (!mediaQueryList.matches)
1832
+ break;
1833
+ change();
1834
+ break;
1835
+ }
1836
+ }
1837
+ }
1838
+ for (const activeKey of activeKeys) {
1839
+ const disposer = disposers.get(activeKey);
1840
+ disposer();
1841
+ disposers.delete(activeKey);
1842
+ }
1843
+ });
1844
+ wrapMethod('after', target, LIFECYCLE_DISCONNECTED, function () {
1845
+ const disposers = (this[DISPOSERS] ??= new Map());
1846
+ disposers.forEach((disposer) => disposer());
1847
+ disposers.clear();
1848
+ });
1849
+ };
1850
+ }
1851
+
1852
+ /**
1853
+ * Creates a reactive property, reflecting a corresponding attribute value,
1854
+ * and updates the element when the property is set.
1855
+ */
1856
+ function Property(options) {
1857
+ return function (target, key, descriptor) {
1858
+ // Unique symbol for property storage to avoid naming conflicts
1859
+ const KEY = Symbol();
1860
+ // Unique symbol for the lock flag to prevent infinite loops during updates
1861
+ const LOCKED = Symbol();
1862
+ // Calculate attribute name from the property key if not explicitly provided
1863
+ const attribute = options?.attribute || kebabCase(key);
1864
+ // Store the original setter (if it exists) to preserve its behavior
1865
+ const originalSetter = descriptor?.set;
1866
+ // Register the attribute in the observedAttributes array for the element
1867
+ (target.constructor['observedAttributes'] ||= []).push(attribute);
1868
+ // Getter function to retrieve the property value
1869
+ function get() {
1870
+ return this[KEY];
1871
+ }
1872
+ // Setter function to update the property value and trigger updates
1873
+ function set(value) {
1874
+ // Store the previous value
1875
+ const previous = this[KEY];
1876
+ // Store the new value
1877
+ const next = value;
1878
+ // Skip updates if the value hasn't changed and no custom setter is defined
1879
+ if (!originalSetter && next === previous)
1880
+ return;
1881
+ // If a custom setter exists, call it with the new value
1882
+ if (originalSetter) {
1883
+ originalSetter.call(this, next);
1884
+ }
1885
+ // Otherwise, update the property directly
1886
+ else {
1887
+ this[KEY] = next;
1888
+ }
1889
+ // Request an update
1890
+ requestUpdate(this, key, previous, (skipped) => {
1891
+ // Skip if the update was aborted
1892
+ if (skipped)
1893
+ return;
1894
+ // If reflection is enabled, update the corresponding attribute
1895
+ if (!options?.reflect)
1896
+ return;
1897
+ // Lock to prevent infinite loops
1898
+ this[LOCKED] = true;
1899
+ // Update the attribute
1900
+ updateAttribute(this, attribute, next);
1901
+ // Unlock
1902
+ this[LOCKED] = false;
1903
+ });
1904
+ }
1905
+ // Override the property descriptor if a custom setter exists
1906
+ if (originalSetter) {
1907
+ descriptor.set = set;
1908
+ }
1909
+ // Attach the getter and setter to the target class property if no descriptor exists
1910
+ if (!descriptor) {
1911
+ defineProperty(target, key, { configurable: true, get, set });
1912
+ }
1913
+ /**
1914
+ * Define a raw property setter to handle updates that trigger from the `attributeChangedCallback`,
1915
+ * To intercept and process raw attribute values before they are assigned to the property
1916
+ */
1917
+ defineProperty(target, 'RAW:' + attribute, {
1918
+ set(value) {
1919
+ if (!this[LOCKED]) {
1920
+ // Convert the raw value and set it to the corresponding property
1921
+ this[key] = toProperty(value, options?.type);
1922
+ }
1923
+ }
1924
+ });
1925
+ // Attach getter and setter to the host element on construction
1926
+ wrapMethod('before', target, LIFECYCLE_CONSTRUCTED, function () {
1927
+ const get = () => {
1928
+ if (descriptor && !descriptor.get) {
1929
+ throw new Error(`Property '${key}' does not have a getter. Unable to retrieve value.`);
1930
+ }
1931
+ return this[key];
1932
+ };
1933
+ const set = (value) => {
1934
+ if (descriptor && !descriptor.set) {
1935
+ throw new Error(`Property '${key}' does not have a setter. Unable to assign value.`);
1936
+ }
1937
+ this[key] = value;
1938
+ };
1939
+ defineProperty(host(this), key, { configurable: true, get, set });
1940
+ });
1941
+ /**
1942
+ * TODO: Review these behaviors again.
1943
+ *
1944
+ * When a property has a reflect and either a getter, a setter, or both are available,
1945
+ * three approaches are possible:
1946
+ *
1947
+ * 1. Only a getter is present: The attribute updates after each render is completed.
1948
+ * 2. Only a setter is present: The attribute updates after each setter call.
1949
+ * 3. Both getter and setter are present: The attribute is updated via the setter call
1950
+ * and also after each render is completed, resulting in two attribute update processes.
1951
+ */
1952
+ if (options?.reflect && descriptor?.get) {
1953
+ wrapMethod('before', target, LIFECYCLE_UPDATED, function () {
1954
+ // Lock to prevent infinite loops
1955
+ this[LOCKED] = true;
1956
+ // Update the attribute
1957
+ updateAttribute(this, attribute, this[key]);
1958
+ // Unlock
1959
+ this[LOCKED] = false;
1960
+ });
1961
+ }
1962
+ };
1963
+ }
1964
+
1965
+ /**
1966
+ * Selects the first element in the shadow dom that matches a specified CSS selector.
1967
+ *
1968
+ * @param selectors A string containing one or more selectors to match.
1969
+ * This string must be a valid CSS selector string; if it isn't, a `SyntaxError` exception is thrown. See
1970
+ * [Locating DOM elements using selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors)
1971
+ * for more about selectors and how to manage them.
1972
+ */
1973
+ function Query(selectors) {
1974
+ return toDecorator(query, selectors);
1975
+ }
1976
+
1977
+ /**
1978
+ * Selects all elements in the shadow dom that match a specified CSS selector.
1979
+ *
1980
+ * @param selectors A string containing one or more selectors to match against.
1981
+ * This string must be a valid
1982
+ * [CSS selector](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_selectors)
1983
+ * string; if it's not, a `SyntaxError` exception is thrown. See
1984
+ * [Locating DOM elements using selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors)
1985
+ * for more information about using selectors to identify elements.
1986
+ * Multiple selectors may be specified by separating them using commas.
1987
+ */
1988
+ function QueryAll(selectors) {
1989
+ return toDecorator(queryAll, selectors);
1990
+ }
1991
+
1992
+ /**
1993
+ * Returns the slots name.
1994
+ */
1995
+ function Slots() {
1996
+ return toDecorator(slots);
1997
+ }
1998
+
1999
+ /**
2000
+ * Applying this decorator to any `class property` will trigger the
2001
+ * element to re-render upon the desired property changes.
2002
+ */
2003
+ function State() {
2004
+ return function (target, key) {
2005
+ const KEY = Symbol();
2006
+ const name = String(key);
2007
+ defineProperty(target, key, {
2008
+ enumerable: true,
2009
+ configurable: true,
2010
+ get() {
2011
+ return this[KEY];
2012
+ },
2013
+ set(next) {
2014
+ const previous = this[KEY];
2015
+ if (next === previous)
2016
+ return;
2017
+ this[KEY] = next;
2018
+ requestUpdate(this, name, previous);
2019
+ }
2020
+ });
2021
+ };
2022
+ }
2023
+
2024
+ // TODO: check the logic
2025
+ function Style() {
2026
+ return function (target, key) {
2027
+ const LAST = Symbol();
2028
+ const SHEET = Symbol();
2029
+ wrapMethod('before', target, LIFECYCLE_UPDATED, function () {
2030
+ let sheet = this[SHEET];
2031
+ let value = this[key];
2032
+ const update = (value) => (result) => {
2033
+ if (value && value !== this[LAST])
2034
+ return;
2035
+ sheet.replaceSync(toCssString(result));
2036
+ this[LAST] = undefined;
2037
+ };
2038
+ if (!sheet) {
2039
+ sheet = new CSSStyleSheet();
2040
+ this[SHEET] = sheet;
2041
+ shadowRoot(this)?.adoptedStyleSheets.push(sheet);
2042
+ }
2043
+ if (typeof value === 'function') {
2044
+ value = value.call(this);
2045
+ }
2046
+ if (value instanceof Promise) {
2047
+ value.then(update((this[LAST] = value))).catch((error) => {
2048
+ throw new Error('TODO', { cause: error });
2049
+ });
2050
+ }
2051
+ else {
2052
+ update()(value);
2053
+ }
2054
+ });
2055
+ };
2056
+ }
2057
+ const toCssString = (input, parent) => {
2058
+ if (typeof input == 'string') {
2059
+ return input.trim();
2060
+ }
2061
+ if (Array.isArray(input)) {
2062
+ return input
2063
+ .map((item) => toCssString(item, parent))
2064
+ .filter(Boolean)
2065
+ .join('\n');
2066
+ }
2067
+ if (typeof input != 'object')
2068
+ return '';
2069
+ let result = '';
2070
+ for (const key of Object.keys(input)) {
2071
+ const value = input[key];
2072
+ const ignore = [null, undefined, false].includes(value);
2073
+ if (ignore)
2074
+ continue;
2075
+ const cssKey = key.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
2076
+ if (typeof value === 'object') {
2077
+ result += `${cssKey} {${toCssString(value, cssKey)}}`;
2078
+ }
2079
+ else {
2080
+ result += `${cssKey}: ${value};`;
2081
+ }
2082
+ }
2083
+ return parent ? result : `:host {${result}}`;
2084
+ };
2085
+
2086
+ /**
2087
+ * Monitors `@Property` and `@State` to detect changes.
2088
+ * The decorated method will be called after any changes,
2089
+ * with the `key`, `newValue`, and `oldValue` as parameters.
2090
+ * If the `key` is not defined, all `@Property` and `@State` are considered.
2091
+ *
2092
+ * @param keys Collection of `@Property` and `@State` names.
2093
+ * @param immediate Triggers the callback immediately after initialization.
2094
+ */
2095
+ function Watch(keys, immediate) {
2096
+ return function (target, key) {
2097
+ // Gets all keys
2098
+ const all = [keys].flat().filter((item) => item);
2099
+ // Registers a lifecycle to detect changes.
2100
+ wrapMethod('after', target, LIFECYCLE_UPDATED, function (states) {
2101
+ // Skips the logic if 'immediate' wasn't passed.
2102
+ if (!immediate && !this[API_RENDER_COMPLETED])
2103
+ return;
2104
+ // Loops the keys.
2105
+ states.forEach((previous, item) => {
2106
+ // Skips the current key.
2107
+ if (all.length && !all.includes(item))
2108
+ return;
2109
+ // Invokes the method with parameters.
2110
+ this[key](this[item], previous, item);
2111
+ });
2112
+ });
2113
+ };
2114
+ }
2115
+
2116
+ const attributes = attributes$2;
2117
+ const html = html$1;
2118
+ const styles = styles$1;
2119
+
2120
+ export { Bind, Consumer, Debounce, Direction, Element, Event, Host, IsRTL, Listen, Method, Overrides, Property, Provider, Query, QueryAll, Slots, State, Style, Watch, attributes as a, classes, direction, dispatch, getConfig, getConfigCreator, html as h, host, isCSSColor, isRTL, off, on, query, queryAll, styles as s, setConfig, setConfigCreator, slots, toCSSColor, toCSSUnit, toUnit };