@mgdis/core-ui-helpers 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +8 -8
  3. package/rollup.config.mjs +3 -3
  4. package/src/angular/mg-angular-logger/mg-angular-logger.spec.ts +1 -1
  5. package/src/angular/mg-angular-logger/mg-angular-logger.ts +2 -1
  6. package/src/locale/index.spec.ts +10 -1
  7. package/src/locale/locale.spec.ts +43 -18
  8. package/src/locale/locale.ts +13 -5
  9. package/src/playwright/utils/utils.spec.ts +16 -9
  10. package/src/playwright/utils/utils.ts +14 -6
  11. package/src/stencil/ide/cem.spec.ts +4 -4
  12. package/src/stencil/ide/cem.ts +9 -9
  13. package/src/stencil/ide/ide.ts +26 -26
  14. package/src/storybook/stencil/stencil.spec.ts +30 -6
  15. package/src/storybook/stencil/stencil.ts +24 -13
  16. package/src/tests/index.spec.ts +7 -1
  17. package/src/tests/unit/unit.conf.ts +9 -2
  18. package/src/tests/unit/unit.spec.ts +103 -61
  19. package/src/tests/unit/unit.ts +38 -11
  20. package/src/utils/attributes/id/id.spec.ts +9 -6
  21. package/src/utils/attributes/id/id.ts +3 -2
  22. package/src/utils/components/components.spec.ts +6 -6
  23. package/src/utils/components/components.ts +19 -5
  24. package/src/utils/elements/elements.ts +4 -2
  25. package/src/utils/number/number.spec.ts +2 -2
  26. package/src/utils/object/object.spec.ts +2 -2
  27. package/src/utils/object/object.ts +2 -1
  28. package/src/utils/string/string.spec.ts +12 -5
  29. package/src/utils/string/string.ts +2 -1
  30. package/src/utils/windows/windows.spec.ts +6 -2
  31. package/src/vue/mg-model/mg-model.ts +7 -2
  32. package/vitest.config.mts +1 -1
  33. package/.turbo/turbo-build.log +0 -52
  34. package/dist/angular/index.cjs +0 -27
  35. package/dist/angular/index.cjs.map +0 -1
  36. package/dist/angular/index.d.ts +0 -21
  37. package/dist/angular/index.js +0 -25
  38. package/dist/angular/index.js.map +0 -1
  39. package/dist/angular/index.umd.js +0 -33
  40. package/dist/angular/index.umd.js.map +0 -1
  41. package/dist/locale/index.cjs +0 -188
  42. package/dist/locale/index.cjs.map +0 -1
  43. package/dist/locale/index.d.ts +0 -110
  44. package/dist/locale/index.js +0 -179
  45. package/dist/locale/index.js.map +0 -1
  46. package/dist/locale/index.umd.js +0 -194
  47. package/dist/locale/index.umd.js.map +0 -1
  48. package/dist/playwright/index.cjs +0 -130
  49. package/dist/playwright/index.cjs.map +0 -1
  50. package/dist/playwright/index.d.ts +0 -39
  51. package/dist/playwright/index.js +0 -126
  52. package/dist/playwright/index.js.map +0 -1
  53. package/dist/playwright/index.umd.js +0 -136
  54. package/dist/playwright/index.umd.js.map +0 -1
  55. package/dist/stencil/index.cjs +0 -363
  56. package/dist/stencil/index.cjs.map +0 -1
  57. package/dist/stencil/index.d.ts +0 -222
  58. package/dist/stencil/index.js +0 -357
  59. package/dist/stencil/index.js.map +0 -1
  60. package/dist/stencil/index.umd.js +0 -369
  61. package/dist/stencil/index.umd.js.map +0 -1
  62. package/dist/storybook/index.cjs +0 -2333
  63. package/dist/storybook/index.cjs.map +0 -1
  64. package/dist/storybook/index.d.ts +0 -85
  65. package/dist/storybook/index.js +0 -2327
  66. package/dist/storybook/index.js.map +0 -1
  67. package/dist/storybook/index.umd.js +0 -2339
  68. package/dist/storybook/index.umd.js.map +0 -1
  69. package/dist/tests/index.cjs +0 -300
  70. package/dist/tests/index.cjs.map +0 -1
  71. package/dist/tests/index.d.ts +0 -100
  72. package/dist/tests/index.js +0 -294
  73. package/dist/tests/index.js.map +0 -1
  74. package/dist/tests/index.umd.js +0 -306
  75. package/dist/tests/index.umd.js.map +0 -1
  76. package/dist/utils/index.cjs +0 -433
  77. package/dist/utils/index.cjs.map +0 -1
  78. package/dist/utils/index.d.ts +0 -265
  79. package/dist/utils/index.js +0 -409
  80. package/dist/utils/index.js.map +0 -1
  81. package/dist/utils/index.umd.js +0 -439
  82. package/dist/utils/index.umd.js.map +0 -1
  83. package/dist/vue/index.cjs +0 -1934
  84. package/dist/vue/index.cjs.map +0 -1
  85. package/dist/vue/index.d.ts +0 -35
  86. package/dist/vue/index.js +0 -1932
  87. package/dist/vue/index.js.map +0 -1
  88. package/dist/vue/index.umd.js +0 -1940
  89. package/dist/vue/index.umd.js.map +0 -1
@@ -1,2333 +0,0 @@
1
- 'use strict';
2
-
3
- // src/app-data/index.ts
4
- var BUILD = {
5
- updatable: true,
6
- slotRelocation: true};
7
-
8
- /*
9
- Stencil Client Platform v4.43.5 | MIT Licensed | https://stenciljs.com
10
- */
11
-
12
-
13
- // src/utils/constants.ts
14
- var SVG_NS = "http://www.w3.org/2000/svg";
15
- var HTML_NS = "http://www.w3.org/1999/xhtml";
16
-
17
- // src/client/client-host-ref.ts
18
- var getHostRef = (ref) => {
19
- if (ref.__stencil__getHostRef) {
20
- return ref.__stencil__getHostRef();
21
- }
22
- return void 0;
23
- };
24
- var isMemberInElement = (elm, memberName) => memberName in elm;
25
- var XLINK_NS = "http://www.w3.org/1999/xlink";
26
- var win = typeof window !== "undefined" ? window : {};
27
- var plt = {
28
- $flags$: 0,
29
- $resourcesUrl$: "",
30
- jmp: (h2) => h2(),
31
- raf: (h2) => requestAnimationFrame(h2),
32
- ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),
33
- rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),
34
- ce: (eventName, opts) => new CustomEvent(eventName, opts)
35
- };
36
- var updateFallbackSlotVisibility = (elm) => {
37
- const childNodes = internalCall(elm, "childNodes");
38
- if (elm.tagName && elm.tagName.includes("-") && elm["s-cr"] && elm.tagName !== "SLOT-FB") {
39
- getHostSlotNodes(childNodes, elm.tagName).forEach((slotNode) => {
40
- if (slotNode.nodeType === 1 /* ElementNode */ && slotNode.tagName === "SLOT-FB") {
41
- if (getSlotChildSiblings(slotNode, getSlotName(slotNode), false).length) {
42
- slotNode.hidden = true;
43
- } else {
44
- slotNode.hidden = false;
45
- }
46
- }
47
- });
48
- }
49
- let i2 = 0;
50
- for (i2 = 0; i2 < childNodes.length; i2++) {
51
- const childNode = childNodes[i2];
52
- if (childNode.nodeType === 1 /* ElementNode */ && internalCall(childNode, "childNodes").length) {
53
- updateFallbackSlotVisibility(childNode);
54
- }
55
- }
56
- };
57
- var getSlottedChildNodes = (childNodes) => {
58
- const result = [];
59
- for (let i2 = 0; i2 < childNodes.length; i2++) {
60
- const slottedNode = childNodes[i2]["s-nr"] || void 0;
61
- if (slottedNode && slottedNode.isConnected) {
62
- result.push(slottedNode);
63
- }
64
- }
65
- return result;
66
- };
67
- function getHostSlotNodes(childNodes, hostName, slotName) {
68
- let i2 = 0;
69
- let slottedNodes = [];
70
- let childNode;
71
- for (; i2 < childNodes.length; i2++) {
72
- childNode = childNodes[i2];
73
- if (childNode["s-sr"] && (!hostName || childNode["s-hn"] === hostName) && (slotName === void 0 || getSlotName(childNode) === slotName)) {
74
- slottedNodes.push(childNode);
75
- if (typeof slotName !== "undefined") return slottedNodes;
76
- }
77
- slottedNodes = [...slottedNodes, ...getHostSlotNodes(childNode.childNodes, hostName, slotName)];
78
- }
79
- return slottedNodes;
80
- }
81
- var getSlotChildSiblings = (slot, slotName, includeSlot = true) => {
82
- const childNodes = [];
83
- if (includeSlot && slot["s-sr"] || !slot["s-sr"]) childNodes.push(slot);
84
- let node = slot;
85
- while (node = node.nextSibling) {
86
- if (getSlotName(node) === slotName && (includeSlot || !node["s-sr"])) childNodes.push(node);
87
- }
88
- return childNodes;
89
- };
90
- var isNodeLocatedInSlot = (nodeToRelocate, slotName) => {
91
- if (nodeToRelocate.nodeType === 1 /* ElementNode */) {
92
- if (nodeToRelocate.getAttribute("slot") === null && slotName === "") {
93
- return true;
94
- }
95
- if (nodeToRelocate.getAttribute("slot") === slotName) {
96
- return true;
97
- }
98
- return false;
99
- }
100
- if (nodeToRelocate["s-sn"] === slotName) {
101
- return true;
102
- }
103
- return slotName === "";
104
- };
105
- var getSlotName = (node) => typeof node["s-sn"] === "string" ? node["s-sn"] : node.nodeType === 1 && node.getAttribute("slot") || void 0;
106
- function patchSlotNode(node) {
107
- if (node.assignedElements || node.assignedNodes || !node["s-sr"]) return;
108
- const assignedFactory = (elementsOnly) => (function(opts) {
109
- const toReturn = [];
110
- const slotName = this["s-sn"];
111
- if (opts == null ? void 0 : opts.flatten) {
112
- console.error(`
113
- Flattening is not supported for Stencil non-shadow slots.
114
- You can use \`.childNodes\` to nested slot fallback content.
115
- If you have a particular use case, please open an issue on the Stencil repo.
116
- `);
117
- }
118
- const parent = this["s-cr"].parentElement;
119
- const slottedNodes = parent.__childNodes ? parent.childNodes : getSlottedChildNodes(parent.childNodes);
120
- slottedNodes.forEach((n) => {
121
- if (slotName === getSlotName(n)) {
122
- toReturn.push(n);
123
- }
124
- });
125
- if (elementsOnly) {
126
- return toReturn.filter((n) => n.nodeType === 1 /* ElementNode */);
127
- }
128
- return toReturn;
129
- }).bind(node);
130
- node.assignedElements = assignedFactory(true);
131
- node.assignedNodes = assignedFactory(false);
132
- }
133
- function dispatchSlotChangeEvent(elm) {
134
- elm.dispatchEvent(new CustomEvent("slotchange", { bubbles: false, cancelable: false, composed: false }));
135
- }
136
- function findSlotFromSlottedNode(slottedNode, parentHost) {
137
- var _a;
138
- parentHost = parentHost || ((_a = slottedNode["s-ol"]) == null ? void 0 : _a.parentElement);
139
- if (!parentHost) return { slotNode: null, slotName: "" };
140
- const slotName = slottedNode["s-sn"] = getSlotName(slottedNode) || "";
141
- const childNodes = internalCall(parentHost, "childNodes");
142
- const slotNode = getHostSlotNodes(childNodes, parentHost.tagName, slotName)[0];
143
- return { slotNode, slotName };
144
- }
145
- function internalCall(node, method) {
146
- if ("__" + method in node) {
147
- const toReturn = node["__" + method];
148
- if (typeof toReturn !== "function") return toReturn;
149
- return toReturn.bind(node);
150
- } else {
151
- if (typeof node[method] !== "function") return node[method];
152
- return node[method].bind(node);
153
- }
154
- }
155
-
156
- // src/utils/helpers.ts
157
- var isDef = (v) => v != null && v !== void 0;
158
- var isComplexType = (o) => {
159
- o = typeof o;
160
- return o === "object" || o === "function";
161
- };
162
-
163
- // src/runtime/vdom/h.ts
164
- var h = (nodeName, vnodeData, ...children) => {
165
- let child = null;
166
- let key = null;
167
- let slotName = null;
168
- let simple = false;
169
- let lastSimple = false;
170
- const vNodeChildren = [];
171
- const walk = (c) => {
172
- for (let i2 = 0; i2 < c.length; i2++) {
173
- child = c[i2];
174
- if (Array.isArray(child)) {
175
- walk(child);
176
- } else if (child != null && typeof child !== "boolean") {
177
- if (simple = !isComplexType(child)) {
178
- child = String(child);
179
- }
180
- if (simple && lastSimple) {
181
- vNodeChildren[vNodeChildren.length - 1].$text$ += child;
182
- } else {
183
- vNodeChildren.push(simple ? newVNode(null, child) : child);
184
- }
185
- lastSimple = simple;
186
- }
187
- }
188
- };
189
- walk(children);
190
- const vnode = newVNode(nodeName, null);
191
- vnode.$attrs$ = vnodeData;
192
- if (vNodeChildren.length > 0) {
193
- vnode.$children$ = vNodeChildren;
194
- }
195
- {
196
- vnode.$key$ = key;
197
- }
198
- {
199
- vnode.$name$ = slotName;
200
- }
201
- return vnode;
202
- };
203
- var newVNode = (tag, text) => {
204
- const vnode = {
205
- $flags$: 0,
206
- $tag$: tag,
207
- // Normalize undefined to null to prevent rendering "undefined" as text
208
- $text$: text != null ? text : null,
209
- $elm$: null,
210
- $children$: null
211
- };
212
- {
213
- vnode.$attrs$ = null;
214
- }
215
- {
216
- vnode.$key$ = null;
217
- }
218
- {
219
- vnode.$name$ = null;
220
- }
221
- return vnode;
222
- };
223
- var Host = {};
224
- var isHost = (node) => node && node.$tag$ === Host;
225
- var setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags, initialRender) => {
226
- if (oldValue === newValue) {
227
- return;
228
- }
229
- let isProp = isMemberInElement(elm, memberName);
230
- let ln = memberName.toLowerCase();
231
- if (memberName === "class") {
232
- const classList = elm.classList;
233
- const oldClasses = parseClassList(oldValue);
234
- let newClasses = parseClassList(newValue);
235
- {
236
- classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));
237
- classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));
238
- }
239
- } else if (memberName === "style") {
240
- {
241
- for (const prop in oldValue) {
242
- if (!newValue || newValue[prop] == null) {
243
- if (prop.includes("-")) {
244
- elm.style.removeProperty(prop);
245
- } else {
246
- elm.style[prop] = "";
247
- }
248
- }
249
- }
250
- }
251
- for (const prop in newValue) {
252
- if (!oldValue || newValue[prop] !== oldValue[prop]) {
253
- if (prop.includes("-")) {
254
- elm.style.setProperty(prop, newValue[prop]);
255
- } else {
256
- elm.style[prop] = newValue[prop];
257
- }
258
- }
259
- }
260
- } else if (memberName === "key") ; else if (memberName === "ref") {
261
- if (newValue) {
262
- queueRefAttachment(newValue, elm);
263
- }
264
- } else if ((!elm.__lookupSetter__(memberName)) && memberName[0] === "o" && memberName[1] === "n") {
265
- if (memberName[2] === "-") {
266
- memberName = memberName.slice(3);
267
- } else if (isMemberInElement(win, ln)) {
268
- memberName = ln.slice(2);
269
- } else {
270
- memberName = ln[2] + memberName.slice(3);
271
- }
272
- if (oldValue || newValue) {
273
- const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX);
274
- memberName = memberName.replace(CAPTURE_EVENT_REGEX, "");
275
- if (oldValue) {
276
- plt.rel(elm, memberName, oldValue, capture);
277
- }
278
- if (newValue) {
279
- plt.ael(elm, memberName, newValue, capture);
280
- }
281
- }
282
- } else if (memberName[0] === "a" && memberName.startsWith("attr:")) {
283
- const propName = memberName.slice(5);
284
- let attrName;
285
- {
286
- const hostRef = getHostRef(elm);
287
- if (hostRef && hostRef.$cmpMeta$ && hostRef.$cmpMeta$.$members$) {
288
- const memberMeta = hostRef.$cmpMeta$.$members$[propName];
289
- if (memberMeta && memberMeta[1]) {
290
- attrName = memberMeta[1];
291
- }
292
- }
293
- }
294
- if (!attrName) {
295
- attrName = propName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
296
- }
297
- if (newValue == null || newValue === false) {
298
- if (newValue !== false || elm.getAttribute(attrName) === "") {
299
- elm.removeAttribute(attrName);
300
- }
301
- } else {
302
- elm.setAttribute(attrName, newValue === true ? "" : newValue);
303
- }
304
- return;
305
- } else if (memberName[0] === "p" && memberName.startsWith("prop:")) {
306
- const propName = memberName.slice(5);
307
- try {
308
- elm[propName] = newValue;
309
- } catch (e) {
310
- }
311
- return;
312
- } else {
313
- const isComplex = isComplexType(newValue);
314
- if ((isProp || isComplex && newValue !== null) && !isSvg) {
315
- try {
316
- if (!elm.tagName.includes("-")) {
317
- const n = newValue == null ? "" : newValue;
318
- if (memberName === "list") {
319
- isProp = false;
320
- } else if (oldValue == null || elm[memberName] !== n) {
321
- if (typeof elm.__lookupSetter__(memberName) === "function") {
322
- elm[memberName] = n;
323
- } else {
324
- elm.setAttribute(memberName, n);
325
- }
326
- }
327
- } else if (elm[memberName] !== newValue) {
328
- elm[memberName] = newValue;
329
- }
330
- } catch (e) {
331
- }
332
- }
333
- let xlink = false;
334
- {
335
- if (ln !== (ln = ln.replace(/^xlink\:?/, ""))) {
336
- memberName = ln;
337
- xlink = true;
338
- }
339
- }
340
- if (newValue == null || newValue === false) {
341
- if (newValue !== false || elm.getAttribute(memberName) === "") {
342
- if (xlink) {
343
- elm.removeAttributeNS(XLINK_NS, memberName);
344
- } else {
345
- elm.removeAttribute(memberName);
346
- }
347
- }
348
- } else if ((!isProp || flags & 4 /* isHost */ || isSvg) && !isComplex && elm.nodeType === 1 /* ElementNode */) {
349
- newValue = newValue === true ? "" : newValue;
350
- if (xlink) {
351
- elm.setAttributeNS(XLINK_NS, memberName, newValue);
352
- } else {
353
- elm.setAttribute(memberName, newValue);
354
- }
355
- }
356
- }
357
- };
358
- var parseClassListRegex = /\s/;
359
- var parseClassList = (value) => {
360
- if (typeof value === "object" && value && "baseVal" in value) {
361
- value = value.baseVal;
362
- }
363
- if (!value || typeof value !== "string") {
364
- return [];
365
- }
366
- return value.split(parseClassListRegex);
367
- };
368
- var CAPTURE_EVENT_SUFFIX = "Capture";
369
- var CAPTURE_EVENT_REGEX = new RegExp(CAPTURE_EVENT_SUFFIX + "$");
370
-
371
- // src/runtime/vdom/update-element.ts
372
- var updateElement = (oldVnode, newVnode, isSvgMode2, isInitialRender) => {
373
- const elm = newVnode.$elm$.nodeType === 11 /* DocumentFragment */ && newVnode.$elm$.host ? newVnode.$elm$.host : newVnode.$elm$;
374
- const oldVnodeAttrs = oldVnode && oldVnode.$attrs$ || {};
375
- const newVnodeAttrs = newVnode.$attrs$ || {};
376
- {
377
- for (const memberName of sortedAttrNames(Object.keys(oldVnodeAttrs))) {
378
- if (!(memberName in newVnodeAttrs)) {
379
- setAccessor(
380
- elm,
381
- memberName,
382
- oldVnodeAttrs[memberName],
383
- void 0,
384
- isSvgMode2,
385
- newVnode.$flags$);
386
- }
387
- }
388
- }
389
- for (const memberName of sortedAttrNames(Object.keys(newVnodeAttrs))) {
390
- setAccessor(
391
- elm,
392
- memberName,
393
- oldVnodeAttrs[memberName],
394
- newVnodeAttrs[memberName],
395
- isSvgMode2,
396
- newVnode.$flags$);
397
- }
398
- };
399
- function sortedAttrNames(attrNames) {
400
- return attrNames.includes("ref") ? (
401
- // we need to sort these to ensure that `'ref'` is the last attr
402
- [...attrNames.filter((attr) => attr !== "ref"), "ref"]
403
- ) : (
404
- // no need to sort, return the original array
405
- attrNames
406
- );
407
- }
408
-
409
- // src/runtime/vdom/vdom-render.ts
410
- var scopeId;
411
- var contentRef;
412
- var hostTagName;
413
- var useNativeShadowDom = false;
414
- var checkSlotFallbackVisibility = false;
415
- var checkSlotRelocate = false;
416
- var isSvgMode = false;
417
- var refCallbacksToRemove = [];
418
- var refCallbacksToAttach = [];
419
- var createElm = (oldParentVNode, newParentVNode, childIndex) => {
420
- var _a;
421
- const newVNode2 = newParentVNode.$children$[childIndex];
422
- let i2 = 0;
423
- let elm;
424
- let childNode;
425
- let oldVNode;
426
- if (!useNativeShadowDom) {
427
- checkSlotRelocate = true;
428
- if (newVNode2.$tag$ === "slot") {
429
- newVNode2.$flags$ |= newVNode2.$children$ ? (
430
- // slot element has fallback content
431
- // still create an element that "mocks" the slot element
432
- 2 /* isSlotFallback */
433
- ) : (
434
- // slot element does not have fallback content
435
- // create an html comment we'll use to always reference
436
- // where actual slot content should sit next to
437
- 1 /* isSlotReference */
438
- );
439
- }
440
- }
441
- if (newVNode2.$text$ != null) {
442
- elm = newVNode2.$elm$ = win.document.createTextNode(newVNode2.$text$);
443
- } else if (newVNode2.$flags$ & 1 /* isSlotReference */) {
444
- elm = newVNode2.$elm$ = win.document.createTextNode("");
445
- {
446
- updateElement(null, newVNode2, isSvgMode);
447
- }
448
- } else {
449
- if (!isSvgMode) {
450
- isSvgMode = newVNode2.$tag$ === "svg";
451
- }
452
- if (!win.document) {
453
- throw new Error("You are trying to render a Stencil component in an environment that doesn't support the DOM.");
454
- }
455
- elm = newVNode2.$elm$ = win.document.createElementNS(
456
- isSvgMode ? SVG_NS : HTML_NS,
457
- !useNativeShadowDom && BUILD.slotRelocation && newVNode2.$flags$ & 2 /* isSlotFallback */ ? "slot-fb" : newVNode2.$tag$
458
- ) ;
459
- if (isSvgMode && newVNode2.$tag$ === "foreignObject") {
460
- isSvgMode = false;
461
- }
462
- {
463
- updateElement(null, newVNode2, isSvgMode);
464
- }
465
- if (isDef(scopeId) && elm["s-si"] !== scopeId) {
466
- elm.classList.add(elm["s-si"] = scopeId);
467
- }
468
- if (newVNode2.$children$) {
469
- const appendTarget = newVNode2.$tag$ === "template" ? elm.content : elm;
470
- for (i2 = 0; i2 < newVNode2.$children$.length; ++i2) {
471
- childNode = createElm(oldParentVNode, newVNode2, i2);
472
- if (childNode) {
473
- appendTarget.appendChild(childNode);
474
- }
475
- }
476
- }
477
- {
478
- if (newVNode2.$tag$ === "svg") {
479
- isSvgMode = false;
480
- } else if (elm.tagName === "foreignObject") {
481
- isSvgMode = true;
482
- }
483
- }
484
- }
485
- elm["s-hn"] = hostTagName;
486
- {
487
- if (newVNode2.$flags$ & (2 /* isSlotFallback */ | 1 /* isSlotReference */)) {
488
- elm["s-sr"] = true;
489
- elm["s-cr"] = contentRef;
490
- elm["s-sn"] = newVNode2.$name$ || "";
491
- elm["s-rf"] = (_a = newVNode2.$attrs$) == null ? void 0 : _a.ref;
492
- patchSlotNode(elm);
493
- oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];
494
- if (oldVNode && oldVNode.$tag$ === newVNode2.$tag$ && oldParentVNode.$elm$) {
495
- relocateToHostRoot(oldParentVNode.$elm$);
496
- }
497
- {
498
- addRemoveSlotScopedClass(contentRef, elm, newParentVNode.$elm$, oldParentVNode == null ? void 0 : oldParentVNode.$elm$);
499
- }
500
- }
501
- }
502
- return elm;
503
- };
504
- var relocateToHostRoot = (parentElm) => {
505
- plt.$flags$ |= 1 /* isTmpDisconnected */;
506
- const host = parentElm.closest(hostTagName.toLowerCase());
507
- if (host != null) {
508
- const contentRefNode = Array.from(host.__childNodes || host.childNodes).find(
509
- (ref) => ref["s-cr"]
510
- );
511
- const childNodeArray = Array.from(
512
- parentElm.__childNodes || parentElm.childNodes
513
- );
514
- for (const childNode of contentRefNode ? childNodeArray.reverse() : childNodeArray) {
515
- if (childNode["s-sh"] != null) {
516
- insertBefore(host, childNode, contentRefNode != null ? contentRefNode : null);
517
- childNode["s-sh"] = void 0;
518
- checkSlotRelocate = true;
519
- }
520
- }
521
- }
522
- plt.$flags$ &= -2 /* isTmpDisconnected */;
523
- };
524
- var putBackInOriginalLocation = (parentElm, recursive) => {
525
- plt.$flags$ |= 1 /* isTmpDisconnected */;
526
- const oldSlotChildNodes = Array.from(parentElm.__childNodes || parentElm.childNodes);
527
- if (parentElm["s-sr"]) {
528
- let node = parentElm;
529
- while (node = node.nextSibling) {
530
- if (node && node["s-sn"] === parentElm["s-sn"] && node["s-sh"] === hostTagName) {
531
- oldSlotChildNodes.push(node);
532
- }
533
- }
534
- }
535
- for (let i2 = oldSlotChildNodes.length - 1; i2 >= 0; i2--) {
536
- const childNode = oldSlotChildNodes[i2];
537
- if (childNode["s-hn"] !== hostTagName && childNode["s-ol"]) {
538
- insertBefore(referenceNode(childNode).parentNode, childNode, referenceNode(childNode));
539
- childNode["s-ol"].remove();
540
- childNode["s-ol"] = void 0;
541
- childNode["s-sh"] = void 0;
542
- checkSlotRelocate = true;
543
- }
544
- if (recursive) {
545
- putBackInOriginalLocation(childNode, recursive);
546
- }
547
- }
548
- plt.$flags$ &= -2 /* isTmpDisconnected */;
549
- };
550
- var addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {
551
- let containerElm = parentElm["s-cr"] && parentElm["s-cr"].parentNode || parentElm;
552
- let childNode;
553
- if (containerElm.shadowRoot && containerElm.tagName === hostTagName) {
554
- containerElm = containerElm.shadowRoot;
555
- }
556
- if (parentVNode.$tag$ === "template") {
557
- containerElm = containerElm.content;
558
- }
559
- for (; startIdx <= endIdx; ++startIdx) {
560
- if (vnodes[startIdx]) {
561
- childNode = createElm(null, parentVNode, startIdx);
562
- if (childNode) {
563
- vnodes[startIdx].$elm$ = childNode;
564
- insertBefore(containerElm, childNode, referenceNode(before) );
565
- }
566
- }
567
- }
568
- };
569
- var removeVnodes = (vnodes, startIdx, endIdx) => {
570
- for (let index = startIdx; index <= endIdx; ++index) {
571
- const vnode = vnodes[index];
572
- if (vnode) {
573
- const elm = vnode.$elm$;
574
- nullifyVNodeRefs(vnode);
575
- if (elm) {
576
- {
577
- checkSlotFallbackVisibility = true;
578
- if (elm["s-ol"]) {
579
- elm["s-ol"].remove();
580
- } else {
581
- putBackInOriginalLocation(elm, true);
582
- }
583
- }
584
- elm.remove();
585
- }
586
- }
587
- }
588
- };
589
- var updateChildren = (parentElm, oldCh, newVNode2, newCh, isInitialRender = false) => {
590
- let oldStartIdx = 0;
591
- let newStartIdx = 0;
592
- let idxInOld = 0;
593
- let i2 = 0;
594
- let oldEndIdx = oldCh.length - 1;
595
- let oldStartVnode = oldCh[0];
596
- let oldEndVnode = oldCh[oldEndIdx];
597
- let newEndIdx = newCh.length - 1;
598
- let newStartVnode = newCh[0];
599
- let newEndVnode = newCh[newEndIdx];
600
- let node;
601
- let elmToMove;
602
- const containerElm = newVNode2.$tag$ === "template" ? parentElm.content : parentElm;
603
- while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
604
- if (oldStartVnode == null) {
605
- oldStartVnode = oldCh[++oldStartIdx];
606
- } else if (oldEndVnode == null) {
607
- oldEndVnode = oldCh[--oldEndIdx];
608
- } else if (newStartVnode == null) {
609
- newStartVnode = newCh[++newStartIdx];
610
- } else if (newEndVnode == null) {
611
- newEndVnode = newCh[--newEndIdx];
612
- } else if (isSameVnode(oldStartVnode, newStartVnode, isInitialRender)) {
613
- patch(oldStartVnode, newStartVnode, isInitialRender);
614
- oldStartVnode = oldCh[++oldStartIdx];
615
- newStartVnode = newCh[++newStartIdx];
616
- } else if (isSameVnode(oldEndVnode, newEndVnode, isInitialRender)) {
617
- patch(oldEndVnode, newEndVnode, isInitialRender);
618
- oldEndVnode = oldCh[--oldEndIdx];
619
- newEndVnode = newCh[--newEndIdx];
620
- } else if (isSameVnode(oldStartVnode, newEndVnode, isInitialRender)) {
621
- if ((oldStartVnode.$tag$ === "slot" || newEndVnode.$tag$ === "slot")) {
622
- putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);
623
- }
624
- patch(oldStartVnode, newEndVnode, isInitialRender);
625
- insertBefore(containerElm, oldStartVnode.$elm$, oldEndVnode.$elm$.nextSibling);
626
- oldStartVnode = oldCh[++oldStartIdx];
627
- newEndVnode = newCh[--newEndIdx];
628
- } else if (isSameVnode(oldEndVnode, newStartVnode, isInitialRender)) {
629
- if ((oldStartVnode.$tag$ === "slot" || newEndVnode.$tag$ === "slot")) {
630
- putBackInOriginalLocation(oldEndVnode.$elm$.parentNode, false);
631
- }
632
- patch(oldEndVnode, newStartVnode, isInitialRender);
633
- insertBefore(containerElm, oldEndVnode.$elm$, oldStartVnode.$elm$);
634
- oldEndVnode = oldCh[--oldEndIdx];
635
- newStartVnode = newCh[++newStartIdx];
636
- } else {
637
- idxInOld = -1;
638
- {
639
- for (i2 = oldStartIdx; i2 <= oldEndIdx; ++i2) {
640
- if (oldCh[i2] && oldCh[i2].$key$ !== null && oldCh[i2].$key$ === newStartVnode.$key$) {
641
- idxInOld = i2;
642
- break;
643
- }
644
- }
645
- }
646
- if (idxInOld >= 0) {
647
- elmToMove = oldCh[idxInOld];
648
- if (elmToMove.$tag$ !== newStartVnode.$tag$) {
649
- node = createElm(oldCh && oldCh[newStartIdx], newVNode2, idxInOld);
650
- } else {
651
- patch(elmToMove, newStartVnode, isInitialRender);
652
- oldCh[idxInOld] = void 0;
653
- node = elmToMove.$elm$;
654
- }
655
- newStartVnode = newCh[++newStartIdx];
656
- } else {
657
- node = createElm(oldCh && oldCh[newStartIdx], newVNode2, newStartIdx);
658
- newStartVnode = newCh[++newStartIdx];
659
- }
660
- if (node) {
661
- {
662
- insertBefore(
663
- referenceNode(oldStartVnode.$elm$).parentNode,
664
- node,
665
- referenceNode(oldStartVnode.$elm$)
666
- );
667
- }
668
- }
669
- }
670
- }
671
- if (oldStartIdx > oldEndIdx) {
672
- addVnodes(
673
- parentElm,
674
- newCh[newEndIdx + 1] == null ? null : newCh[newEndIdx + 1].$elm$,
675
- newVNode2,
676
- newCh,
677
- newStartIdx,
678
- newEndIdx
679
- );
680
- } else if (newStartIdx > newEndIdx) {
681
- removeVnodes(oldCh, oldStartIdx, oldEndIdx);
682
- }
683
- };
684
- var isSameVnode = (leftVNode, rightVNode, isInitialRender = false) => {
685
- if (leftVNode.$tag$ === rightVNode.$tag$) {
686
- if (leftVNode.$tag$ === "slot") {
687
- return leftVNode.$name$ === rightVNode.$name$;
688
- }
689
- if (!isInitialRender) {
690
- return leftVNode.$key$ === rightVNode.$key$;
691
- }
692
- if (isInitialRender && !leftVNode.$key$ && rightVNode.$key$) {
693
- leftVNode.$key$ = rightVNode.$key$;
694
- }
695
- return true;
696
- }
697
- return false;
698
- };
699
- var referenceNode = (node) => node && node["s-ol"] || node;
700
- var patch = (oldVNode, newVNode2, isInitialRender = false) => {
701
- const elm = newVNode2.$elm$ = oldVNode.$elm$;
702
- const oldChildren = oldVNode.$children$;
703
- const newChildren = newVNode2.$children$;
704
- const tag = newVNode2.$tag$;
705
- const text = newVNode2.$text$;
706
- let defaultHolder;
707
- if (text == null) {
708
- {
709
- isSvgMode = tag === "svg" ? true : tag === "foreignObject" ? false : isSvgMode;
710
- }
711
- {
712
- if (tag === "slot" && !useNativeShadowDom) {
713
- if (oldVNode.$name$ !== newVNode2.$name$) {
714
- newVNode2.$elm$["s-sn"] = newVNode2.$name$ || "";
715
- relocateToHostRoot(newVNode2.$elm$.parentElement);
716
- }
717
- }
718
- updateElement(oldVNode, newVNode2, isSvgMode);
719
- }
720
- if (oldChildren !== null && newChildren !== null) {
721
- updateChildren(elm, oldChildren, newVNode2, newChildren, isInitialRender);
722
- } else if (newChildren !== null) {
723
- if (oldVNode.$text$ !== null) {
724
- elm.textContent = "";
725
- }
726
- addVnodes(elm, null, newVNode2, newChildren, 0, newChildren.length - 1);
727
- } else if (
728
- // don't do this on initial render as it can cause non-hydrated content to be removed
729
- !isInitialRender && BUILD.updatable && oldChildren !== null
730
- ) {
731
- removeVnodes(oldChildren, 0, oldChildren.length - 1);
732
- } else ;
733
- if (isSvgMode && tag === "svg") {
734
- isSvgMode = false;
735
- }
736
- } else if ((defaultHolder = elm["s-cr"])) {
737
- defaultHolder.parentNode.textContent = text;
738
- } else if (oldVNode.$text$ !== text) {
739
- elm.data = text;
740
- }
741
- };
742
- var relocateNodes = [];
743
- var markSlotContentForRelocation = (elm) => {
744
- let node;
745
- let hostContentNodes;
746
- let j;
747
- const children = elm.__childNodes || elm.childNodes;
748
- for (const childNode of children) {
749
- if (childNode["s-sr"] && (node = childNode["s-cr"]) && node.parentNode) {
750
- hostContentNodes = node.parentNode.__childNodes || node.parentNode.childNodes;
751
- const slotName = childNode["s-sn"];
752
- for (j = hostContentNodes.length - 1; j >= 0; j--) {
753
- node = hostContentNodes[j];
754
- if (!node["s-cn"] && !node["s-nr"] && node["s-hn"] !== childNode["s-hn"] && (!node["s-sh"] || node["s-sh"] !== childNode["s-hn"])) {
755
- if (isNodeLocatedInSlot(node, slotName)) {
756
- let relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
757
- checkSlotFallbackVisibility = true;
758
- node["s-sn"] = node["s-sn"] || slotName;
759
- if (relocateNodeData) {
760
- relocateNodeData.$nodeToRelocate$["s-sh"] = childNode["s-hn"];
761
- relocateNodeData.$slotRefNode$ = childNode;
762
- } else {
763
- node["s-sh"] = childNode["s-hn"];
764
- relocateNodes.push({
765
- $slotRefNode$: childNode,
766
- $nodeToRelocate$: node
767
- });
768
- }
769
- if (node["s-sr"]) {
770
- relocateNodes.map((relocateNode) => {
771
- if (isNodeLocatedInSlot(relocateNode.$nodeToRelocate$, node["s-sn"])) {
772
- relocateNodeData = relocateNodes.find((r) => r.$nodeToRelocate$ === node);
773
- if (relocateNodeData && !relocateNode.$slotRefNode$) {
774
- relocateNode.$slotRefNode$ = relocateNodeData.$slotRefNode$;
775
- }
776
- }
777
- });
778
- }
779
- } else if (!relocateNodes.some((r) => r.$nodeToRelocate$ === node)) {
780
- relocateNodes.push({
781
- $nodeToRelocate$: node
782
- });
783
- }
784
- }
785
- }
786
- }
787
- if (childNode.nodeType === 1 /* ElementNode */) {
788
- markSlotContentForRelocation(childNode);
789
- }
790
- }
791
- };
792
- var nullifyVNodeRefs = (vNode) => {
793
- {
794
- if (vNode.$attrs$ && vNode.$attrs$.ref) {
795
- refCallbacksToRemove.push(() => vNode.$attrs$.ref(null));
796
- }
797
- vNode.$children$ && vNode.$children$.map(nullifyVNodeRefs);
798
- }
799
- };
800
- var queueRefAttachment = (refCallback, elm) => {
801
- {
802
- refCallbacksToAttach.push(() => refCallback(elm));
803
- }
804
- };
805
- var flushQueuedRefCallbacks = () => {
806
- {
807
- refCallbacksToRemove.forEach((cb) => cb());
808
- refCallbacksToRemove.length = 0;
809
- refCallbacksToAttach.forEach((cb) => cb());
810
- refCallbacksToAttach.length = 0;
811
- }
812
- };
813
- var insertBefore = (parent, newNode, reference, isInitialLoad) => {
814
- {
815
- if (typeof newNode["s-sn"] === "string" && !!newNode["s-sr"] && !!newNode["s-cr"]) {
816
- addRemoveSlotScopedClass(newNode["s-cr"], newNode, parent, newNode.parentElement);
817
- } else if (typeof newNode["s-sn"] === "string") {
818
- parent.insertBefore(newNode, reference);
819
- const { slotNode } = findSlotFromSlottedNode(newNode);
820
- if (slotNode && !isInitialLoad) dispatchSlotChangeEvent(slotNode);
821
- return newNode;
822
- }
823
- }
824
- if (parent.__insertBefore) {
825
- return parent.__insertBefore(newNode, reference);
826
- } else {
827
- return parent == null ? void 0 : parent.insertBefore(newNode, reference);
828
- }
829
- };
830
- function addRemoveSlotScopedClass(reference, slotNode, newParent, oldParent) {
831
- var _a, _b;
832
- let scopeId2;
833
- if (reference && typeof slotNode["s-sn"] === "string" && !!slotNode["s-sr"] && reference.parentNode && reference.parentNode["s-sc"] && (scopeId2 = slotNode["s-si"] || reference.parentNode["s-sc"])) {
834
- const scopeName = slotNode["s-sn"];
835
- const hostName = slotNode["s-hn"];
836
- (_a = newParent.classList) == null ? void 0 : _a.add(scopeId2 + "-s");
837
- if (oldParent && ((_b = oldParent.classList) == null ? void 0 : _b.contains(scopeId2 + "-s"))) {
838
- let child = (oldParent.__childNodes || oldParent.childNodes)[0];
839
- let found = false;
840
- while (child) {
841
- if (child["s-sn"] !== scopeName && child["s-hn"] === hostName && !!child["s-sr"]) {
842
- found = true;
843
- break;
844
- }
845
- child = child.nextSibling;
846
- }
847
- if (!found) oldParent.classList.remove(scopeId2 + "-s");
848
- }
849
- }
850
- }
851
- var renderVdom = (hostRef, renderFnResults, isInitialLoad = false) => {
852
- var _a, _b, _c, _d, _e;
853
- const hostElm = hostRef.$hostElement$;
854
- const cmpMeta = hostRef.$cmpMeta$;
855
- const oldVNode = hostRef.$vnode$ || newVNode(null, null);
856
- const isHostElement = isHost(renderFnResults);
857
- const rootVnode = isHostElement ? renderFnResults : h(null, null, renderFnResults);
858
- hostTagName = hostElm.tagName;
859
- if (cmpMeta.$attrsToReflect$) {
860
- rootVnode.$attrs$ = rootVnode.$attrs$ || {};
861
- cmpMeta.$attrsToReflect$.forEach(([propName, attribute]) => {
862
- if (BUILD.serializer && hostRef.$serializerValues$.has(propName)) {
863
- rootVnode.$attrs$[attribute] = hostRef.$serializerValues$.get(propName);
864
- } else {
865
- rootVnode.$attrs$[attribute] = hostElm[propName];
866
- }
867
- });
868
- }
869
- if (isInitialLoad && rootVnode.$attrs$) {
870
- for (const key of Object.keys(rootVnode.$attrs$)) {
871
- if (hostElm.hasAttribute(key) && !["key", "ref", "style", "class"].includes(key)) {
872
- rootVnode.$attrs$[key] = hostElm[key];
873
- }
874
- }
875
- }
876
- rootVnode.$tag$ = null;
877
- rootVnode.$flags$ |= 4 /* isHost */;
878
- hostRef.$vnode$ = rootVnode;
879
- rootVnode.$elm$ = oldVNode.$elm$ = hostElm.shadowRoot || hostElm ;
880
- {
881
- scopeId = hostElm["s-sc"];
882
- }
883
- useNativeShadowDom = !!(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) && !(cmpMeta.$flags$ & 128 /* shadowNeedsScopedCss */);
884
- {
885
- contentRef = hostElm["s-cr"];
886
- checkSlotFallbackVisibility = false;
887
- }
888
- patch(oldVNode, rootVnode, isInitialLoad);
889
- {
890
- plt.$flags$ |= 1 /* isTmpDisconnected */;
891
- if (checkSlotRelocate) {
892
- markSlotContentForRelocation(rootVnode.$elm$);
893
- for (const relocateData of relocateNodes) {
894
- const nodeToRelocate = relocateData.$nodeToRelocate$;
895
- if (!nodeToRelocate["s-ol"] && win.document) {
896
- const orgLocationNode = win.document.createTextNode("");
897
- orgLocationNode["s-nr"] = nodeToRelocate;
898
- insertBefore(
899
- nodeToRelocate.parentNode,
900
- nodeToRelocate["s-ol"] = orgLocationNode,
901
- nodeToRelocate,
902
- isInitialLoad
903
- );
904
- }
905
- }
906
- for (const relocateData of relocateNodes) {
907
- const nodeToRelocate = relocateData.$nodeToRelocate$;
908
- const slotRefNode = relocateData.$slotRefNode$;
909
- if (nodeToRelocate.nodeType === 1 /* ElementNode */ && isInitialLoad) {
910
- nodeToRelocate["s-ih"] = (_a = nodeToRelocate.hidden) != null ? _a : false;
911
- }
912
- if (slotRefNode) {
913
- const parentNodeRef = slotRefNode.parentNode;
914
- let insertBeforeNode = slotRefNode.nextSibling;
915
- if (insertBeforeNode && insertBeforeNode.nodeType === 1 /* ElementNode */) {
916
- let orgLocationNode = (_b = nodeToRelocate["s-ol"]) == null ? void 0 : _b.previousSibling;
917
- while (orgLocationNode) {
918
- let refNode = (_c = orgLocationNode["s-nr"]) != null ? _c : null;
919
- if (refNode && refNode["s-sn"] === nodeToRelocate["s-sn"] && parentNodeRef === (refNode.__parentNode || refNode.parentNode)) {
920
- refNode = refNode.nextSibling;
921
- while (refNode === nodeToRelocate || (refNode == null ? void 0 : refNode["s-sr"])) {
922
- refNode = refNode == null ? void 0 : refNode.nextSibling;
923
- }
924
- if (!refNode || !refNode["s-nr"]) {
925
- insertBeforeNode = refNode;
926
- break;
927
- }
928
- }
929
- orgLocationNode = orgLocationNode.previousSibling;
930
- }
931
- }
932
- const parent = nodeToRelocate.__parentNode || nodeToRelocate.parentNode;
933
- const nextSibling = nodeToRelocate.__nextSibling || nodeToRelocate.nextSibling;
934
- if (!insertBeforeNode && parentNodeRef !== parent || nextSibling !== insertBeforeNode) {
935
- if (nodeToRelocate !== insertBeforeNode) {
936
- insertBefore(parentNodeRef, nodeToRelocate, insertBeforeNode, isInitialLoad);
937
- if (nodeToRelocate.nodeType === 8 /* CommentNode */ && nodeToRelocate.nodeValue.startsWith("s-nt-")) {
938
- const textNode = win.document.createTextNode(nodeToRelocate.nodeValue.replace(/^s-nt-/, ""));
939
- textNode["s-hn"] = nodeToRelocate["s-hn"];
940
- textNode["s-sn"] = nodeToRelocate["s-sn"];
941
- textNode["s-sh"] = nodeToRelocate["s-sh"];
942
- textNode["s-sr"] = nodeToRelocate["s-sr"];
943
- textNode["s-ol"] = nodeToRelocate["s-ol"];
944
- textNode["s-ol"]["s-nr"] = textNode;
945
- insertBefore(nodeToRelocate.parentNode, textNode, nodeToRelocate, isInitialLoad);
946
- nodeToRelocate.parentNode.removeChild(nodeToRelocate);
947
- }
948
- if (nodeToRelocate.nodeType === 1 /* ElementNode */ && nodeToRelocate.tagName !== "SLOT-FB") {
949
- nodeToRelocate.hidden = (_d = nodeToRelocate["s-ih"]) != null ? _d : false;
950
- }
951
- }
952
- }
953
- nodeToRelocate && typeof slotRefNode["s-rf"] === "function" && slotRefNode["s-rf"](slotRefNode);
954
- } else if (nodeToRelocate.nodeType === 1 /* ElementNode */) {
955
- nodeToRelocate.hidden = true;
956
- }
957
- }
958
- }
959
- if (checkSlotFallbackVisibility) {
960
- updateFallbackSlotVisibility(rootVnode.$elm$);
961
- }
962
- plt.$flags$ &= -2 /* isTmpDisconnected */;
963
- relocateNodes.length = 0;
964
- }
965
- if (!useNativeShadowDom && !(cmpMeta.$flags$ & 1 /* shadowDomEncapsulation */) && hostElm["s-cr"]) {
966
- const children = rootVnode.$elm$.__childNodes || rootVnode.$elm$.childNodes;
967
- for (const childNode of children) {
968
- if (childNode["s-hn"] !== hostTagName && !childNode["s-sh"]) {
969
- if (isInitialLoad && childNode["s-ih"] == null) {
970
- childNode["s-ih"] = (_e = childNode.hidden) != null ? _e : false;
971
- }
972
- if (childNode.nodeType === 1 /* ElementNode */) {
973
- childNode.hidden = true;
974
- } else if (childNode.nodeType === 3 /* TextNode */ && !!childNode.nodeValue.trim()) {
975
- const textCommentNode = win.document.createComment("s-nt-" + childNode.nodeValue);
976
- textCommentNode["s-sn"] = childNode["s-sn"];
977
- insertBefore(childNode.parentNode, textCommentNode, childNode, isInitialLoad);
978
- childNode.parentNode.removeChild(childNode);
979
- }
980
- }
981
- }
982
- }
983
- contentRef = void 0;
984
- flushQueuedRefCallbacks();
985
- };
986
-
987
- /**
988
- * @type {import('htmlfy').Config}
989
- */
990
- const CONFIG = {
991
- content_wrap: 0,
992
- ignore: [],
993
- ignore_with: '!i-£___£%_',
994
- strict: false,
995
- tab_size: 2,
996
- tag_wrap: 0,
997
- trim: []
998
- };
999
-
1000
- const VOID_ELEMENTS = [
1001
- 'area', 'base', 'br', 'col', 'embed', 'hr',
1002
- 'img', 'input', 'link', 'meta',
1003
- 'param', 'source', 'track', 'wbr'
1004
- ];
1005
-
1006
- /**
1007
- * Defined by state.js and configuration.
1008
- *
1009
- * CONTENT_IGNORE_PLACEHOLDER
1010
- * SELF_CLOSING_PLACEHOLDER
1011
- * ATTRIBUTE_IGNORE_PLACEHOLDER
1012
- */
1013
-
1014
- /**
1015
- * @typedef {object} Constants
1016
- * @property {string} CONTENT_IGNORE_PLACEHOLDER
1017
- * @property {string} SELF_CLOSING_PLACEHOLDER
1018
- * @property {string} ATTRIBUTE_IGNORE_PLACEHOLDER
1019
- */
1020
- /**
1021
- * @typedef {object} State
1022
- * @property {boolean} checked_html - If passed in HTML has been checked for HTML within it.
1023
- * @property {import("htmlfy").Config} config - Validated configuration.
1024
- * @property {boolean} ignored
1025
- * @property {Constants} constants - Constant strings, influenced by ignore_with.
1026
- */
1027
-
1028
- /**
1029
- * @type State
1030
- *
1031
- * `constants` prefixes and suffixes must be in sync with those in utils.js
1032
- */
1033
- const state = {
1034
- checked_html: false,
1035
- config: { ...CONFIG },
1036
- ignored: false,
1037
- constants: {
1038
- CONTENT_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}_`,
1039
- SELF_CLOSING_PLACEHOLDER: `${CONFIG.ignore_with}/_>`,
1040
- ATTRIBUTE_IGNORE_PLACEHOLDER: `${CONFIG.ignore_with}=_`
1041
- }
1042
- };
1043
-
1044
- /**
1045
- *
1046
- * @returns {State}
1047
- */
1048
- const getState = () => state;
1049
-
1050
- /**
1051
- *
1052
- * @param {Partial<State>} new_state
1053
- */
1054
- const setState = (new_state) => Object.assign(state, new_state);
1055
-
1056
- /**
1057
- * Checks if content contains at least one HTML element or custom HTML element.
1058
- *
1059
- * The first regex matches void and self-closing elements.
1060
- * The second regex matches normal HTML elements, plus they can have a namespace.
1061
- * The third regex matches custom HTML elemtns, plus they can have a namespace.
1062
- *
1063
- * HTML elements should begin with a letter, and can end with a letter or number.
1064
- *
1065
- * Custom elements must begin with a letter, and can end with a letter, number,
1066
- * hyphen, underscore, or period. However, all letters must be lowercase.
1067
- * They must have at least one hyphen, and can only have periods and underscores if there is a hyphen.
1068
- *
1069
- * These regexes are based on
1070
- * https://w3c.github.io/html-reference/syntax.html#tag-name
1071
- * and
1072
- * https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
1073
- * respectively.
1074
- *
1075
- * @param {string} content Content to evaluate.
1076
- * @returns {boolean} A boolean.
1077
- */
1078
- const isHtml = (content) => {
1079
- setState({ checked_html: true });
1080
-
1081
- return /<(?:[A-Za-z]+[A-Za-z0-9]*)(?:\s+.*?)*?\/{0,1}>/.test(content) ||
1082
- /<(?<Element>(?:[A-Za-z]+[A-Za-z0-9]*:)?(?:[A-Za-z]+[A-Za-z0-9]*))(?:\s+.*?)*?>(?:.|\n)*?<\/{1}\k<Element>>/.test(content) ||
1083
- /<(?<Element>(?:[a-z][a-z0-9._]*:)?[a-z][a-z0-9._]*-[a-z0-9._-]+)(?:\s+.*?)*?>(?:.|\n)*?<\/{1}\k<Element>>/.test(content)
1084
- };
1085
-
1086
- /**
1087
- * Generic utility which merges two objects.
1088
- *
1089
- * @param {any} current Original object.
1090
- * @param {any} updates Object to merge with original.
1091
- * @returns {any}
1092
- */
1093
- const mergeObjects = (current, updates) => {
1094
- if (!current || !updates)
1095
- throw new Error("Both 'current' and 'updates' must be passed-in to mergeObjects()")
1096
-
1097
- /**
1098
- * @type {any}
1099
- */
1100
- let merged;
1101
-
1102
- if (Array.isArray(current)) {
1103
- merged = structuredClone(current).concat(updates);
1104
- } else if (typeof current === 'object') {
1105
- merged = { ...current };
1106
- for (let key of Object.keys(updates)) {
1107
- if (typeof updates[key] !== 'object') {
1108
- merged[key] = updates[key];
1109
- } else {
1110
- /* key is an object, run mergeObjects again. */
1111
- merged[key] = mergeObjects(merged[key] || {}, updates[key]);
1112
- }
1113
- }
1114
- }
1115
-
1116
- return merged
1117
- };
1118
-
1119
- /**
1120
- * Merge a user config with the default config.
1121
- *
1122
- * @param {import('htmlfy').Config} default_config The default config.
1123
- * @param {import('htmlfy').UserConfig} config The user config.
1124
- * @returns {import('htmlfy').Config}
1125
- */
1126
- const mergeConfig = (default_config, config) => {
1127
- const validated_config = mergeObjects(default_config, config);
1128
-
1129
- /* Below `constants` prefixes and suffixes must be in sync with those in state.js */
1130
- setState({
1131
- config: validated_config,
1132
- constants: {
1133
- CONTENT_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}_`,
1134
- SELF_CLOSING_PLACEHOLDER: `${validated_config.ignore_with}/_>`,
1135
- ATTRIBUTE_IGNORE_PLACEHOLDER: `${validated_config.ignore_with}=_`
1136
- }
1137
- });
1138
- return validated_config
1139
- };
1140
-
1141
- /**
1142
- *
1143
- * @param {string} html
1144
- */
1145
- const protectAttributes = (html) => {
1146
- const { constants } = getState();
1147
-
1148
- html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1149
- return match.replace(capture, (match) => {
1150
- return match
1151
- .replace(/\n/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'nl!')
1152
- .replace(/\r/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'cr!')
1153
- .replace(/\s/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'ws!')
1154
- })
1155
- });
1156
-
1157
- return html
1158
- };
1159
-
1160
- /**
1161
- *
1162
- * @param {string} html
1163
- */
1164
- const protectContent = (html) => {
1165
- const { constants } = getState();
1166
-
1167
- return html
1168
- .replace(/\n/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!')
1169
- .replace(/\r/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!')
1170
- .replace(/\s/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'ws!')
1171
- };
1172
-
1173
- /**
1174
- *
1175
- * @param {string} html
1176
- */
1177
- const finalProtectContent = (html) => {
1178
- const regex = /\s*<([a-zA-Z0-9:-]+)[^>]*>\n\s*<\/\1>(?=\n[ ]*[^\n]*__!i-£___£%__[^\n]*\n)(\n[ ]*\S[^\n]*\n)|<([a-zA-Z0-9:-]+)[^>]*>(?=\n[ ]*[^\n]*__!i-£___£%__[^\n]*\n)(\n[ ]*\S[^\n]*\n\s*)<\/\3>/g;
1179
- const { constants } = getState();
1180
-
1181
- return html
1182
- .replace(regex, (/** @type {string} */match, p1, p2, p3, p4) => {
1183
- const text_to_protect = p2 || p4;
1184
-
1185
- if (!text_to_protect)
1186
- return match
1187
-
1188
- const protected_text = text_to_protect
1189
- .replace(/\n/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!')
1190
- .replace(/\r/g, constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!')
1191
- .replace(/\s/g, constants.CONTENT_IGNORE_PLACEHOLDER + "ws!");
1192
-
1193
- return match.replace(text_to_protect, protected_text)
1194
- })
1195
- };
1196
-
1197
- /**
1198
- * Replace html brackets with ignore string.
1199
- *
1200
- * @param {string} html
1201
- * @returns {string}
1202
- */
1203
- const setIgnoreAttribute = (html) => {
1204
- const regex = /<([A-Za-z][A-Za-z0-9]*|[a-z][a-z0-9._]*-[a-z0-9._-]+)((?:\s+[A-Za-z0-9_-]+="[^"]*"|\s*[a-z]*)*)>/g;
1205
- const { constants } = getState();
1206
-
1207
- html = html.replace(regex, (/** @type {string} */match, p1, p2) => {
1208
- return match.replace(p2, (match) => {
1209
- return match
1210
- .replace(/</g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'lt!')
1211
- .replace(/>/g, constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'gt!')
1212
- })
1213
- });
1214
-
1215
- return html
1216
- };
1217
-
1218
- /**
1219
- * Trim leading and trailing whitespace characters.
1220
- *
1221
- * @param {string} html
1222
- * @param {string[]} trim
1223
- * @returns {string}
1224
- */
1225
- const trimify = (html, trim) => {
1226
- for (let e = 0; e < trim.length; e++) {
1227
- /* Whitespace character must be escaped with '\' or RegExp() won't include it. */
1228
- const leading_whitespace = new RegExp(`(<${trim[e]}[^>]*>)\\s+`, "g");
1229
- const trailing_whitespace = new RegExp(`\\s+(</${trim[e]}>)`, "g");
1230
-
1231
- html = html
1232
- .replace(leading_whitespace, '$1')
1233
- .replace(trailing_whitespace, '$1');
1234
- }
1235
-
1236
- return html
1237
- };
1238
-
1239
- /**
1240
- *
1241
- * @param {string} html
1242
- */
1243
- const unprotectAttributes = (html) => {
1244
- const { constants } = getState();
1245
-
1246
- html = html.replace(/<[\w:\-]+([^>]*[^\/])>/g, (/** @type {string} */match, /** @type {any} */capture) => {
1247
- return match.replace(capture, (match) => {
1248
- return match
1249
- .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'nl!', "g"), '\n')
1250
- .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'cr!', "g"), '\r')
1251
- .replace(new RegExp(constants.ATTRIBUTE_IGNORE_PLACEHOLDER + 'ws!', "g"), ' ')
1252
- })
1253
- });
1254
-
1255
- return html
1256
- };
1257
-
1258
- /**
1259
- *
1260
- * @param {string} html
1261
- */
1262
- const unprotectContent = (html) => {
1263
- const { constants } = getState();
1264
-
1265
- html = html.replace(new RegExp(`.*${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!.*`, "g"), (/** @type {string} */match) => {
1266
- return match.replace(new RegExp(`${constants.CONTENT_IGNORE_PLACEHOLDER}[a-z]{2}!`, "g"), (match) => {
1267
- return match
1268
- .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'nl!', "g"), '\n')
1269
- .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'cr!', "g"), '\r')
1270
- .replace(new RegExp(constants.CONTENT_IGNORE_PLACEHOLDER + 'ws!', "g"), ' ')
1271
- })
1272
- });
1273
-
1274
- return html
1275
- };
1276
-
1277
- /**
1278
- * Replace ignore string with html brackets.
1279
- *
1280
- * @param {string} html
1281
- * @returns {string}
1282
- */
1283
- const unsetIgnoreAttribute = (html) => {
1284
- /* Regex to find opening tags and capture their attributes. */
1285
- const tagRegex = /<([\w:\-]+)([^>]*)>/g;
1286
- const { constants } = getState();
1287
- const escapedIgnoreString = constants.ATTRIBUTE_IGNORE_PLACEHOLDER.replace(
1288
- /[-\/\\^$*+?.()|[\]{}]/g,
1289
- "\\$&"
1290
- );
1291
- const ltPlaceholderRegex = new RegExp(escapedIgnoreString + "lt!", "g");
1292
- const gtPlaceholderRegex = new RegExp(escapedIgnoreString + "gt!", "g");
1293
-
1294
- return html.replace(
1295
- tagRegex,
1296
- (
1297
- /** @type {string} */ fullMatch,
1298
- /** @type {string} */ tagName,
1299
- /** @type {string} */ attributesCapture
1300
- ) => {
1301
- const processedAttributes = attributesCapture
1302
- .replace(ltPlaceholderRegex, "<")
1303
- .replace(gtPlaceholderRegex, ">");
1304
-
1305
- /* Reconstruct the tag. */
1306
- return `<${tagName}${processedAttributes}>`
1307
- }
1308
- )
1309
- };
1310
-
1311
- /**
1312
- * Validate any passed-in config options and merge with CONFIG.
1313
- *
1314
- * @param {import('htmlfy').UserConfig} config A user config.
1315
- * @returns {import('htmlfy').Config} A validated config.
1316
- */
1317
- const validateConfig = (config) => {
1318
- if (typeof config !== 'object') throw new Error('Config must be an object.')
1319
-
1320
- const default_config = { ...CONFIG };
1321
-
1322
- const config_empty = !(
1323
- Object.hasOwn(config, 'content_wrap') ||
1324
- Object.hasOwn(config, 'ignore') ||
1325
- Object.hasOwn(config, 'ignore_with') ||
1326
- Object.hasOwn(config, 'strict') ||
1327
- Object.hasOwn(config, 'tab_size') ||
1328
- Object.hasOwn(config, 'tag_wrap') ||
1329
- Object.hasOwn(config, 'trim')
1330
- );
1331
-
1332
- if (config_empty) {
1333
- setState({ config: default_config });
1334
- return default_config
1335
- }
1336
-
1337
- let tab_size = config.tab_size;
1338
-
1339
- if (tab_size) {
1340
- if (typeof tab_size !== 'number') throw new Error(`tab_size must be a number, not ${typeof config.tab_size}.`)
1341
-
1342
- const safe = Number.isSafeInteger(tab_size);
1343
- if (!safe) throw new Error(`Tab size ${tab_size} is not safe. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger for more info.`)
1344
-
1345
- /**
1346
- * Round down, just in case a safe floating point,
1347
- * like 4.0, was passed.
1348
- */
1349
- tab_size = Math.floor(tab_size);
1350
- if (tab_size < 1 || tab_size > 16) throw new Error('Tab size out of range. Expecting 1 to 16.')
1351
-
1352
- config.tab_size = tab_size;
1353
- }
1354
-
1355
- if (Object.hasOwn(config, 'content_wrap') && typeof config.content_wrap !== 'number')
1356
- throw new Error(`content_wrap config must be a number, not ${typeof config.content_wrap}.`)
1357
-
1358
- if (Object.hasOwn(config, 'ignore') && (!Array.isArray(config.ignore) || !config.ignore?.every((e) => typeof e === 'string')))
1359
- throw new Error('Ignore config must be an array of strings.')
1360
-
1361
- if (Object.hasOwn(config, 'ignore_with')) {
1362
- if (typeof config.ignore_with !== 'string')
1363
- throw new Error(`ignore_with must be a string, not ${typeof config.ignore_with}.`)
1364
- else if (config.ignore_with.startsWith('_'))
1365
- /**
1366
- * This negatively affects processing of preserved tag attributes,
1367
- * because tag names can end with an underscore, so the regex
1368
- * does not capture them.
1369
- */
1370
- throw new Error(`ignore_with cannot start with an underscore.`)
1371
- }
1372
-
1373
- if (Object.hasOwn(config, 'strict') && typeof config.strict !== 'boolean')
1374
- throw new Error(`Strict config must be a boolean, not ${typeof config.strict}.`)
1375
-
1376
- if (Object.hasOwn(config, 'tag_wrap') && typeof config.tag_wrap !== 'number')
1377
- throw new Error(`tag_wrap config must be a number, not ${typeof config.tag_wrap}.`)
1378
-
1379
- if (Object.hasOwn(config, 'trim') && (!Array.isArray(config.trim) || !config.trim?.every((e) => typeof e === 'string')))
1380
- throw new Error('Trim config must be an array of strings.')
1381
-
1382
- return mergeConfig(default_config, config)
1383
-
1384
- };
1385
-
1386
- /**
1387
- *
1388
- * @param {string} text
1389
- * @param {number} width
1390
- * @param {string} indent
1391
- */
1392
- const wordWrap = (text, width, indent) => {
1393
- const words = text.trim().split(/\s+/);
1394
-
1395
- if (words.length === 0 || (words.length === 1 && words[0] === ''))
1396
- return ""
1397
-
1398
- const lines = [];
1399
- let current_line = "";
1400
- const padding_string = indent;
1401
-
1402
- words.forEach((word) => {
1403
- if (word === "") return
1404
-
1405
- if (word.length >= width) {
1406
- /* If there's content on the current line, push it first with correct padding. */
1407
- if (current_line !== "")
1408
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1409
-
1410
- /* Push a long word on its own line with correct padding. */
1411
- lines.push(lines.length === 0 ? indent + word : padding_string + word);
1412
- current_line = ""; // Reset current line
1413
- return // Move to the next word
1414
- }
1415
-
1416
- /* Check if adding the next word exceeds the wrap width. */
1417
- const test_line = current_line === "" ? word : current_line + " " + word;
1418
-
1419
- if (test_line.length <= width) {
1420
- current_line = test_line;
1421
- } else {
1422
- /* Word doesn't fit, finish the current line and push it. */
1423
- if (current_line !== "") {
1424
- /* Add padding based on whether it's the first line added or not. */
1425
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1426
- }
1427
- /* Start a new line with the current word. */
1428
- current_line = word;
1429
- }
1430
- });
1431
-
1432
- /* Add the last remaining line with appropriate padding. */
1433
- if (current_line !== "")
1434
- lines.push(lines.length === 0 ? indent + current_line : padding_string + current_line);
1435
-
1436
- const result = lines.join("\n");
1437
-
1438
- return protectContent(result)
1439
- };
1440
-
1441
- /**
1442
- * Extract any HTML blocks to be ignored,
1443
- * and replace them with a placeholder
1444
- * for re-insertion later.
1445
- *
1446
- * @param {string} html
1447
- * @returns {{ html_with_markers: string, extracted_map: Map<any,any> }}
1448
- */
1449
- function extractIgnoredBlocks(html) {
1450
- setState({ ignored: true });
1451
- const config = (getState()).config;
1452
- let current_html = html;
1453
- const extracted_blocks = new Map();
1454
- let marker_id = 0;
1455
- const MARKER_PREFIX = "___HTMLFY_SPECIAL_IGNORE_MARKER_";
1456
-
1457
- for (const tag of config.ignore) {
1458
- /* Ensure tag is escaped if it can contain regex special chars. */
1459
- const safe_tag_name = tag.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
1460
-
1461
- const regex = new RegExp(
1462
- `(<\\s*${safe_tag_name}[^>]*>)(.*?)(<\\s*\/\\s*${safe_tag_name}\\s*>)`,
1463
- "gs" // global and dotAll
1464
- );
1465
-
1466
- /** @type RegExpExecArray | null */
1467
- let match;
1468
-
1469
- /**
1470
- * @type {{ start: number; end: number; marker: string }[]}
1471
- */
1472
- const replacements = [];
1473
-
1474
- while ((match = regex.exec(current_html)) !== null) {
1475
- const marker = `${MARKER_PREFIX}${marker_id++}___`;
1476
-
1477
- /* Only store content, and minify tags later. */
1478
- extracted_blocks.set(marker, match[2]);
1479
-
1480
- replacements.push({
1481
- start: match.index + match[1].length, // start of content
1482
- end: match.index + match[1].length + match[2].length, // end of content
1483
- marker: marker,
1484
- });
1485
- }
1486
-
1487
- /* Apply replacements from the end to the beginning to keep indices valid. */
1488
- for (let i = replacements.length - 1; i >= 0; i--) {
1489
- const rep = replacements[i];
1490
- current_html =
1491
- current_html.substring(0, rep.start) +
1492
- rep.marker +
1493
- current_html.substring(rep.end);
1494
- }
1495
- }
1496
-
1497
- return { html_with_markers: current_html, extracted_map: extracted_blocks }
1498
- }
1499
-
1500
- /**
1501
- * Re-insert ignored HTML blocks.
1502
- *
1503
- * @param {string} html_with_markers
1504
- * @param {Map<any,any>} extracted_map
1505
- * @returns
1506
- */
1507
- function reinsertIgnoredBlocks(html_with_markers, extracted_map) {
1508
- setState({ ignored: false });
1509
- let final_html = html_with_markers;
1510
-
1511
- for (const [marker, original_block] of extracted_map) {
1512
- final_html = final_html.split(marker).join(original_block);
1513
- }
1514
- return final_html
1515
- }
1516
-
1517
- const void_element_regex = new RegExp(`<(${VOID_ELEMENTS.join("|")})(?:\\s(?:[^/>]|/(?!>))*)*>`, 'g');
1518
-
1519
- /**
1520
- * Add a placeholder for void elements that are not self-closing.
1521
- * This is for internal processing only.
1522
- *
1523
- * @param {string} html
1524
- * @returns
1525
- */
1526
- function setSelfClosing(html) {
1527
- const { constants } = getState();
1528
-
1529
- return html.replace(
1530
- // match only void elements that are not self-closing
1531
- void_element_regex,
1532
- match => match.replace(/>$/, constants.SELF_CLOSING_PLACEHOLDER)
1533
- )
1534
- }
1535
-
1536
- /**
1537
- * Remove internal placeholder for non-native self-closing void elements.
1538
- *
1539
- * @param {string} html
1540
- * @returns
1541
- */
1542
- function unsetSelfClosing(html) {
1543
- const { constants } = getState();
1544
-
1545
- return html.replace(constants.SELF_CLOSING_PLACEHOLDER, ">")
1546
- }
1547
-
1548
- /**
1549
- * Enforce entity characters for textarea content.
1550
- * To also minifiy tags, pass `minify` as `true`.
1551
- *
1552
- * @param {string} html The HTML string to evaluate.
1553
- * @param {boolean} [minify] Minifies the textarea tags themselves.
1554
- * Defaults to `false`. We recommend a value of `true` if you're running `entify()`
1555
- * as a standalone function.
1556
- * @returns {string}
1557
- * @example <textarea>3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1558
- * @example With minify.
1559
- * <textarea >3 > 2</textarea> => <textarea>3&nbsp;&gt;&nbsp;2</textarea>
1560
- */
1561
- const entify = (html, minify = false) => {
1562
- /**
1563
- * Use entities inside textarea content.
1564
- */
1565
- html = html.replace(/<\s*textarea[^>]*>((.|\n)*?)<s*\/\s*textarea\s*>/g, (match, capture) => {
1566
- return match.replace(capture, (match) => {
1567
- return match
1568
- .replace(/</g, '&lt;')
1569
- .replace(/>/g, '&gt;')
1570
- .replace(/"/g, '&quot;')
1571
- .replace(/'/g, '&apos;')
1572
- .replace(/\n/g, '&#10;')
1573
- .replace(/\r/g, '&#13;')
1574
- .replace(/\s/g, '&nbsp;')
1575
- })
1576
- });
1577
-
1578
- if (minify) {
1579
- html = html.replace(/<\s*textarea[^>]*>(.|\n)*?<\s*\/\s*textarea\s*>/g, (match) => {
1580
- /* This only affects the html tags, since everything else has been entified. */
1581
- return match
1582
- .replace(/\s+/g, ' ')
1583
- .replace(/\s>/g, '>')
1584
- .replace(/>\s/g, '>')
1585
- .replace(/\s</g, '<')
1586
- .replace(/<\s/g, '<')
1587
- .replace(/<\/\s/g, '<\/')
1588
- .replace(/class=["']\s/g, (match) => match.replace(/\s/g, ''))
1589
- .replace(/(class=.*)\s(["'])/g, '$1'+'$2')
1590
- });
1591
- }
1592
-
1593
- return html
1594
- };
1595
-
1596
- /**
1597
- * Remove entity characters for textarea content.
1598
- * Currently internal use only.
1599
- *
1600
- * @param {string} html The HTML string to evaluate.
1601
- * @returns {string}
1602
- * @example <textarea>3&nbsp;&gt;&nbsp;2</textarea> => <textarea>3 > 2</textarea>
1603
- */
1604
- const dentify = (html) => {
1605
- /**
1606
- * Remove entities inside textarea content.
1607
- */
1608
- return html = html.replace(/<textarea[^>]*>((.|\n)*?)<\/textarea>/g, (match, capture) => {
1609
- return match.replace(capture, (match) => {
1610
- match = match
1611
- .replace(/&lt;/g, '<')
1612
- .replace(/&gt;/g, '>')
1613
- .replace(/&quot;/g, '"')
1614
- .replace(/&apos;/g, "'")
1615
- .replace(/&#10;/g, '\n')
1616
- .replace(/&#13;/g, '\r')
1617
- .replace(/&nbsp;/g, ' ')
1618
- // Ensure we collapse consecutive spaces, or they'll be completely removed later.
1619
- .replace(/\s+/g, ' ');
1620
-
1621
- return match
1622
- })
1623
- })
1624
- };
1625
-
1626
- /**
1627
- * @type {Map<any,any>}
1628
- */
1629
- let ignore_map$1;
1630
-
1631
- /**
1632
- * Creates a single-line HTML string
1633
- * by removing line returns, tabs, and relevant spaces.
1634
- *
1635
- * @param {string} html The HTML string to minify.
1636
- * @param {import('htmlfy').UserConfig} [config] A user configuration object.
1637
- * @returns {string} A minified HTML string.
1638
- */
1639
- const minify = (html, config) => {
1640
- let reinsert_ignored = false;
1641
- const { checked_html, ignored, constants } = getState();
1642
-
1643
- if (!checked_html && !isHtml(html)) return html
1644
-
1645
- const validated_config = (getState()).config;
1646
- const ignore = validated_config.ignore.length > 0;
1647
-
1648
- /* Extract ignored elements. Skipped if prettify has already ignored blocks. */
1649
- if (!ignored && ignore) {
1650
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
1651
- html = html_with_markers;
1652
- ignore_map$1 = extracted_map;
1653
- reinsert_ignored = true;
1654
- }
1655
-
1656
- /**
1657
- * Ensure textarea content is protected
1658
- * before general minification.
1659
- */
1660
- html = entify(html, true);
1661
-
1662
- /* All other minification. */
1663
- // Remove ALL newlines and tabs explicitly.
1664
- html = html.replace(/\n|\t/g, '');
1665
-
1666
- // Remove whitespace ONLY between tags.
1667
- html = html.replace(/>\s+</g, "><");
1668
-
1669
- // Collapse any remaining multiple spaces to single spaces.
1670
- html = html.replace(/ {2,}/g, ' ');
1671
-
1672
- // Protect space between text content and an opening tag (e.g., "text <a>")
1673
- html = html.replace(
1674
- /(\S) (<[a-zA-Z][a-zA-Z0-9_:-]*)/g,
1675
- `$1___MINIFY-PROTECTED-SPACE___$2`
1676
- );
1677
-
1678
- // Protect space between a closing tag and text content (e.g., "</a> text")
1679
- html = html.replace(
1680
- /(<\/[a-zA-Z][a-zA-Z0-9_:-]*>) (\S)/g,
1681
- `$1___MINIFY-PROTECTED-SPACE___$2`
1682
- );
1683
-
1684
- // Remove specific single spaces between tags and whitespace within tags.
1685
- html = html.replace(/ >/g, ">"); // <tag > -> <tag>
1686
- html = html.replace(/ </g, "<"); // leading space before tag
1687
- html = html.replace(/> /g, ">"); // trailing space after tag
1688
- html = html.replace(/< /g, "<"); // < tag> -> <tag>
1689
- html = html.replace(/<\s+\//g, '</'); // < /tag> -> </tag>
1690
- html = html.replace(/<\/\s+/g, '</'); // </ tag> -> </tag>
1691
-
1692
- // Unprotect space around inner tags
1693
- html = html.replace(new RegExp('___MINIFY-PROTECTED-SPACE___', 'g'), ' ');
1694
-
1695
- // Trim spaces around equals signs in attributes (run before value trim)
1696
- // This handles `attr = "value"` -> `attr="value"`
1697
- html = html.replace(/ = /g, "=");
1698
- // Consider safer alternatives if needed (e.g., / = "/g, '="')
1699
-
1700
- // Trim whitespace inside attribute values
1701
- html = html.replace(
1702
- /([a-zA-Z0-9_-]+)=(['"])(.*?)\2/g,
1703
- (match, attr_name, quote, value) => {
1704
- // value.trim() handles both leading/trailing spaces
1705
- // and cases where the value is only whitespace (becomes empty string)
1706
- const trimmed_value = value.trim();
1707
- return `${attr_name}=${quote}${trimmed_value}${quote}`
1708
- }
1709
- );
1710
-
1711
- // Final trim for the whole string
1712
- html = html.trim();
1713
-
1714
- /* Remove protective entities. */
1715
- html = dentify(html);
1716
-
1717
- /* Re-insert ignored elements. Skipped unless minify did the ignore. */
1718
- if (reinsert_ignored) {
1719
- html = reinsertIgnoredBlocks(html, ignore_map$1);
1720
- }
1721
-
1722
- return html
1723
- };
1724
-
1725
- /**
1726
- * @type {{ line: Record<string,string>[] }}
1727
- */
1728
- const convert = {
1729
- line: []
1730
- };
1731
-
1732
- /**
1733
- * @type {Map<any,any>}
1734
- */
1735
- let ignore_map;
1736
-
1737
- /**
1738
- * Isolate tags, content, and comments.
1739
- *
1740
- * @param {string} html The HTML string to evaluate.
1741
- * @example <div>Hello World!</div> =>
1742
- * [#-# : 0 : <div> : #-#]
1743
- * Hello World!
1744
- * [#-# : 1 : </div> : #-#]
1745
- */
1746
- const enqueue = (html) => {
1747
- convert.line = [];
1748
- let i = -1;
1749
- /* Regex to find tags OR text content between tags. */
1750
- const regex = /(<[^>]+>)|([^<]+)/g;
1751
-
1752
- html.replace(regex, (match, c1, c2) => {
1753
- if (c1) {
1754
- convert.line.push({ type: "tag", value: match });
1755
- } else if (c2 && c2.trim().length > 0) {
1756
- /* It's text content (and not just whitespace). */
1757
- convert.line.push({ type: "text", value: match });
1758
- }
1759
-
1760
- i++;
1761
- return `\n[#-# : ${i} : ${match} : #-#]\n`
1762
- });
1763
- };
1764
-
1765
- /**
1766
- * Process enqueued content.
1767
- *
1768
- * @returns {string}
1769
- */
1770
- const process = () => {
1771
- const { config, constants } = getState();
1772
- const step = " ".repeat(config.tab_size);
1773
- const tag_wrap = config.tag_wrap;
1774
- const content_wrap = config.content_wrap;
1775
- const strict = config.strict;
1776
-
1777
- /* Track current number of indentations needed. */
1778
- let indents = '';
1779
-
1780
- /** @type string[] */
1781
- const output_lines = [];
1782
- const tag_regex = /<[A-Za-z]+\b[^>]*(?:.|\n)*?\/?>/g; /* Is opening tag or void element. */
1783
- const attribute_regex = /\s{1}[A-Za-z-]+(?:=".*?")?/g; /* Matches all tag/element attributes. */
1784
-
1785
- /* Process lines and indent. */
1786
- convert.line.forEach((source, index) => {
1787
- let current_line_value = source.value;
1788
-
1789
- const is_ignored_content =
1790
- current_line_value.startsWith('___HTMLFY_SPECIAL_IGNORE_MARKER_');
1791
-
1792
- let subtrahend = 0;
1793
- const prev_line_data = convert.line[index - 1];
1794
- const prev_line_value = prev_line_data?.value ?? ""; // Use empty string if no prev line
1795
-
1796
- /**
1797
- * Arbitratry character, to keep track of the string's length.
1798
- */
1799
- indents += '0';
1800
-
1801
- if (index === 0) subtrahend++;
1802
- /* We're processing a closing tag. */
1803
- if (current_line_value.trim().startsWith("</")) subtrahend++;
1804
- /* prevLine is a doctype declaration. */
1805
- if (prev_line_value.trim().startsWith("<!doctype")) subtrahend++;
1806
- /* prevLine is a comment. */
1807
- if (prev_line_value.trim().startsWith("<!--")) subtrahend++;
1808
- /* prevLine is a void element. */
1809
- if (
1810
- prev_line_value.trim().endsWith("/>") // native self-closing
1811
- ||
1812
- prev_line_value.trim().endsWith(constants.SELF_CLOSING_PLACEHOLDER) // synthetic self-closing
1813
- ) subtrahend++;
1814
- /* prevLine is a closing tag. */
1815
- if (prev_line_value.trim().startsWith("</")) subtrahend++;
1816
- /* prevLine is text. */
1817
- if (prev_line_data?.type === "text") subtrahend++;
1818
-
1819
- /* Determine offset for line indentation. */
1820
- const offset = Math.max(0, indents.length - subtrahend);
1821
- /* Correct indent level for *this* line's content */
1822
- const current_indent_level = offset; // Store the level for this line
1823
-
1824
- indents = indents.substring(0, current_indent_level); // Adjust for *next* round
1825
-
1826
- /**
1827
- * Starts with a single punctuation character.
1828
- * Add punctuation to end of previous line.
1829
- */
1830
- if (source.type === 'text' && /^[!,;\.]/.test(current_line_value)) {
1831
- if (current_line_value.length === 1) {
1832
- output_lines[output_lines.length - 1] =
1833
- output_lines.at(-1) + current_line_value;
1834
- return
1835
- } else {
1836
- output_lines[output_lines.length - 1] =
1837
- output_lines.at(-1) + current_line_value.charAt(0);
1838
- current_line_value = current_line_value.slice(1).trim();
1839
-
1840
- /* If nothing left after extracting punctuation, skip this line. */
1841
- if (current_line_value.length === 0) return
1842
- }
1843
- }
1844
-
1845
- const padding = step.repeat(current_indent_level);
1846
-
1847
- if (is_ignored_content) {
1848
- /* Stop processing this line, as it's set to be ignored. */
1849
- output_lines.push(current_line_value);
1850
- } else {
1851
- /* Remove comment. */
1852
- if (strict && current_line_value.trim().startsWith("<!--"))
1853
- return
1854
-
1855
- let result = current_line_value;
1856
-
1857
- /* Remove self-closing placeholder, if needed. */
1858
- result = unsetSelfClosing(result);
1859
-
1860
- if (
1861
- source.type === 'text' &&
1862
- content_wrap > 0 &&
1863
- result.length >= content_wrap
1864
- ) {
1865
- result = wordWrap(result, content_wrap, padding);
1866
- }
1867
- /* Wrap the attributes of open tags and void elements. */
1868
- else if (
1869
- tag_wrap > 0 &&
1870
- result.length > tag_wrap &&
1871
- tag_regex.test(result)
1872
- ) {
1873
- tag_regex.lastIndex = 0; // Reset stateful regex
1874
- attribute_regex.lastIndex = 0; // Reset stateful regex
1875
-
1876
- const tag_parts = result.split(attribute_regex).filter(Boolean);
1877
-
1878
- if (tag_parts.length >= 2) {
1879
- const attributes = result.matchAll(attribute_regex);
1880
- const inner_padding = padding + step;
1881
- let wrapped_tag = padding + tag_parts[0] + "\n";
1882
-
1883
- for (const a of attributes) {
1884
- const attribute_string = a[0].trim();
1885
- wrapped_tag += inner_padding + attribute_string + "\n";
1886
- }
1887
-
1888
- const tag_name_match = tag_parts[0].match(/<([A-Za-z_:-]+)/);
1889
- const tag_name = tag_name_match ? tag_name_match[1] : "";
1890
- const is_self_closing = tag_parts.at(-1)?.endsWith("/>") && VOID_ELEMENTS.includes(tag_name);
1891
- const closing_part = tag_parts[1].trim();
1892
- const closing_padding = padding + (strict && is_self_closing ? " " : "");
1893
-
1894
- wrapped_tag += closing_padding + closing_part;
1895
-
1896
- result = wrapped_tag; // Assign the fully wrapped string
1897
- } else {
1898
- result = padding + result;
1899
- }
1900
- } else {
1901
- /* Apply simple indentation (if no wrapping occurred) */
1902
- result = padding + result;
1903
- }
1904
-
1905
- /* Add the processed line (or lines if wordWrap creates them) to the output */
1906
- output_lines.push(result);
1907
- }
1908
- });
1909
-
1910
- /* Join all processed lines into the final HTML string */
1911
- let final_html = output_lines.join("\n");
1912
-
1913
- /* Preserve wrapped attributes. */
1914
- if (tag_wrap > 0) final_html = protectAttributes(final_html);
1915
-
1916
- /* Extra preserve wrapped content. */
1917
- if (content_wrap > 0 && new RegExp(`/\\n[ ]*[^\\n]*${constants.CONTENT_IGNORE_PLACEHOLDER}[^\\n]*\\n/`).test(final_html))
1918
- final_html = finalProtectContent(final_html);
1919
-
1920
- /* Remove line returns, tabs, and consecutive spaces within html elements or their content. */
1921
- final_html = final_html.replace(
1922
- /<(?<Element>[^>\s]+)[^>]*>[^<]*?[^><\/\s][^<]*?<\/\k<Element>>|<script[^>]*>[\s]*<\/script>|<([\w:\._-]+)([^>]*)><\/\2>|<([\w:\._-]+)([^>]*)>[\s]+<\/\4>/g,
1923
- match => {
1924
- // Check if this contains placeholder
1925
- if (match.includes(constants.SELF_CLOSING_PLACEHOLDER) || match.includes(constants.CONTENT_IGNORE_PLACEHOLDER)) {
1926
- return match // Don't modify if it contains the placeholder
1927
- }
1928
-
1929
- return match.replace(/\n|\t|\s{2,}/g, '')
1930
- }
1931
- );
1932
-
1933
- /* Revert wrapped content. */
1934
- if (content_wrap > 0) final_html = unprotectContent(final_html);
1935
-
1936
- /* Revert wrapped attributes. */
1937
- if (tag_wrap > 0) final_html = unprotectAttributes(final_html);
1938
-
1939
- /* Remove self-closing nature of void elements. */
1940
- if (strict) final_html = final_html.replace(/\s\/>|\/>/g, '>');
1941
-
1942
- /* Trim leading and/or trailing line returns. */
1943
- if (final_html.startsWith("\n")) final_html = final_html.substring(1);
1944
- if (final_html.endsWith("\n")) final_html = final_html.substring(0, final_html.length - 1);
1945
-
1946
- return final_html
1947
- };
1948
-
1949
- /**
1950
- * Format HTML with line returns and indentations.
1951
- *
1952
- * @param {string} html The HTML string to prettify.
1953
- * @param {import('htmlfy').UserConfig} [config] A user configuration object.
1954
- * @returns {string} A well-formed HTML string.
1955
- */
1956
- const prettify = (html, config) => {
1957
- let reinsert_ignored = false;
1958
- const { checked_html, ignored } = getState();
1959
-
1960
- /* Return content as-is if it does not contain any HTML elements. */
1961
- if (!checked_html && !isHtml(html)) return html
1962
-
1963
- /* Runs setState for config. */
1964
- const validated_config = validateConfig(config || {});
1965
-
1966
- const ignore = validated_config.ignore.length > 0;
1967
-
1968
- /* Allows you to trimify before ignoring. */
1969
- if (validated_config.trim.length > 0) html = trimify(html, validated_config.trim);
1970
-
1971
- /* Extract ignored elements. */
1972
- if (!ignored && ignore) {
1973
- const { html_with_markers, extracted_map } = extractIgnoredBlocks(html);
1974
- html = html_with_markers;
1975
- ignore_map = extracted_map;
1976
- reinsert_ignored = true;
1977
- }
1978
-
1979
- /* Preserve html text within attribute values. */
1980
- html = setIgnoreAttribute(html);
1981
-
1982
- /* Insert placeholder for void elements that aren't self-closing. */
1983
- html = setSelfClosing(html);
1984
-
1985
- html = minify(html);
1986
- enqueue(html);
1987
- html = process();
1988
-
1989
- /* Revert html text within attribute values. */
1990
- html = unsetIgnoreAttribute(html);
1991
-
1992
- /* Re-insert ignored elements. */
1993
- if (reinsert_ignored) {
1994
- html = reinsertIgnoredBlocks(html, ignore_map);
1995
- }
1996
-
1997
- return html
1998
- };
1999
-
2000
- /**
2001
- * Render attribute on the given element
2002
- * @param element - targeted to render attribute
2003
- * @param name - of the attribute
2004
- * @param value - of the attribute
2005
- */
2006
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2007
- const renderAttribute = (element, name, value) => {
2008
- if ([null, undefined, '', false].includes(value) || ['innerHTML', 'style', ''].includes(name)) {
2009
- return;
2010
- }
2011
- element.setAttribute(name, !['object', 'function'].includes(typeof value) ? value : `⚠️ Property must be set through a script or a framework-specific syntax.`);
2012
- };
2013
- /**
2014
- * Render new element in parent element
2015
- * @param parentNode - HTML element
2016
- * @param tagName - of the new element
2017
- * @param attributes - of the new element
2018
- * @param children - of the new element
2019
- * @param text - of the new element
2020
- */
2021
- const renderElement = (parentNode, tagName, attributes, children, text) => {
2022
- // render HTML
2023
- if (tagName && typeof tagName === 'string') {
2024
- const element = document.createElement(tagName);
2025
- Object.keys(attributes || {}).forEach(attr => {
2026
- renderAttribute(element, attr, attributes[attr]);
2027
- });
2028
- children?.forEach(child => {
2029
- renderElement(element, child.$tag$, child.$attrs$, child.$children$, child.$text$);
2030
- });
2031
- if (attributes?.innerHTML)
2032
- element.innerHTML = attributes.innerHTML;
2033
- parentNode.appendChild(element);
2034
- }
2035
- // render text
2036
- if (text) {
2037
- parentNode.innerHTML = text;
2038
- }
2039
- };
2040
- /**
2041
- * Filter default argument on component argument to prevent them to be rendered
2042
- * @param args - all possible args with custom values
2043
- * @param defaultValues - component default args values
2044
- * @param slots - slots
2045
- * @returns filtres args
2046
- * @example
2047
- * ```ts
2048
- * import { filterArgs } from '@mgdis/core-ui-helpers/dist/storybook';
2049
- * const Template = (args: MgBadgeType): HTMLElement => <mg-badge {...filterArgs(args, { variant: 'info' }, ['actions'])}></mg-badge>;
2050
- * ```
2051
- */
2052
- const filterArgs = (args, defaultValues, slots = []) => {
2053
- const filteredArgs = {};
2054
- if (typeof args !== 'object') {
2055
- throw new Error("filterArgs - args isn't an object.");
2056
- }
2057
- for (const k in args) {
2058
- if (!slots.includes(k)) {
2059
- const arg = args[k];
2060
- // Change camelCase k to kebab-case
2061
- const key = k.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
2062
- if (!defaultValues || !Object.keys(defaultValues).includes(k) || defaultValues[k] !== arg) {
2063
- filteredArgs[key] = arg;
2064
- }
2065
- }
2066
- }
2067
- return filteredArgs;
2068
- };
2069
- /**
2070
- * Storybook stencil wrapper. Used to target element with `storybook-root` id and render virtual DOM inside.
2071
- * @param storyFn - storybook render function
2072
- * @param context - storybook context
2073
- * @returns rendered element
2074
- * @example
2075
- * ```ts
2076
- * // .storybook/preview.ts
2077
- * import { stencilWrapper } from '@mgdis/core-ui-helpers/dist/storybook';
2078
- * export const decorators: Preview['decorators'] = [stencilWrapper];
2079
- * ```
2080
- */
2081
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2082
- const stencilWrapper = (storyFn, context) => {
2083
- const host = document.getElementById('storybook-root');
2084
- if (host === null)
2085
- return;
2086
- // update local switcher based on context variable
2087
- document.querySelector('[lang]')?.setAttribute('lang', context.globals?.locale || 'en');
2088
- renderVdom({
2089
- $cmpMeta$: {
2090
- $flags$: 0,
2091
- $tagName$: host.tagName,
2092
- },
2093
- $hostElement$: host,
2094
- }, storyFn(context));
2095
- return host.children[host.children.length - 1];
2096
- };
2097
- /**
2098
- * Get story HTML from virtual DOM.
2099
- * Mainly used to render, component code exemple in stories.
2100
- * @param vitualNode - story virtual DOM
2101
- * @returns stringified rendered HTML
2102
- * @example
2103
- * ```ts
2104
- * // .storybook/preview.ts
2105
- * import { getStoryHTML } from '@mgdis/core-ui-helpers/dist/storybook';
2106
- *
2107
- * export const parameters: Preview['parameters'] = {
2108
- * docs: {
2109
- * source: {
2110
- * transform: (_, ctx) => getStoryHTML(ctx.originalStoryFn(ctx.args)),
2111
- * }
2112
- * },
2113
- * };
2114
- * ```
2115
- */
2116
- const getStoryHTML = ({ $tag$, $attrs$, $children$, $text$ }) => {
2117
- const host = document.createElement('div');
2118
- renderElement(host, $tag$, $attrs$, $children$, $text$);
2119
- return prettify(host.innerHTML, {
2120
- tag_wrap: 40,
2121
- content_wrap: 120,
2122
- }).replace(/="true"/g, '');
2123
- };
2124
- /**
2125
- * Retrieve Component Storybook URL from file path
2126
- * @param storybookBaseUrl - Storybook Base URL
2127
- * @param filePath - Component file path
2128
- * @returns Component Storybook URL
2129
- */
2130
- const getStorybookUrl = (storybookBaseUrl, filePath) => {
2131
- if (!filePath) {
2132
- return;
2133
- }
2134
- const split = filePath.split('/');
2135
- return `${storybookBaseUrl}${split.slice(2, split.length - 1).join('-')}--docs`;
2136
- };
2137
- class StorybookPreview {
2138
- /**
2139
- * JsonDocs
2140
- */
2141
- jsonDoc;
2142
- constructor(jsonDoc) {
2143
- this.jsonDoc = jsonDoc;
2144
- }
2145
- /**
2146
- * Get component data from the jsonDoc
2147
- * @param tagName - tag name we want to get the data from
2148
- * @returns component data
2149
- */
2150
- #getComponentData = (tagName) => {
2151
- return this.jsonDoc.components.find(component => component.tag === tagName);
2152
- };
2153
- /**
2154
- * Get the control for the given prop
2155
- * Based on https://storybook.js.org/docs/api/arg-types#controltype
2156
- * @param prop - prop to get control for
2157
- * @returns control type and options if applicable
2158
- */
2159
- #getPropControl = (prop) => {
2160
- // Get types
2161
- const types = prop.type
2162
- .replace(/"([^"]+)"/g, '$1') // Remove quotes
2163
- .replace(/\s/g, '') // Remove all whitespace for simplicity
2164
- .replace(/\(.*?\)/g, match => match.replace(/\|/g, ' OR ')) // Replace '|' inside parentheses
2165
- .split('|')
2166
- .map(type => type.trim().replace(/ OR /g, '|')); // Revert ' OR ' back to '|'
2167
- // Return control and options
2168
- if (prop.type === 'string') {
2169
- return { control: { type: 'text' } };
2170
- }
2171
- else if (prop.type === 'number') {
2172
- return { control: { type: 'number' } };
2173
- }
2174
- else if (prop.type === 'boolean') {
2175
- return { control: { type: 'boolean' } };
2176
- }
2177
- else if (prop.type.startsWith('{') && prop.type.endsWith('}')) {
2178
- return { control: { type: 'object' } };
2179
- }
2180
- else if (types.length > 1) {
2181
- // Manage case when multiple types are possible
2182
- if (types.includes('string')) {
2183
- return { control: { type: 'text' } };
2184
- }
2185
- else if (types.every(type => type?.includes('[]'))) {
2186
- return { control: { type: 'object' } };
2187
- }
2188
- else {
2189
- // Add the posibility to set undefined
2190
- types.unshift(undefined);
2191
- return { control: { type: 'select' }, options: types };
2192
- }
2193
- }
2194
- else
2195
- return { control: { type: 'object' } };
2196
- };
2197
- /**
2198
- * Extract component arg types from the component data
2199
- * @param tagName - tag name we want to extract the arg types from
2200
- * @returns component arg types
2201
- */
2202
- extractArgTypes = (tagName) => {
2203
- const componentData = this.#getComponentData(tagName);
2204
- // Extract props arg types
2205
- const componentPropsArgTypes = componentData?.props.reduce((acc, prop) => {
2206
- // Get Controls
2207
- const { control, options } = this.#getPropControl(prop);
2208
- // Set Component ArgTypes
2209
- return {
2210
- ...acc,
2211
- [prop.name]: {
2212
- name: prop.attr || prop.name,
2213
- description: prop.docs,
2214
- type: { required: prop.required },
2215
- table: {
2216
- category: 'props',
2217
- type: { summary: prop.type },
2218
- defaultValue: { summary: prop.default },
2219
- },
2220
- control,
2221
- options,
2222
- },
2223
- };
2224
- }, {});
2225
- // Extract events arg types
2226
- const componentEventsArgTypes = componentData?.events.reduce((acc, event) => ({
2227
- ...acc,
2228
- [event.event]: {
2229
- name: event.event,
2230
- description: event.docs,
2231
- table: {
2232
- category: 'events',
2233
- type: { summary: event.detail },
2234
- },
2235
- },
2236
- }), {});
2237
- // Extracts Methods arg types
2238
- const componentMethodsArgTypes = componentData?.methods.reduce((acc, method) => ({
2239
- ...acc,
2240
- [method.name]: {
2241
- name: method.name,
2242
- description: method.docs,
2243
- table: {
2244
- category: 'methods',
2245
- type: { summary: method.signature },
2246
- },
2247
- },
2248
- }), {});
2249
- // Extracts Slots arg types
2250
- const componentSlotsArgTypes = componentData?.slots.reduce((acc, slot) => ({
2251
- ...acc,
2252
- [slot.name]: {
2253
- name: slot.name !== '' ? slot.name : 'default', // default slot are unnamed
2254
- description: slot.docs,
2255
- table: {
2256
- category: 'slots',
2257
- type: { summary: undefined },
2258
- },
2259
- },
2260
- }), {});
2261
- // Extracts CSS Properties arg types
2262
- const componentCSSPropArgTypes = componentData?.styles.reduce((acc, style) => ({
2263
- ...acc,
2264
- [style.name]: {
2265
- name: style.name,
2266
- description: style.docs,
2267
- table: {
2268
- category: 'custom properties',
2269
- type: { summary: undefined },
2270
- },
2271
- },
2272
- }), {});
2273
- // Extract component dependencies
2274
- const componentDependencies = componentData?.dependencies.reduce((acc, dependency) => {
2275
- const dependencyData = this.#getComponentData(dependency);
2276
- if (!dependencyData)
2277
- return acc; // Prevents from adding internal dependency
2278
- return {
2279
- ...acc,
2280
- [dependency]: {
2281
- name: dependency,
2282
- description: `<a href="./?path=/docs/${getStorybookUrl('', dependencyData?.filePath)}">View Component Documentation</a>`,
2283
- table: {
2284
- category: 'depends on',
2285
- type: { summary: undefined },
2286
- },
2287
- },
2288
- };
2289
- }, {});
2290
- // Extract dependents components
2291
- const componentDependents = componentData?.dependents.reduce((acc, dependent) => {
2292
- const dependentData = this.#getComponentData(dependent);
2293
- if (!dependentData)
2294
- return acc; // Prevents from adding internal dependent
2295
- return {
2296
- ...acc,
2297
- [dependent]: {
2298
- name: dependent,
2299
- description: `<a href="./?path=/docs/${getStorybookUrl('', dependentData?.filePath)}">View Component Documentation</a>`,
2300
- table: {
2301
- category: 'used by',
2302
- type: { summary: undefined },
2303
- },
2304
- },
2305
- };
2306
- }, {});
2307
- return {
2308
- ...componentPropsArgTypes,
2309
- ...componentEventsArgTypes,
2310
- ...componentMethodsArgTypes,
2311
- ...componentSlotsArgTypes,
2312
- ...componentCSSPropArgTypes,
2313
- ...componentDependencies,
2314
- ...componentDependents,
2315
- };
2316
- };
2317
- /**
2318
- * Extract component description from the component data
2319
- * @param tagName - tag name we want to extract the description from
2320
- * @returns component description
2321
- */
2322
- extractComponentDescription = (tagName) => {
2323
- const componentData = this.#getComponentData(tagName);
2324
- return componentData?.readme || componentData?.docs;
2325
- };
2326
- }
2327
-
2328
- exports.StorybookPreview = StorybookPreview;
2329
- exports.filterArgs = filterArgs;
2330
- exports.getStoryHTML = getStoryHTML;
2331
- exports.getStorybookUrl = getStorybookUrl;
2332
- exports.stencilWrapper = stencilWrapper;
2333
- //# sourceMappingURL=index.cjs.map