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