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