@rededor/cura 2.0.0-alpha.11 → 2.0.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -2,6 +2,1146 @@ import { C as CuraThemeModule } from './cura-theme-module-BrK961-w.js';
2
2
  import './theme-legacy-default-BTIDzOyO.js';
3
3
  import './static-DfJS7YqS.js';
4
4
 
5
+ /**
6
+ * This file contains the WeakMaps used throughout this project. The WeakMaps exist to tie
7
+ * objects together without polluting the objects themselves with references we'd rather keep
8
+ * hidden. This allows the polyfill to work as transparently as possible.
9
+ */
10
+ /** Use an ElementInternals instance to get a reference to the element it is attached to */
11
+ const refMap = new WeakMap();
12
+ /** Usee an ElementsInternals instance to get its ValidityState object */
13
+ const validityMap = new WeakMap();
14
+ /** Use an ElementInternals instance to get its attached input[type="hidden"] */
15
+ const hiddenInputMap = new WeakMap();
16
+ /** Use a custom element to get its attached ElementInternals instance */
17
+ const internalsMap = new WeakMap();
18
+ /** Use an ElementInternals instance to get the attached validation message */
19
+ const validationMessageMap = new WeakMap();
20
+ /** Use a form element to get attached custom elements and ElementInternals instances */
21
+ const formsMap = new WeakMap();
22
+ /** Use a custom element or other object to get their associated MutationObservers */
23
+ const shadowHostsMap = new WeakMap();
24
+ /** Use a form element to get a set of attached custom elements */
25
+ const formElementsMap = new WeakMap();
26
+ /** Use an ElementInternals instance to get a reference to an element's value */
27
+ const refValueMap = new WeakMap();
28
+ /** Elements that need to be upgraded once added to the DOM */
29
+ const upgradeMap = new WeakMap();
30
+ /** Save references to shadow roots for inclusion in internals instance */
31
+ const shadowRootMap = new WeakMap();
32
+ /** Save a reference to the internals' validation anchor */
33
+ const validationAnchorMap = new WeakMap();
34
+ /** Map DocumentFragments to their MutationObservers so we can disconnect once elements are removed */
35
+ const documentFragmentMap = new WeakMap();
36
+ /** Whether connectedCallback has already been called. */
37
+ const connectedCallbackMap = new WeakMap();
38
+ /** Save a reference to validity state for elements that need to upgrade after being connected */
39
+ const validityUpgradeMap = new WeakMap();
40
+
41
+ /**
42
+ * Set attribute if its value differs from existing one.
43
+ *
44
+ * In comparison to other attribute modification methods (removeAttribute and
45
+ * toggleAttribute), setAttribute always triggers attributeChangedCallback
46
+ * even if the actual value has not changed.
47
+ *
48
+ * This polyfill relies heavily on attributes to pass aria information to
49
+ * screen readers. This behaviour differs from native implementation which does
50
+ * not change attributes.
51
+ *
52
+ * To limit this difference we only set attribute value when it is different
53
+ * from the current state.
54
+ *
55
+ * @param {ICustomElement | Element} ref - The custom element instance
56
+ * @param {string} name - The attribute name
57
+ * @param {string} value - The attribute value
58
+ * @returns
59
+ */
60
+ const setAttribute = (ref, name, value) => {
61
+ if (ref.getAttribute(name) === value) {
62
+ return;
63
+ }
64
+ ref.setAttribute(name, value);
65
+ };
66
+ /**
67
+ * Toggle's the disabled state (attributes & callback) on the given element
68
+ * @param {HTMLElement} ref - The custom element instance
69
+ * @param {boolean} disabled - The disabled state
70
+ */
71
+ const setDisabled = (ref, disabled) => {
72
+ ref.toggleAttribute("internals-disabled", disabled);
73
+ if (disabled) {
74
+ setAttribute(ref, "aria-disabled", "true");
75
+ }
76
+ else {
77
+ ref.removeAttribute("aria-disabled");
78
+ }
79
+ if (ref.formDisabledCallback) {
80
+ ref.formDisabledCallback.apply(ref, [disabled]);
81
+ }
82
+ };
83
+ /**
84
+ * Removes all hidden inputs for the given element internals instance
85
+ * @param {ElementInternals} internals - The element internals instance
86
+ * @return {void}
87
+ */
88
+ const removeHiddenInputs = (internals) => {
89
+ const hiddenInputs = hiddenInputMap.get(internals);
90
+ hiddenInputs.forEach((hiddenInput) => {
91
+ hiddenInput.remove();
92
+ });
93
+ hiddenInputMap.set(internals, []);
94
+ };
95
+ /**
96
+ * Creates a hidden input for the given ref
97
+ * @param {HTMLElement} ref - The element to watch
98
+ * @param {ElementInternals} internals - The element internals instance for the ref
99
+ * @return {HTMLInputElement} The hidden input
100
+ */
101
+ const createHiddenInput = (ref, internals) => {
102
+ const input = document.createElement("input");
103
+ input.type = "hidden";
104
+ input.name = ref.getAttribute("name");
105
+ ref.after(input);
106
+ hiddenInputMap.get(internals).push(input);
107
+ return input;
108
+ };
109
+ /**
110
+ * Set up labels for the ref
111
+ * @param {HTMLElement} ref - The ref to add labels to
112
+ * @param {NodeList} labels - A list of the labels
113
+ * @return {void}
114
+ */
115
+ const initLabels = (ref, labels) => {
116
+ if (labels.length) {
117
+ const labelList = Array.from(labels);
118
+ labelList.forEach((label) => label.addEventListener("click", ref.click.bind(ref)));
119
+ const [firstLabel] = labelList;
120
+ let firstLabelId = firstLabel.id;
121
+ if (!firstLabel.id) {
122
+ firstLabelId = `${firstLabel.htmlFor}_Label`;
123
+ firstLabel.id = firstLabelId;
124
+ }
125
+ setAttribute(ref, "aria-labelledby", firstLabelId);
126
+ }
127
+ };
128
+ /**
129
+ * Sets the internals-valid and internals-invalid attributes
130
+ * based on form validity.
131
+ * @param {HTMLFormElement} - The target form
132
+ * @return {void}
133
+ */
134
+ const setFormValidity = (form) => {
135
+ const nativeControlValidity = Array.from(form.elements)
136
+ .filter((element) => !element.tagName.includes("-") && element.validity)
137
+ .map((element) => element.validity.valid);
138
+ const polyfilledElements = formElementsMap.get(form) || [];
139
+ const polyfilledValidity = Array.from(polyfilledElements)
140
+ .filter((control) => control.isConnected)
141
+ .map((control) => internalsMap.get(control).validity.valid);
142
+ const hasInvalid = [...nativeControlValidity, ...polyfilledValidity].includes(false);
143
+ form.toggleAttribute("internals-invalid", hasInvalid);
144
+ form.toggleAttribute("internals-valid", !hasInvalid);
145
+ };
146
+ /**
147
+ * The global form input callback. Updates the form's validity
148
+ * attributes on input.
149
+ * @param {Event} - The form input event
150
+ * @return {void}
151
+ */
152
+ const formInputCallback = (event) => {
153
+ setFormValidity(findParentForm(event.target));
154
+ };
155
+ /**
156
+ * The global form change callback. Updates the form's validity
157
+ * attributes on change.
158
+ * @param {Event} - The form change event
159
+ * @return {void}
160
+ */
161
+ const formChangeCallback = (event) => {
162
+ setFormValidity(findParentForm(event.target));
163
+ };
164
+ /**
165
+ * The global form submit callback. We need to cancel any submission
166
+ * if a nested internals is invalid.
167
+ * @param {HTMLFormElement} - The form element
168
+ * @return {void}
169
+ */
170
+ const wireSubmitLogic = (form) => {
171
+ const submitButtonSelector = [
172
+ "button[type=submit]",
173
+ "input[type=submit]",
174
+ "button:not([type])",
175
+ ]
176
+ .map((sel) => `${sel}:not([disabled])`)
177
+ .map((sel) => `${sel}:not([form])${form.id ? `,${sel}[form='${form.id}']` : ""}`)
178
+ .join(",");
179
+ form.addEventListener("click", (event) => {
180
+ const target = event.target;
181
+ if (target.closest(submitButtonSelector)) {
182
+ // validate
183
+ const elements = formElementsMap.get(form);
184
+ /**
185
+ * If this form does not validate then we're done
186
+ */
187
+ if (form.noValidate) {
188
+ return;
189
+ }
190
+ /** If the Set has items, continue */
191
+ if (elements.size) {
192
+ const nodes = Array.from(elements);
193
+ /** Check the internals.checkValidity() of all nodes */
194
+ const validityList = nodes.reverse().map((node) => {
195
+ const internals = internalsMap.get(node);
196
+ return internals.reportValidity();
197
+ });
198
+ /** If any node is false, stop the event */
199
+ if (validityList.includes(false)) {
200
+ event.preventDefault();
201
+ }
202
+ }
203
+ }
204
+ });
205
+ };
206
+ /**
207
+ * The global form reset callback. This will loop over added
208
+ * inputs and call formResetCallback if applicable
209
+ * @return {void}
210
+ */
211
+ const formResetCallback = (event) => {
212
+ /** Get the Set of elements attached to this form */
213
+ const elements = formElementsMap.get(event.target);
214
+ /** Some forms won't contain form associated custom elements */
215
+ if (elements && elements.size) {
216
+ /** Loop over the elements and call formResetCallback if applicable */
217
+ elements.forEach((element) => {
218
+ if (element.constructor.formAssociated &&
219
+ element.formResetCallback) {
220
+ element.formResetCallback.apply(element);
221
+ }
222
+ });
223
+ }
224
+ };
225
+ /**
226
+ * Initialize the form. We will need to add submit and reset listeners
227
+ * if they don't already exist. If they do, just add the new ref to the form.
228
+ * @param {HTMLElement} ref - The element ref that includes internals
229
+ * @param {HTMLFormElement} form - The form the ref belongs to
230
+ * @param {ElementInternals} internals - The internals for ref
231
+ * @return {void}
232
+ */
233
+ const initForm = (ref, form, internals) => {
234
+ if (form) {
235
+ /** This will be a WeakMap<HTMLFormElement, Set<HTMLElement> */
236
+ const formElements = formElementsMap.get(form);
237
+ if (formElements) {
238
+ /** If formElements exists, add to it */
239
+ formElements.add(ref);
240
+ }
241
+ else {
242
+ /** If formElements doesn't exist, create it and add to it */
243
+ const initSet = new Set();
244
+ initSet.add(ref);
245
+ formElementsMap.set(form, initSet);
246
+ /** Add listeners to emulate validation and reset behavior */
247
+ wireSubmitLogic(form);
248
+ form.addEventListener("reset", formResetCallback);
249
+ form.addEventListener("input", formInputCallback);
250
+ form.addEventListener("change", formChangeCallback);
251
+ }
252
+ formsMap.set(form, { ref, internals });
253
+ /** Call formAssociatedCallback if applicable */
254
+ if (ref.constructor["formAssociated"] && ref.formAssociatedCallback) {
255
+ setTimeout(() => {
256
+ ref.formAssociatedCallback.apply(ref, [form]);
257
+ }, 0);
258
+ }
259
+ setFormValidity(form);
260
+ }
261
+ };
262
+ /**
263
+ * Recursively look for an element's parent form
264
+ * @param {Element} elem - The element to look for a parent form
265
+ * @return {HTMLFormElement|null} - The parent form, if one exists
266
+ */
267
+ const findParentForm = (elem) => {
268
+ let parent = elem.parentNode;
269
+ if (parent && parent.tagName !== "FORM") {
270
+ parent = findParentForm(parent);
271
+ }
272
+ return parent;
273
+ };
274
+ /**
275
+ * Throw an error if the element ref is not form associated
276
+ * @param ref {HTMLElement} - The element to check if it is form associated
277
+ * @param message {string} - The error message to throw
278
+ * @param ErrorType {any} - The error type to throw, defaults to DOMException
279
+ */
280
+ const throwIfNotFormAssociated = (ref, message, ErrorType = DOMException) => {
281
+ if (!ref.constructor["formAssociated"]) {
282
+ throw new ErrorType(message);
283
+ }
284
+ };
285
+ /**
286
+ * Called for each HTMLFormElement.checkValidity|reportValidity
287
+ * will loop over a form's added components and call the respective
288
+ * method modifying the default return value if needed
289
+ * @param form {HTMLFormElement} - The form element to run the method on
290
+ * @param returnValue {boolean} - The initial result of the original method
291
+ * @param method {'checkValidity'|'reportValidity'} - The original method
292
+ * @returns {boolean} The form's validity state
293
+ */
294
+ const overrideFormMethod = (form, returnValue, method) => {
295
+ const elements = formElementsMap.get(form);
296
+ /** Some forms won't contain form associated custom elements */
297
+ if (elements && elements.size) {
298
+ elements.forEach((element) => {
299
+ const internals = internalsMap.get(element);
300
+ const valid = internals[method]();
301
+ if (!valid) {
302
+ returnValue = false;
303
+ }
304
+ });
305
+ }
306
+ return returnValue;
307
+ };
308
+ /**
309
+ * Will upgrade an ElementInternals instance by initializing the
310
+ * instance's form and labels. This is called when the element is
311
+ * either constructed or appended from a DocumentFragment
312
+ * @param ref {HTMLElement} - The custom element to upgrade
313
+ */
314
+ const upgradeInternals = (ref) => {
315
+ let attached = false;
316
+ if (ref.constructor["formAssociated"]) {
317
+ let internals = internalsMap.get(ref);
318
+ // we might have cases where the internals are not set
319
+ if (internals === undefined) {
320
+ ref.attachInternals();
321
+ internals = internalsMap.get(ref);
322
+ attached = true;
323
+ }
324
+ const { labels, form } = internals;
325
+ initLabels(ref, labels);
326
+ initForm(ref, form, internals);
327
+ }
328
+ return attached;
329
+ };
330
+ /**
331
+ * Check to see if MutationObserver exists in the current
332
+ * execution context. Will likely return false on the server
333
+ * @returns {boolean}
334
+ */
335
+ function mutationObserverExists() {
336
+ return typeof MutationObserver !== "undefined";
337
+ }
338
+
339
+ const aom = {
340
+ ariaAtomic: "aria-atomic",
341
+ ariaAutoComplete: "aria-autocomplete",
342
+ ariaBrailleLabel: "aria-braillelabel",
343
+ ariaBrailleRoleDescription: "aria-brailleroledescription",
344
+ ariaBusy: "aria-busy",
345
+ ariaChecked: "aria-checked",
346
+ ariaColCount: "aria-colcount",
347
+ ariaColIndex: "aria-colindex",
348
+ ariaColIndexText: "aria-colindextext",
349
+ ariaColSpan: "aria-colspan",
350
+ ariaCurrent: "aria-current",
351
+ ariaDescription: "aria-description",
352
+ ariaDisabled: "aria-disabled",
353
+ ariaExpanded: "aria-expanded",
354
+ ariaHasPopup: "aria-haspopup",
355
+ ariaHidden: "aria-hidden",
356
+ ariaInvalid: "aria-invalid",
357
+ ariaKeyShortcuts: "aria-keyshortcuts",
358
+ ariaLabel: "aria-label",
359
+ ariaLevel: "aria-level",
360
+ ariaLive: "aria-live",
361
+ ariaModal: "aria-modal",
362
+ ariaMultiLine: "aria-multiline",
363
+ ariaMultiSelectable: "aria-multiselectable",
364
+ ariaOrientation: "aria-orientation",
365
+ ariaPlaceholder: "aria-placeholder",
366
+ ariaPosInSet: "aria-posinset",
367
+ ariaPressed: "aria-pressed",
368
+ ariaReadOnly: "aria-readonly",
369
+ ariaRelevant: "aria-relevant",
370
+ ariaRequired: "aria-required",
371
+ ariaRoleDescription: "aria-roledescription",
372
+ ariaRowCount: "aria-rowcount",
373
+ ariaRowIndex: "aria-rowindex",
374
+ ariaRowIndexText: "aria-rowindextext",
375
+ ariaRowSpan: "aria-rowspan",
376
+ ariaSelected: "aria-selected",
377
+ ariaSetSize: "aria-setsize",
378
+ ariaSort: "aria-sort",
379
+ ariaValueMax: "aria-valuemax",
380
+ ariaValueMin: "aria-valuemin",
381
+ ariaValueNow: "aria-valuenow",
382
+ ariaValueText: "aria-valuetext",
383
+ role: "role",
384
+ };
385
+ const initAom = (ref, internals) => {
386
+ for (let key in aom) {
387
+ internals[key] = null;
388
+ let closureValue = null;
389
+ const attributeName = aom[key];
390
+ Object.defineProperty(internals, key, {
391
+ get() {
392
+ return closureValue;
393
+ },
394
+ set(value) {
395
+ closureValue = value;
396
+ if (ref.isConnected) {
397
+ setAttribute(ref, attributeName, value);
398
+ }
399
+ else {
400
+ upgradeMap.set(ref, internals);
401
+ }
402
+ },
403
+ });
404
+ }
405
+ };
406
+
407
+ /**
408
+ * Initialize a ref by setting up an attribute observe on it
409
+ * looking for changes to disabled
410
+ * @param {HTMLElement} ref - The element to watch
411
+ * @param {ElementInternals} internals - The element internals instance for the ref
412
+ * @return {void}
413
+ */
414
+ const initRef = (ref, internals) => {
415
+ hiddenInputMap.set(internals, []);
416
+ disabledOrNameObserver.observe?.(ref, disabledOrNameObserverConfig);
417
+ };
418
+ function initNode(node) {
419
+ const internals = internalsMap.get(node);
420
+ const { form } = internals;
421
+ initForm(node, form, internals);
422
+ initLabels(node, internals.labels);
423
+ }
424
+ /**
425
+ * If a fieldset's disabled state is toggled, the formDisabledCallback
426
+ * on any child form-associated cusotm elements.
427
+ */
428
+ const walkFieldset = (node, firstRender = false) => {
429
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT, {
430
+ acceptNode(node) {
431
+ return internalsMap.has(node) ?
432
+ NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
433
+ }
434
+ });
435
+ let current = walker.nextNode();
436
+ /**
437
+ * We don't need to call anything on first render if
438
+ * the element isn't disabled
439
+ */
440
+ const isCallNecessary = (!firstRender || node.disabled);
441
+ while (current) {
442
+ if (current.formDisabledCallback && isCallNecessary) {
443
+ setDisabled(current, node.disabled);
444
+ }
445
+ current = walker.nextNode();
446
+ }
447
+ };
448
+ const disabledOrNameObserverConfig = { attributes: true, attributeFilter: ['disabled', 'name'] };
449
+ const disabledOrNameObserver = mutationObserverExists() ? new MutationObserver((mutationsList) => {
450
+ for (const mutation of mutationsList) {
451
+ const target = mutation.target;
452
+ /** Manage changes to the ref's disabled state */
453
+ if (mutation.attributeName === 'disabled') {
454
+ if (target.constructor['formAssociated']) {
455
+ setDisabled(target, target.hasAttribute('disabled'));
456
+ }
457
+ else if (target.localName === 'fieldset') {
458
+ /**
459
+ * Repurpose the observer for fieldsets which need
460
+ * to be walked whenever the disabled attribute is set
461
+ */
462
+ walkFieldset(target);
463
+ }
464
+ }
465
+ /** Manage changes to the ref's name */
466
+ if (mutation.attributeName === 'name') {
467
+ if (target.constructor['formAssociated']) {
468
+ const internals = internalsMap.get(target);
469
+ const value = refValueMap.get(target);
470
+ internals.setFormValue(value);
471
+ }
472
+ }
473
+ }
474
+ }) : {};
475
+ function observerCallback(mutationList) {
476
+ mutationList.forEach(mutationRecord => {
477
+ const { addedNodes, removedNodes } = mutationRecord;
478
+ const added = Array.from(addedNodes);
479
+ const removed = Array.from(removedNodes);
480
+ added.forEach(node => {
481
+ /** Allows for dynamic addition of elements to forms */
482
+ if (internalsMap.has(node) && node.constructor['formAssociated']) {
483
+ initNode(node);
484
+ }
485
+ /** Upgrade the accessibility information on any previously connected */
486
+ if (upgradeMap.has(node)) {
487
+ const internals = upgradeMap.get(node);
488
+ const aomKeys = Object.keys(aom);
489
+ aomKeys
490
+ .filter(key => internals[key] !== null)
491
+ .forEach(key => {
492
+ setAttribute(node, aom[key], internals[key]);
493
+ });
494
+ upgradeMap.delete(node);
495
+ }
496
+ /** Upgrade the validity state when the element is connected */
497
+ if (validityUpgradeMap.has(node)) {
498
+ const internals = validityUpgradeMap.get(node);
499
+ setAttribute(node, 'internals-valid', internals.validity.valid.toString());
500
+ setAttribute(node, 'internals-invalid', (!internals.validity.valid).toString());
501
+ setAttribute(node, 'aria-invalid', (!internals.validity.valid).toString());
502
+ validityUpgradeMap.delete(node);
503
+ }
504
+ /** If the node that's added is a form, check the validity */
505
+ if (node.localName === 'form') {
506
+ const formElements = formElementsMap.get(node);
507
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT, {
508
+ acceptNode(node) {
509
+ return (internalsMap.has(node) && node.constructor['formAssociated'] && !(formElements && formElements.has(node))) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
510
+ }
511
+ });
512
+ let current = walker.nextNode();
513
+ while (current) {
514
+ initNode(current);
515
+ current = walker.nextNode();
516
+ }
517
+ }
518
+ if (node.localName === 'fieldset') {
519
+ disabledOrNameObserver.observe?.(node, disabledOrNameObserverConfig);
520
+ walkFieldset(node, true);
521
+ }
522
+ });
523
+ removed.forEach(node => {
524
+ const internals = internalsMap.get(node);
525
+ /** Clean up any hidden input elements left after an element is disconnected */
526
+ if (internals && hiddenInputMap.get(internals)) {
527
+ removeHiddenInputs(internals);
528
+ }
529
+ /** Disconnect any unneeded MutationObservers */
530
+ if (shadowHostsMap.has(node)) {
531
+ const observer = shadowHostsMap.get(node);
532
+ observer.disconnect();
533
+ }
534
+ });
535
+ });
536
+ }
537
+ /**
538
+ * This observer callback is just for document fragments
539
+ * it will upgrade an ElementInternals instance if was appended
540
+ * from a document fragment.
541
+ */
542
+ function fragmentObserverCallback(mutationList) {
543
+ mutationList.forEach(mutation => {
544
+ const { removedNodes } = mutation;
545
+ removedNodes.forEach(node => {
546
+ const observer = documentFragmentMap.get(mutation.target);
547
+ if (internalsMap.has(node)) {
548
+ upgradeInternals(node);
549
+ }
550
+ observer.disconnect();
551
+ });
552
+ });
553
+ }
554
+ /**
555
+ * Defer the upgrade of nodes withing a DocumentFragment
556
+ * @param fragment {DocumentFragment}
557
+ */
558
+ const deferUpgrade = (fragment) => {
559
+ const observer = new MutationObserver(fragmentObserverCallback);
560
+ // is this using shady DOM and is not actually a DocumentFragment?
561
+ if (window?.ShadyDOM?.inUse &&
562
+ fragment.mode &&
563
+ fragment.host) {
564
+ // using shady DOM polyfill. Best to just observe the host.
565
+ fragment = fragment.host;
566
+ }
567
+ observer.observe?.(fragment, { childList: true });
568
+ documentFragmentMap.set(fragment, observer);
569
+ };
570
+ mutationObserverExists() ? new MutationObserver(observerCallback) : {};
571
+ const observerConfig = {
572
+ childList: true,
573
+ subtree: true
574
+ };
575
+
576
+ /** Emulate the browser's default ValidityState object */
577
+ class ValidityState {
578
+ constructor() {
579
+ this.badInput = false;
580
+ this.customError = false;
581
+ this.patternMismatch = false;
582
+ this.rangeOverflow = false;
583
+ this.rangeUnderflow = false;
584
+ this.stepMismatch = false;
585
+ this.tooLong = false;
586
+ this.tooShort = false;
587
+ this.typeMismatch = false;
588
+ this.valid = true;
589
+ this.valueMissing = false;
590
+ Object.seal(this);
591
+ }
592
+ }
593
+ /**
594
+ * Reset a ValidityState object back to valid
595
+ * @param {ValidityState} validityObject - The object to modify
596
+ * @return {ValidityState} - The modified ValidityStateObject
597
+ */
598
+ const setValid = (validityObject) => {
599
+ validityObject.badInput = false;
600
+ validityObject.customError = false;
601
+ validityObject.patternMismatch = false;
602
+ validityObject.rangeOverflow = false;
603
+ validityObject.rangeUnderflow = false;
604
+ validityObject.stepMismatch = false;
605
+ validityObject.tooLong = false;
606
+ validityObject.tooShort = false;
607
+ validityObject.typeMismatch = false;
608
+ validityObject.valid = true;
609
+ validityObject.valueMissing = false;
610
+ return validityObject;
611
+ };
612
+ /**
613
+ * Reconcile a ValidityState object with a new state object
614
+ * @param {ValidityState} - The base object to reconcile with new state
615
+ * @param {Object} - A partial ValidityState object to override the original
616
+ * @return {ValidityState} - The updated ValidityState object
617
+ */
618
+ const reconcileValidity = (validityObject, newState, form) => {
619
+ validityObject.valid = isValid(newState);
620
+ Object.keys(newState).forEach(key => validityObject[key] = newState[key]);
621
+ if (form) {
622
+ setFormValidity(form);
623
+ }
624
+ return validityObject;
625
+ };
626
+ /**
627
+ * Check if a partial ValidityState object should be valid
628
+ * @param {Object} - A partial ValidityState object
629
+ * @return {Boolean} - Should the new object be valid
630
+ */
631
+ const isValid = (validityState) => {
632
+ let valid = true;
633
+ for (let key in validityState) {
634
+ if (key !== 'valid' && validityState[key] !== false) {
635
+ valid = false;
636
+ }
637
+ }
638
+ return valid;
639
+ };
640
+
641
+ /** Save a reference to the ref for the CustomStateSet */
642
+ const customStateMap = new WeakMap();
643
+ function addState(ref, stateName) {
644
+ ref.toggleAttribute(stateName, true);
645
+ if (ref.part) {
646
+ ref.part.add(stateName);
647
+ }
648
+ }
649
+ class CustomStateSet extends Set {
650
+ static get isPolyfilled() {
651
+ return true;
652
+ }
653
+ constructor(ref) {
654
+ super();
655
+ if (!ref || !ref.tagName || ref.tagName.indexOf("-") === -1) {
656
+ throw new TypeError("Illegal constructor");
657
+ }
658
+ customStateMap.set(this, ref);
659
+ }
660
+ add(state) {
661
+ if (!/^--/.test(state) || typeof state !== "string") {
662
+ throw new DOMException(`Failed to execute 'add' on 'CustomStateSet': The specified value ${state} must start with '--'.`);
663
+ }
664
+ const result = super.add(state);
665
+ const ref = customStateMap.get(this);
666
+ const stateName = `state${state}`;
667
+ /**
668
+ * Only add the state immediately if the ref is connected to the DOM;
669
+ * otherwise, wait a tick because the element is likely being constructed
670
+ * by document.createElement and would throw otherwise.
671
+ */
672
+ if (ref.isConnected) {
673
+ addState(ref, stateName);
674
+ }
675
+ else {
676
+ setTimeout(() => {
677
+ addState(ref, stateName);
678
+ });
679
+ }
680
+ return result;
681
+ }
682
+ clear() {
683
+ for (let [entry] of this.entries()) {
684
+ this.delete(entry);
685
+ }
686
+ super.clear();
687
+ }
688
+ delete(state) {
689
+ const result = super.delete(state);
690
+ const ref = customStateMap.get(this);
691
+ /**
692
+ * Only toggle the state/attr immediately if the ref is connected to the DOM;
693
+ * otherwise, wait a tick because the element is likely being constructed
694
+ * by document.createElement and would throw otherwise.
695
+ */
696
+ if (ref.isConnected) {
697
+ ref.toggleAttribute(`state${state}`, false);
698
+ if (ref.part) {
699
+ ref.part.remove(`state${state}`);
700
+ }
701
+ }
702
+ else {
703
+ setTimeout(() => {
704
+ ref.toggleAttribute(`state${state}`, false);
705
+ if (ref.part) {
706
+ ref.part.remove(`state${state}`);
707
+ }
708
+ });
709
+ }
710
+ return result;
711
+ }
712
+ }
713
+
714
+ var __classPrivateFieldSet = (undefined && undefined.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
715
+ if (kind === "m") throw new TypeError("Private method is not writable");
716
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
717
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
718
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
719
+ };
720
+ var __classPrivateFieldGet = (undefined && undefined.__classPrivateFieldGet) || function (receiver, state, kind, f) {
721
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
722
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
723
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
724
+ };
725
+ var _HTMLFormControlsCollection_elements;
726
+ class HTMLFormControlsCollection {
727
+ constructor(elements) {
728
+ _HTMLFormControlsCollection_elements.set(this, void 0);
729
+ __classPrivateFieldSet(this, _HTMLFormControlsCollection_elements, elements, "f");
730
+ for (let i = 0; i < elements.length; i++) {
731
+ let element = elements[i];
732
+ this[i] = element;
733
+ if (element.hasAttribute('name')) {
734
+ this[element.getAttribute('name')] = element;
735
+ }
736
+ }
737
+ Object.freeze(this);
738
+ }
739
+ get length() {
740
+ return __classPrivateFieldGet(this, _HTMLFormControlsCollection_elements, "f").length;
741
+ }
742
+ [(_HTMLFormControlsCollection_elements = new WeakMap(), Symbol.iterator)]() {
743
+ return __classPrivateFieldGet(this, _HTMLFormControlsCollection_elements, "f")[Symbol.iterator]();
744
+ }
745
+ item(i) {
746
+ return this[i] == null ? null : this[i];
747
+ }
748
+ namedItem(name) {
749
+ return this[name] == null ? null : this[name];
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Patch the HTMLElement prototype
755
+ *
756
+ * This function patches checkValidity, reportValidity and elements
757
+ */
758
+ function patchFormPrototype() {
759
+ const checkValidity = HTMLFormElement.prototype.checkValidity;
760
+ HTMLFormElement.prototype.checkValidity = checkValidityOverride;
761
+ const reportValidity = HTMLFormElement.prototype.reportValidity;
762
+ HTMLFormElement.prototype.reportValidity = reportValidityOverride;
763
+ function checkValidityOverride(...args) {
764
+ let returnValue = checkValidity.apply(this, args);
765
+ return overrideFormMethod(this, returnValue, 'checkValidity');
766
+ }
767
+ function reportValidityOverride(...args) {
768
+ let returnValue = reportValidity.apply(this, args);
769
+ return overrideFormMethod(this, returnValue, 'reportValidity');
770
+ }
771
+ const { get } = Object.getOwnPropertyDescriptor(HTMLFormElement.prototype, 'elements');
772
+ Object.defineProperty(HTMLFormElement.prototype, 'elements', {
773
+ get(...args) {
774
+ const elements = get.call(this, ...args);
775
+ const polyfilledElements = Array.from(formElementsMap.get(this) || []);
776
+ // If there are no polyfilled elements, return the native elements collection
777
+ if (polyfilledElements.length === 0) {
778
+ return elements;
779
+ }
780
+ // Merge the native elements with the polyfilled elements
781
+ // and order them by their position in the DOM
782
+ const orderedElements = Array.from(elements).concat(polyfilledElements).sort((a, b) => {
783
+ if (a.compareDocumentPosition) {
784
+ return a.compareDocumentPosition(b) & 2 ? 1 : -1;
785
+ }
786
+ return 0;
787
+ });
788
+ return new HTMLFormControlsCollection(orderedElements);
789
+ },
790
+ });
791
+ }
792
+
793
+ class ElementInternals {
794
+ static get isPolyfilled() {
795
+ return true;
796
+ }
797
+ constructor(ref) {
798
+ if (!ref || !ref.tagName || ref.tagName.indexOf("-") === -1) {
799
+ throw new TypeError("Illegal constructor");
800
+ }
801
+ const rootNode = ref.getRootNode();
802
+ const validity = new ValidityState();
803
+ this.states = new CustomStateSet(ref);
804
+ refMap.set(this, ref);
805
+ validityMap.set(this, validity);
806
+ internalsMap.set(ref, this);
807
+ initAom(ref, this);
808
+ initRef(ref, this);
809
+ Object.seal(this);
810
+ /**
811
+ * If appended from a DocumentFragment, wait until it is connected
812
+ * before attempting to upgrade the internals instance
813
+ */
814
+ if (rootNode instanceof DocumentFragment) {
815
+ deferUpgrade(rootNode);
816
+ }
817
+ }
818
+ /**
819
+ * Will return true if the element is in a valid state
820
+ */
821
+ checkValidity() {
822
+ const ref = refMap.get(this);
823
+ throwIfNotFormAssociated(ref, `Failed to execute 'checkValidity' on 'ElementInternals': The target element is not a form-associated custom element.`);
824
+ /** If the element will not validate, it is necessarily valid by default */
825
+ if (!this.willValidate) {
826
+ return true;
827
+ }
828
+ const validity = validityMap.get(this);
829
+ if (!validity.valid) {
830
+ const validityEvent = new Event("invalid", {
831
+ bubbles: false,
832
+ cancelable: true,
833
+ composed: false,
834
+ });
835
+ ref.dispatchEvent(validityEvent);
836
+ }
837
+ return validity.valid;
838
+ }
839
+ /** The form element the custom element is associated with */
840
+ get form() {
841
+ const ref = refMap.get(this);
842
+ throwIfNotFormAssociated(ref, `Failed to read the 'form' property from 'ElementInternals': The target element is not a form-associated custom element.`);
843
+ let form;
844
+ if (ref.constructor["formAssociated"] === true) {
845
+ form = findParentForm(ref);
846
+ }
847
+ return form;
848
+ }
849
+ /** A list of all relative form labels for this element */
850
+ get labels() {
851
+ const ref = refMap.get(this);
852
+ throwIfNotFormAssociated(ref, `Failed to read the 'labels' property from 'ElementInternals': The target element is not a form-associated custom element.`);
853
+ const id = ref.getAttribute("id");
854
+ const hostRoot = ref.getRootNode();
855
+ if (hostRoot && id) {
856
+ return hostRoot.querySelectorAll(`[for="${id}"]`);
857
+ }
858
+ return [];
859
+ }
860
+ /** Will report the elements validity state */
861
+ reportValidity() {
862
+ const ref = refMap.get(this);
863
+ throwIfNotFormAssociated(ref, `Failed to execute 'reportValidity' on 'ElementInternals': The target element is not a form-associated custom element.`);
864
+ /** If the element will not validate, it is valid by default */
865
+ if (!this.willValidate) {
866
+ return true;
867
+ }
868
+ const valid = this.checkValidity();
869
+ const anchor = validationAnchorMap.get(this);
870
+ if (anchor && !ref.constructor["formAssociated"]) {
871
+ throw new DOMException(`Failed to execute 'reportValidity' on 'ElementInternals': The target element is not a form-associated custom element.`);
872
+ }
873
+ if (!valid && anchor) {
874
+ ref.focus();
875
+ anchor.focus();
876
+ }
877
+ return valid;
878
+ }
879
+ /** Sets the element's value within the form */
880
+ setFormValue(value) {
881
+ const ref = refMap.get(this);
882
+ throwIfNotFormAssociated(ref, `Failed to execute 'setFormValue' on 'ElementInternals': The target element is not a form-associated custom element.`);
883
+ removeHiddenInputs(this);
884
+ if (value != null && !(value instanceof FormData)) {
885
+ if (ref.getAttribute("name")) {
886
+ const hiddenInput = createHiddenInput(ref, this);
887
+ hiddenInput.value = value;
888
+ }
889
+ }
890
+ else if (value != null && value instanceof FormData) {
891
+ Array.from(value)
892
+ .reverse()
893
+ .forEach(([formDataKey, formDataValue]) => {
894
+ if (typeof formDataValue === "string") {
895
+ const hiddenInput = createHiddenInput(ref, this);
896
+ hiddenInput.name = formDataKey;
897
+ hiddenInput.value = formDataValue;
898
+ }
899
+ });
900
+ }
901
+ refValueMap.set(ref, value);
902
+ }
903
+ /**
904
+ * Sets the element's validity. The first argument is a partial ValidityState object
905
+ * reflecting the changes to be made to the element's validity. If the element is invalid,
906
+ * the second argument sets the element's validation message.
907
+ *
908
+ * If the field is valid and a message is specified, the method will throw a TypeError.
909
+ */
910
+ setValidity(validityChanges, validationMessage, anchor) {
911
+ const ref = refMap.get(this);
912
+ throwIfNotFormAssociated(ref, `Failed to execute 'setValidity' on 'ElementInternals': The target element is not a form-associated custom element.`);
913
+ if (!validityChanges) {
914
+ throw new TypeError("Failed to execute 'setValidity' on 'ElementInternals': 1 argument required, but only 0 present.");
915
+ }
916
+ validationAnchorMap.set(this, anchor);
917
+ const validity = validityMap.get(this);
918
+ const validityChangesObj = {};
919
+ for (const key in validityChanges) {
920
+ validityChangesObj[key] = validityChanges[key];
921
+ }
922
+ if (Object.keys(validityChangesObj).length === 0) {
923
+ setValid(validity);
924
+ }
925
+ const check = { ...validity, ...validityChangesObj };
926
+ delete check.valid;
927
+ const { valid } = reconcileValidity(validity, check, this.form);
928
+ if (!valid && !validationMessage) {
929
+ throw new DOMException(`Failed to execute 'setValidity' on 'ElementInternals': The second argument should not be empty if one or more flags in the first argument are true.`);
930
+ }
931
+ validationMessageMap.set(this, valid ? "" : validationMessage);
932
+ // check to make sure the host element is connected before adding attributes
933
+ // because safari doesnt allow elements to have attributes added in the constructor
934
+ if (ref.isConnected) {
935
+ ref.toggleAttribute("internals-invalid", !valid);
936
+ ref.toggleAttribute("internals-valid", valid);
937
+ setAttribute(ref, "aria-invalid", `${!valid}`);
938
+ }
939
+ else {
940
+ validityUpgradeMap.set(ref, this);
941
+ }
942
+ }
943
+ get shadowRoot() {
944
+ const ref = refMap.get(this);
945
+ const shadowRoot = shadowRootMap.get(ref);
946
+ if (shadowRoot) {
947
+ return shadowRoot;
948
+ }
949
+ return null;
950
+ }
951
+ /** The element's validation message set during a call to ElementInternals.setValidity */
952
+ get validationMessage() {
953
+ const ref = refMap.get(this);
954
+ throwIfNotFormAssociated(ref, `Failed to read the 'validationMessage' property from 'ElementInternals': The target element is not a form-associated custom element.`);
955
+ return validationMessageMap.get(this);
956
+ }
957
+ /** The current validity state of the object */
958
+ get validity() {
959
+ const ref = refMap.get(this);
960
+ throwIfNotFormAssociated(ref, `Failed to read the 'validity' property from 'ElementInternals': The target element is not a form-associated custom element.`);
961
+ const validity = validityMap.get(this);
962
+ return validity;
963
+ }
964
+ /** If true the element will participate in a form's constraint validation. */
965
+ get willValidate() {
966
+ const ref = refMap.get(this);
967
+ throwIfNotFormAssociated(ref, `Failed to read the 'willValidate' property from 'ElementInternals': The target element is not a form-associated custom element.`);
968
+ if (ref.matches(":disabled") ||
969
+ ref["disabled"] ||
970
+ ref.hasAttribute("disabled") ||
971
+ ref.hasAttribute("readonly")) {
972
+ return false;
973
+ }
974
+ return true;
975
+ }
976
+ }
977
+ function isElementInternalsSupported() {
978
+ if (typeof window === "undefined" ||
979
+ !window.ElementInternals ||
980
+ !HTMLElement.prototype.attachInternals) {
981
+ return false;
982
+ }
983
+ class ElementInternalsFeatureDetection extends HTMLElement {
984
+ constructor() {
985
+ super();
986
+ this.internals = this.attachInternals();
987
+ }
988
+ }
989
+ const randomName = `element-internals-feature-detection-${Math.random()
990
+ .toString(36)
991
+ .replace(/[^a-z]+/g, "")}`;
992
+ customElements.define(randomName, ElementInternalsFeatureDetection);
993
+ const featureDetectionElement = new ElementInternalsFeatureDetection();
994
+ return [
995
+ "shadowRoot",
996
+ "form",
997
+ "willValidate",
998
+ "validity",
999
+ "validationMessage",
1000
+ "labels",
1001
+ "setFormValue",
1002
+ "setValidity",
1003
+ "checkValidity",
1004
+ "reportValidity",
1005
+ ].every((prop) => prop in featureDetectionElement.internals);
1006
+ }
1007
+ let hasElementInternalsPolyfillBeenApplied = false;
1008
+ let hasCustomStateSetPolyfillBeenApplied = false;
1009
+ /**
1010
+ * Forcibly applies the polyfill for CustomStateSet.
1011
+ *
1012
+ * https://developer.mozilla.org/en-US/docs/Web/API/CustomStateSet
1013
+ */
1014
+ function forceCustomStateSetPolyfill(attachInternals) {
1015
+ if (hasCustomStateSetPolyfillBeenApplied) {
1016
+ return;
1017
+ }
1018
+ hasCustomStateSetPolyfillBeenApplied = true;
1019
+ /** @ts-expect-error These types won't match because this is a polyfill */
1020
+ window.CustomStateSet = CustomStateSet;
1021
+ if (attachInternals) {
1022
+ HTMLElement.prototype.attachInternals = function (...args) {
1023
+ const internals = attachInternals.call(this, args);
1024
+ internals.states = new CustomStateSet(this);
1025
+ return internals;
1026
+ };
1027
+ }
1028
+ }
1029
+ /**
1030
+ * Forcibly applies the polyfill for ElementInternals. Useful for situations
1031
+ * like Chrome extensions where Chrome supports ElementInternals, but the
1032
+ * CustomElements polyfill is required.
1033
+ *
1034
+ * https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals
1035
+ *
1036
+ * @param forceCustomStateSet Optional: when true, forces the
1037
+ * [CustomStateSet](https://developer.mozilla.org/en-US/docs/Web/API/CustomStateSet)
1038
+ * polyfill as well.
1039
+ */
1040
+ function forceElementInternalsPolyfill(forceCustomStateSet = true) {
1041
+ /**
1042
+ * This is a flag to prevent a DOMException from being thrown when
1043
+ * attachInternals is called in upgradeInternals.
1044
+ */
1045
+ let attachedFlag = false;
1046
+ if (hasElementInternalsPolyfillBeenApplied) {
1047
+ return;
1048
+ }
1049
+ hasElementInternalsPolyfillBeenApplied = true;
1050
+ if (typeof window !== "undefined") {
1051
+ /** @ts-expect-error: we need to replace the default ElementInternals */
1052
+ window.ElementInternals = ElementInternals;
1053
+ }
1054
+ if (typeof CustomElementRegistry !== "undefined") {
1055
+ const define = CustomElementRegistry.prototype.define;
1056
+ CustomElementRegistry.prototype.define = function (name, constructor, options) {
1057
+ if (constructor.formAssociated) {
1058
+ const connectedCallback = constructor.prototype.connectedCallback;
1059
+ constructor.prototype.connectedCallback = function () {
1060
+ if (!connectedCallbackMap.has(this)) {
1061
+ connectedCallbackMap.set(this, true);
1062
+ if (this.hasAttribute("disabled")) {
1063
+ setDisabled(this, true);
1064
+ }
1065
+ }
1066
+ if (connectedCallback != null) {
1067
+ connectedCallback.apply(this);
1068
+ }
1069
+ // always upgradeInternals in connectedCallback instead of constructor
1070
+ attachedFlag = upgradeInternals(this);
1071
+ };
1072
+ }
1073
+ define.call(this, name, constructor, options);
1074
+ };
1075
+ }
1076
+ /**
1077
+ * Attaches an ElementInternals instance to a custom element. Calling this method
1078
+ * on a built-in element will throw an error.
1079
+ */
1080
+ if (typeof HTMLElement !== "undefined") {
1081
+ HTMLElement.prototype.attachInternals = function () {
1082
+ if (!this.tagName) {
1083
+ /** This happens in the LitSSR environment. Here we can generally ignore internals for now */
1084
+ return {};
1085
+ }
1086
+ else if (this.tagName.indexOf("-") === -1) {
1087
+ throw new Error(`Failed to execute 'attachInternals' on 'HTMLElement': Unable to attach ElementInternals to non-custom elements.`);
1088
+ }
1089
+ if (internalsMap.has(this) && !attachedFlag) {
1090
+ throw new DOMException(`DOMException: Failed to execute 'attachInternals' on 'HTMLElement': ElementInternals for the specified element was already attached.`);
1091
+ }
1092
+ return new ElementInternals(this);
1093
+ };
1094
+ }
1095
+ if (typeof Element !== "undefined") {
1096
+ function attachShadowObserver(...args) {
1097
+ const shadowRoot = attachShadow.apply(this, args);
1098
+ shadowRootMap.set(this, shadowRoot);
1099
+ if (mutationObserverExists()) {
1100
+ const observer = new MutationObserver(observerCallback);
1101
+ if (window.ShadyDOM) {
1102
+ observer.observe(this, observerConfig);
1103
+ }
1104
+ else {
1105
+ observer.observe(shadowRoot, observerConfig);
1106
+ }
1107
+ shadowHostsMap.set(this, observer);
1108
+ }
1109
+ return shadowRoot;
1110
+ }
1111
+ const attachShadow = Element.prototype.attachShadow;
1112
+ Element.prototype.attachShadow = attachShadowObserver;
1113
+ }
1114
+ if (mutationObserverExists() && typeof document !== "undefined") {
1115
+ const documentObserver = new MutationObserver(observerCallback);
1116
+ documentObserver.observe(document.documentElement, observerConfig);
1117
+ }
1118
+ /**
1119
+ * Keeps the polyfill from throwing in environments where HTMLFormElement
1120
+ * is undefined like in a server environment
1121
+ */
1122
+ if (typeof HTMLFormElement !== "undefined") {
1123
+ patchFormPrototype();
1124
+ }
1125
+ if (forceCustomStateSet ||
1126
+ (typeof window !== "undefined" && !window.CustomStateSet)) {
1127
+ forceCustomStateSetPolyfill();
1128
+ }
1129
+ }
1130
+
1131
+ // Deteermine whether the webcomponents polyfill has been applied.
1132
+ const isCePolyfill = !!customElements.polyfillWrapFlushCallback;
1133
+ // custom elements polyfill is on. Do not auto-apply. User should determine
1134
+ // whether to force or not.
1135
+ if (!isCePolyfill) {
1136
+ if (!isElementInternalsSupported()) {
1137
+ forceElementInternalsPolyfill(false);
1138
+ }
1139
+ else if (typeof window !== "undefined" && !window.CustomStateSet) {
1140
+ forceCustomStateSetPolyfill(HTMLElement.prototype.attachInternals);
1141
+ }
1142
+ }
1143
+
1144
+ /* Polyfill para suporte a Safari -16.5 */
5
1145
  function CuraInit(options, w = window) {
6
1146
  w.CuraInit = options;
7
1147
  }