@schukai/monster 4.43.2 → 4.43.3

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.
@@ -21,29 +21,29 @@ import { Formatter } from "../text/formatter.mjs";
21
21
  import { parseDataURL } from "../types/dataurl.mjs";
22
22
  import { getGlobalObject } from "../types/global.mjs";
23
23
  import {
24
- isArray,
25
- isFunction,
26
- isIterable,
27
- isObject,
28
- isString,
24
+ isArray,
25
+ isFunction,
26
+ isIterable,
27
+ isObject,
28
+ isString,
29
29
  } from "../types/is.mjs";
30
30
  import { Observer } from "../types/observer.mjs";
31
31
  import { ProxyObserver } from "../types/proxyobserver.mjs";
32
32
  import {
33
- validateFunction,
34
- validateInstance,
35
- validateObject,
33
+ validateFunction,
34
+ validateInstance,
35
+ validateObject,
36
36
  } from "../types/validate.mjs";
37
37
  import { clone } from "../util/clone.mjs";
38
38
  import { getLinkedObjects, hasObjectLink } from "./attributes.mjs";
39
39
  import {
40
- ATTRIBUTE_DISABLED,
41
- ATTRIBUTE_OPTIONS,
42
- ATTRIBUTE_INIT_CALLBACK,
43
- ATTRIBUTE_OPTIONS_SELECTOR,
44
- ATTRIBUTE_SCRIPT_HOST,
45
- customElementUpdaterLinkSymbol,
46
- initControlCallbackName,
40
+ ATTRIBUTE_DISABLED,
41
+ ATTRIBUTE_OPTIONS,
42
+ ATTRIBUTE_INIT_CALLBACK,
43
+ ATTRIBUTE_OPTIONS_SELECTOR,
44
+ ATTRIBUTE_SCRIPT_HOST,
45
+ customElementUpdaterLinkSymbol,
46
+ initControlCallbackName,
47
47
  } from "./constants.mjs";
48
48
  import { findDocumentTemplate, Template } from "./template.mjs";
49
49
  import { addObjectWithUpdaterToElement } from "./updater.mjs";
@@ -55,13 +55,13 @@ import { setOptionFromAttribute } from "./util/set-option-from-attribute.mjs";
55
55
  import { addErrorAttribute } from "./error.mjs";
56
56
 
57
57
  export {
58
- CustomElement,
59
- initMethodSymbol,
60
- assembleMethodSymbol,
61
- attributeObserverSymbol,
62
- registerCustomElement,
63
- getSlottedElements,
64
- updaterTransformerMethodsSymbol,
58
+ CustomElement,
59
+ initMethodSymbol,
60
+ assembleMethodSymbol,
61
+ attributeObserverSymbol,
62
+ registerCustomElement,
63
+ getSlottedElements,
64
+ updaterTransformerMethodsSymbol,
65
65
  };
66
66
 
67
67
  /**
@@ -73,14 +73,14 @@ const initMethodSymbol = Symbol.for("@schukai/monster/dom/@@initMethodSymbol");
73
73
  * @type {symbol}
74
74
  */
75
75
  const assembleMethodSymbol = Symbol.for(
76
- "@schukai/monster/dom/@@assembleMethodSymbol",
76
+ "@schukai/monster/dom/@@assembleMethodSymbol",
77
77
  );
78
78
 
79
79
  /**
80
80
  * @type {symbol}
81
81
  */
82
82
  const updaterTransformerMethodsSymbol = Symbol.for(
83
- "@schukai/monster/dom/@@updaterTransformerMethodsSymbol",
83
+ "@schukai/monster/dom/@@updaterTransformerMethodsSymbol",
84
84
  );
85
85
 
86
86
  /**
@@ -88,7 +88,7 @@ const updaterTransformerMethodsSymbol = Symbol.for(
88
88
  * @type {symbol}
89
89
  */
90
90
  const attributeObserverSymbol = Symbol.for(
91
- "@schukai/monster/dom/@@attributeObserver",
91
+ "@schukai/monster/dom/@@attributeObserver",
92
92
  );
93
93
 
94
94
  /**
@@ -96,7 +96,7 @@ const attributeObserverSymbol = Symbol.for(
96
96
  * @type {symbol}
97
97
  */
98
98
  const attributeMutationObserverSymbol = Symbol(
99
- "@schukai/monster/dom/@@mutationObserver",
99
+ "@schukai/monster/dom/@@mutationObserver",
100
100
  );
101
101
 
102
102
  /**
@@ -185,577 +185,577 @@ const scriptHostElementSymbol = Symbol("scriptHostElement");
185
185
  * @summary A base class for HTML5 custom controls.
186
186
  */
187
187
  class CustomElement extends HTMLElement {
188
- /**
189
- * A new object is created. First, the `initOptions` method is called. Here the
190
- * options can be defined in derived classes. Subsequently, the shadowRoot is initialized.
191
- *
192
- * IMPORTANT: CustomControls instances are not created via the constructor, but either via a tag in the HTML or via <code>document.createElement()</code>.
193
- *
194
- * @throws {Error} the option attribute does not contain a valid JSON definition.
195
- */
196
- constructor() {
197
- super();
198
-
199
- this[attributeObserverSymbol] = {};
200
-
201
- const options = initOptionsFromAttributes(this, extend({}, this.defaults));
202
- if (!isObject(options)) {
203
- throw new Error(
204
- `The options are not defined correctly in the ${this.getTag()} element.`,
205
- );
206
- }
207
-
208
- if (this.customization instanceof Map) {
209
- const pathfinder = new Pathfinder(options);
210
- this.customization.forEach((value, key) => {
211
- pathfinder.setVia(key, value);
212
- });
213
- }
214
-
215
- this[internalSymbol] = new ProxyObserver({ options });
216
- this[initMethodSymbol]();
217
- initOptionObserver.call(this);
218
- this[scriptHostElementSymbol] = [];
219
- }
220
-
221
- /**
222
- * This method is called by the `instanceof` operator.
223
- *
224
- * @return {symbol}
225
- * @since 2.1.0
226
- */
227
- static get [instanceSymbol]() {
228
- return Symbol.for("@schukai/monster/dom/custom-element@@instance");
229
- }
230
-
231
- /**
232
- * This method determines which attributes are to be
233
- * monitored by `attributeChangedCallback()`. Unfortunately, this method is static.
234
- * Therefore, the `observedAttributes` property cannot be changed during runtime.
235
- *
236
- * @return {string[]}
237
- * @since 1.15.0
238
- */
239
- static get observedAttributes() {
240
- return [];
241
- }
242
-
243
- /**
244
- *
245
- * @param attribute
246
- * @param callback
247
- * @return {CustomElement}
248
- */
249
- addAttributeObserver(attribute, callback) {
250
- validateFunction(callback);
251
- this[attributeObserverSymbol][attribute] = callback;
252
- return this;
253
- }
254
-
255
- /**
256
- *
257
- * @param attribute
258
- * @return {CustomElement}
259
- */
260
- removeAttributeObserver(attribute) {
261
- delete this[attributeObserverSymbol][attribute];
262
- return this;
263
- }
264
-
265
- /**
266
- * The `customization` property allows overwriting the defaults.
267
- * Unlike the defaults that expect an object, the customization is a Map.
268
- * This also allows overwriting individual values in a deeper structure
269
- * without having to redefine the entire structure and thus changing the defaults.
270
- * @returns {Map}
271
- */
272
- get customization() {
273
- return new Map();
274
- }
275
-
276
- /**
277
- * The `defaults` property defines the default values for a control. If you want to override these,
278
- * you can use various methods, which are described in the documentation available at
279
- * {@link https://monsterjs.orgendocconfigurate-a-monster-control}.
280
- *
281
- * The individual configuration values are listed below:
282
- *
283
- * More information about the shadowRoot can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow),
284
- * in the [HTML Standard](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements) or in the [WHATWG Wiki](https://wiki.whatwg.org/wiki/Custom_Elements).
285
- *
286
- * More information about the template element can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).
287
- *
288
- * More information about the slot element can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot).
289
- *
290
- * @property {boolean} disabled=false Specifies whether the control is disabled. When present, it makes the element non-mutable, non-focusable, and non-submittable with the form.
291
- * @property {string} shadowMode=open Specifies the mode of the shadow root. When set to `open`, elements in the shadow root are accessible from JavaScript outside the root, while setting it to `closed` denies access to the root's nodes from JavaScript outside it.
292
- * @property {Boolean} delegatesFocus=true Specifies the behavior of the control with respect to focusability. When set to `true`, it mitigates custom element issues around focusability. When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling.
293
- * @property {Object} templates Specifies the templates used by the control.
294
- * @property {string} templates.main=undefined Specifies the main template used by the control.
295
- * @property {Object} templateMapping Specifies the mapping of templates.
296
- * @property {Object} templateFormatter Specifies the formatter for the templates.
297
- * @property {Object} templateFormatter.marker Specifies the marker for the templates.
298
- * @property {Function} templateFormatter.marker.open=null Specifies the opening marker for the templates.
299
- * @property {Function} templateFormatter.marker.close=null Specifies the closing marker for the templates.
300
- * @property {Boolean} templateFormatter.i18n=false Specifies whether the templates should be formatted with i18n.
301
- * @property {Boolean} eventProcessing=false Specifies whether the control processes events.
302
- * @since 1.8.0
303
- */
304
- get defaults() {
305
- return {
306
- disabled: false,
307
- shadowMode: "open",
308
- delegatesFocus: true,
309
- templates: {
310
- main: undefined,
311
- },
312
- templateMapping: {},
313
- templateFormatter: {
314
- marker: {
315
- open: null,
316
- close: null,
317
- },
318
- i18n: false,
319
- },
320
-
321
- eventProcessing: false,
322
- };
323
- }
324
-
325
- /**
326
- * This method updates the labels of the element.
327
- * The labels are defined in the option object.
328
- * The key of the label is used to retrieve the translation from the document.
329
- * If the translation is different from the label, the label is updated.
330
- *
331
- * Before you can use this method, you must have loaded the translations.
332
- *
333
- * @return {CustomElement}
334
- * @throws {Error} Cannot find an element with translations. Add a translation object to the document.
335
- */
336
- updateI18n() {
337
- let translations;
338
-
339
- try {
340
- translations = getDocumentTranslations();
341
- } catch (e) {
342
- addErrorAttribute(this, e);
343
- return this;
344
- }
345
-
346
- if (!translations) {
347
- return this;
348
- }
349
-
350
- const labels = this.getOption("labels");
351
- if (!(isObject(labels) || isIterable(labels))) {
352
- return this;
353
- }
354
-
355
- for (const key in labels) {
356
- const def = labels[key];
357
-
358
- if (isString(def)) {
359
- const text = translations.getText(key, def);
360
- if (text !== def) {
361
- this.setOption(`labels.${key}`, text);
362
- }
363
- continue;
364
- } else if (isObject(def)) {
365
- for (const k in def) {
366
- const d = def[k];
367
-
368
- const text = translations.getPluralRuleText(key, k, d);
369
- if (!isString(text)) {
370
- throw new Error("Invalid labels definition");
371
- }
372
- if (text !== d) {
373
- this.setOption(`labels.${key}.${k}`, text);
374
- }
375
- }
376
- continue;
377
- }
378
-
379
- throw new Error("Invalid labels definition");
380
- }
381
- return this;
382
- }
383
-
384
- /**
385
- * The `getTag()` method returns the tag name associated with the custom element. This method should be overwritten
386
- * by the derived class.
387
- *
388
- * Note that there is no check on the name of the tag in this class. It is the responsibility of
389
- * the developer to assign an appropriate tag name. If the name is not valid, the
390
- * `registerCustomElement()` method will issue an error.
391
- *
392
- * @see https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
393
- * @throws {Error} This method must be overridden by the derived class.
394
- * @return {string} The tag name associated with the custom element.
395
- * @since 1.7.0
396
- */
397
- static getTag() {
398
- throw new Error(
399
- "The method `getTag()` must be overridden by the derived class.",
400
- );
401
- }
402
-
403
- /**
404
- * The `getCSSStyleSheet()` method returns a `CSSStyleSheet` object that defines the styles for the custom element.
405
- * If the environment does not support the `CSSStyleSheet` constructor, then an object can be built using the provided detour.
406
- *
407
- * If `undefined` is returned, then the shadow root does not receive a stylesheet.
408
- *
409
- * Example usage:
410
- *
411
- * ```js
412
- * class MyElement extends CustomElement {
413
- * static getCSSStyleSheet() {
414
- * const sheet = new CSSStyleSheet();
415
- * sheet.replaceSync("p { color: red; }");
416
- * return sheet;
417
- * }
418
- * }
419
- * ```
420
- *
421
- * If the environment does not support the `CSSStyleSheet` constructor,
422
- * you can use the following workaround to create the stylesheet:
423
- *
424
- * ```js
425
- * const doc = document.implementation.createHTMLDocument('title');
426
- * let style = doc.createElement("style");
427
- * style.innerHTML = "p { color: red; }";
428
- * style.appendChild(document.createTextNode(""));
429
- * doc.head.appendChild(style);
430
- * return doc.styleSheets[0];
431
- * ```
432
- *
433
- * @return {CSSStyleSheet|CSSStyleSheet[]|string|undefined} A `CSSStyleSheet` object or an array of such objects that define the styles for the custom element, or `undefined` if no stylesheet should be applied.
434
- */
435
- static getCSSStyleSheet() {
436
- return undefined;
437
- }
438
-
439
- /**
440
- * attach a new observer
441
- *
442
- * @param {Observer} observer
443
- * @return {CustomElement}
444
- */
445
- attachObserver(observer) {
446
- this[internalSymbol].attachObserver(observer);
447
- return this;
448
- }
449
-
450
- /**
451
- * detach a observer
452
- *
453
- * @param {Observer} observer
454
- * @return {CustomElement}
455
- */
456
- detachObserver(observer) {
457
- this[internalSymbol].detachObserver(observer);
458
- return this;
459
- }
460
-
461
- /**
462
- * @param {Observer} observer
463
- * @return {ProxyObserver}
464
- */
465
- containsObserver(observer) {
466
- return this[internalSymbol].containsObserver(observer);
467
- }
468
-
469
- /**
470
- * nested options can be specified by path `a.b.c`
471
- *
472
- * @param {string} path
473
- * @param {*} defaultValue
474
- * @return {*}
475
- * @since 1.10.0
476
- */
477
- getOption(path, defaultValue = undefined) {
478
- let value;
479
-
480
- try {
481
- value = new Pathfinder(
482
- this[internalSymbol].getRealSubject()["options"],
483
- ).getVia(path);
484
- } catch (e) {}
485
-
486
- if (value === undefined) return defaultValue;
487
- return value;
488
- }
489
-
490
- /**
491
- * Set option and inform elements
492
- *
493
- * @param {string} path
494
- * @param {*} value
495
- * @return {CustomElement}
496
- * @since 1.14.0
497
- */
498
- setOption(path, value) {
499
- new Pathfinder(this[internalSymbol].getSubject()["options"]).setVia(
500
- path,
501
- value,
502
- );
503
- return this;
504
- }
505
-
506
- /**
507
- * @since 1.15.0
508
- * @param {string|object} options
509
- * @return {CustomElement}
510
- */
511
- setOptions(options) {
512
- if (isString(options)) {
513
- options = parseOptionsJSON.call(this, options);
514
- }
515
- // 2024-01-21: remove this.defaults, otherwise it will overwrite
516
- // the current settings that have already been made.
517
- // https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/136
518
- extend(this[internalSymbol].getSubject()["options"], options);
519
-
520
- return this;
521
- }
522
-
523
- /**
524
- * Is called once via the constructor
525
- *
526
- * @return {CustomElement}
527
- * @since 1.8.0
528
- */
529
- [initMethodSymbol]() {
530
- return this;
531
- }
532
-
533
- /**
534
- * This method is called once when the object is equipped with update for the dynamic change of the dom.
535
- * The functions returned here can be used as pipe functions in the template.
536
- *
537
- * In the example, the function `my-transformer` is defined. In the template, you can use it as follows:
538
- *
539
- * ```html
540
- * <my-element
541
- * data-monster-option-transformer="path:my-value | call:my-transformer">
542
- * </my-element>
543
- * ```
544
- *
545
- * The function `my-transformer` is called with the value of `my-value` as a parameter.
546
- *
547
- * ```js
548
- * class MyElement extends CustomElement {
549
- * [updaterTransformerMethodsSymbol]() {
550
- * return {
551
- * "my-transformer": (value) => {
552
- * switch (typeof Wert) {
553
- * case "string":
554
- * return value + "!";
555
- * case "Zahl":
556
- * return value + 1;
557
- * default:
558
- * return value;
559
- * }
560
- * }
561
- * };
562
- * };
563
- * }
564
- * ```
565
- *
566
- * @return {object}
567
- * @since 2.43.0
568
- */
569
- [updaterTransformerMethodsSymbol]() {
570
- return {};
571
- }
572
-
573
- /**
574
- * This method is called once when the object is included in the DOM for the first time. It performs the following actions:
575
- *
576
- * <ol>
577
- * <li>Extracts the options from the attributes and the script tag of the element and sets them.</li>
578
- * <li>Initializes the shadow root and its CSS stylesheet (if specified).</li>
579
- * <li>Initializes the HTML content of the element.</li>
580
- * <li>Initializes the custom elements inside the shadow root and the slotted elements.</li>
581
- * <li>Attaches a mutation observer to observe changes to the attributes of the element.</li>
582
- *
583
- * @return {CustomElement} - The updated custom element.
584
- * @since 1.8.0
585
- */
586
- [assembleMethodSymbol]() {
587
- let elements;
588
- let nodeList;
589
- // Extract options from attributes and set them
590
- const AttributeOptions = getOptionsFromAttributes.call(this);
591
- if (
592
- isObject(AttributeOptions) &&
593
- Object.keys(AttributeOptions).length > 0
594
- ) {
595
- this.setOptions(AttributeOptions);
596
- }
597
- // Extract options from script tag and set them
598
- const ScriptOptions = getOptionsFromScriptTag.call(this);
599
- if (isObject(ScriptOptions) && Object.keys(ScriptOptions).length > 0) {
600
- this.setOptions(ScriptOptions);
601
- }
602
- // Initialize the shadow root and its CSS stylesheet
603
- if (this.getOption("shadowMode", false) !== false) {
604
- try {
605
- initShadowRoot.call(this);
606
- elements = this.shadowRoot.childNodes;
607
- } catch (e) {
608
- addErrorAttribute(this, e);
609
- }
610
- try {
611
- initCSSStylesheet.call(this);
612
- } catch (e) {
613
- addErrorAttribute(this, e);
614
- }
615
- }
616
- // If the elements are not found inside the shadow root, initialize the HTML content of the element
617
- if (!(elements instanceof NodeList)) {
618
- initHtmlContent.call(this);
619
- elements = this.childNodes;
620
- }
621
- // Initialize the custom elements inside the shadow root and the slotted elements
622
- initFromCallbackHost.call(this);
623
- try {
624
- nodeList = new Set([...elements, ...getSlottedElements.call(this)]);
625
- } catch (e) {
626
- nodeList = elements;
627
- }
628
- try {
629
- this[updateCloneDataSymbol] = clone(
630
- this[internalSymbol].getRealSubject()["options"],
631
- );
632
- } catch (e) {
633
- addErrorAttribute(this, e);
634
- }
635
- const cfg = {};
636
- if (this.getOption("eventProcessing") === true) {
637
- cfg.eventProcessing = true;
638
- }
639
- addObjectWithUpdaterToElement.call(
640
- this,
641
- nodeList,
642
- customElementUpdaterLinkSymbol,
643
- this[updateCloneDataSymbol],
644
- cfg,
645
- );
646
- // Attach a mutation observer to observe changes to the attributes of the element
647
- attachAttributeChangeMutationObserver.call(this);
648
-
649
- if (isFunction(this[internalSymbol]?.syncDisabledState)) {
650
- this[internalSymbol].syncDisabledState();
651
- }
652
-
653
- return this;
654
- }
655
-
656
- /**
657
- * You know what you are doing? This function is only for advanced users.
658
- * The result is a clone of the internal data.
659
- *
660
- * @return {*}
661
- */
662
- getInternalUpdateCloneData() {
663
- return clone(this[updateCloneDataSymbol]);
664
- }
665
-
666
- /**
667
- * This method is called every time the element is inserted into the DOM. It checks if the custom element
668
- * has already been initialized and if not, calls the assembleMethod to initialize it.
669
- *
670
- * @return {void}
671
- * @since 1.7.0
672
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/connectedCallback
673
- */
674
- connectedCallback() {
675
- // Check if the object has already been initialized
676
- if (!hasObjectLink(this, customElementUpdaterLinkSymbol)) {
677
- // If not, call the assembleMethod to initialize the object
678
- this[assembleMethodSymbol]();
679
- }
680
- }
681
-
682
- /**
683
- * Called every time the element is removed from the DOM. Useful for running clean up code.
684
- *
685
- * @return {void}
686
- * @since 1.7.0
687
- */
688
- disconnectedCallback() {}
689
-
690
- /**
691
- * The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)).
692
- *
693
- * @return {void}
694
- * @since 1.7.0
695
- */
696
- adoptedCallback() {}
697
-
698
- /**
699
- * Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial
700
- * values when an element is created by the parser, or upgraded. Note: only attributes listed in the observedAttributes
701
- * property will receive this callback.
702
- *
703
- * @param {string} attrName
704
- * @param {string} oldVal
705
- * @param {string} newVal
706
- * @return {void}
707
- * @since 1.15.0
708
- */
709
- attributeChangedCallback(attrName, oldVal, newVal) {
710
- if (attrName.startsWith("data-monster-option-")) {
711
- setOptionFromAttribute(
712
- this,
713
- attrName,
714
- this[internalSymbol].getSubject()["options"],
715
- );
716
- }
717
-
718
- const callback = this[attributeObserverSymbol]?.[attrName];
719
- if (isFunction(callback)) {
720
- try {
721
- callback.call(this, newVal, oldVal);
722
- } catch (e) {
723
- addErrorAttribute(this, e);
724
- }
725
- }
726
- }
727
-
728
- /**
729
- * Checks if the provided node is part of this component's child nodes,
730
- * including those within the shadow root, if present.
731
- *
732
- * @param {Node} node - The node to check for within this component's child nodes.
733
- * @return {boolean} Returns true if the given node is found, otherwise false.
734
- * @throws {TypeError} value is not an instance of
735
- * @since 1.19.0
736
- */
737
- hasNode(node) {
738
- if (containChildNode.call(this, validateInstance(node, Node))) {
739
- return true;
740
- }
741
-
742
- if (!(this.shadowRoot instanceof ShadowRoot)) {
743
- return false;
744
- }
745
-
746
- return containChildNode.call(this.shadowRoot, node);
747
- }
748
-
749
- /**
750
- * Invokes a callback function with the given name and arguments.
751
- *
752
- * @param {string} name - The name of the callback to be executed.
753
- * @param {Array} args - An array of arguments to be passed to the callback function.
754
- * @return {*} The result of the callback function execution.
755
- */
756
- callCallback(name, args) {
757
- return callControlCallback.call(this, name, ...args);
758
- }
188
+ /**
189
+ * A new object is created. First, the `initOptions` method is called. Here the
190
+ * options can be defined in derived classes. Subsequently, the shadowRoot is initialized.
191
+ *
192
+ * IMPORTANT: CustomControls instances are not created via the constructor, but either via a tag in the HTML or via <code>document.createElement()</code>.
193
+ *
194
+ * @throws {Error} the option attribute does not contain a valid JSON definition.
195
+ */
196
+ constructor() {
197
+ super();
198
+
199
+ this[attributeObserverSymbol] = {};
200
+
201
+ const options = initOptionsFromAttributes(this, extend({}, this.defaults));
202
+ if (!isObject(options)) {
203
+ throw new Error(
204
+ `The options are not defined correctly in the ${this.getTag()} element.`,
205
+ );
206
+ }
207
+
208
+ if (this.customization instanceof Map) {
209
+ const pathfinder = new Pathfinder(options);
210
+ this.customization.forEach((value, key) => {
211
+ pathfinder.setVia(key, value);
212
+ });
213
+ }
214
+
215
+ this[internalSymbol] = new ProxyObserver({ options });
216
+ this[initMethodSymbol]();
217
+ initOptionObserver.call(this);
218
+ this[scriptHostElementSymbol] = [];
219
+ }
220
+
221
+ /**
222
+ * This method is called by the `instanceof` operator.
223
+ *
224
+ * @return {symbol}
225
+ * @since 2.1.0
226
+ */
227
+ static get [instanceSymbol]() {
228
+ return Symbol.for("@schukai/monster/dom/custom-element@@instance");
229
+ }
230
+
231
+ /**
232
+ * This method determines which attributes are to be
233
+ * monitored by `attributeChangedCallback()`. Unfortunately, this method is static.
234
+ * Therefore, the `observedAttributes` property cannot be changed during runtime.
235
+ *
236
+ * @return {string[]}
237
+ * @since 1.15.0
238
+ */
239
+ static get observedAttributes() {
240
+ return [];
241
+ }
242
+
243
+ /**
244
+ *
245
+ * @param attribute
246
+ * @param callback
247
+ * @return {CustomElement}
248
+ */
249
+ addAttributeObserver(attribute, callback) {
250
+ validateFunction(callback);
251
+ this[attributeObserverSymbol][attribute] = callback;
252
+ return this;
253
+ }
254
+
255
+ /**
256
+ *
257
+ * @param attribute
258
+ * @return {CustomElement}
259
+ */
260
+ removeAttributeObserver(attribute) {
261
+ delete this[attributeObserverSymbol][attribute];
262
+ return this;
263
+ }
264
+
265
+ /**
266
+ * The `customization` property allows overwriting the defaults.
267
+ * Unlike the defaults that expect an object, the customization is a Map.
268
+ * This also allows overwriting individual values in a deeper structure
269
+ * without having to redefine the entire structure and thus changing the defaults.
270
+ * @returns {Map}
271
+ */
272
+ get customization() {
273
+ return new Map();
274
+ }
275
+
276
+ /**
277
+ * The `defaults` property defines the default values for a control. If you want to override these,
278
+ * you can use various methods, which are described in the documentation available at
279
+ * {@link https://monsterjs.orgendocconfigurate-a-monster-control}.
280
+ *
281
+ * The individual configuration values are listed below:
282
+ *
283
+ * More information about the shadowRoot can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow),
284
+ * in the [HTML Standard](https://html.spec.whatwg.org/multipage/custom-elements.html#custom-elements) or in the [WHATWG Wiki](https://wiki.whatwg.org/wiki/Custom_Elements).
285
+ *
286
+ * More information about the template element can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template).
287
+ *
288
+ * More information about the slot element can be found in the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot).
289
+ *
290
+ * @property {boolean} disabled=false Specifies whether the control is disabled. When present, it makes the element non-mutable, non-focusable, and non-submittable with the form.
291
+ * @property {string} shadowMode=open Specifies the mode of the shadow root. When set to `open`, elements in the shadow root are accessible from JavaScript outside the root, while setting it to `closed` denies access to the root's nodes from JavaScript outside it.
292
+ * @property {Boolean} delegatesFocus=true Specifies the behavior of the control with respect to focusability. When set to `true`, it mitigates custom element issues around focusability. When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling.
293
+ * @property {Object} templates Specifies the templates used by the control.
294
+ * @property {string} templates.main=undefined Specifies the main template used by the control.
295
+ * @property {Object} templateMapping Specifies the mapping of templates.
296
+ * @property {Object} templateFormatter Specifies the formatter for the templates.
297
+ * @property {Object} templateFormatter.marker Specifies the marker for the templates.
298
+ * @property {Function} templateFormatter.marker.open=null Specifies the opening marker for the templates.
299
+ * @property {Function} templateFormatter.marker.close=null Specifies the closing marker for the templates.
300
+ * @property {Boolean} templateFormatter.i18n=false Specifies whether the templates should be formatted with i18n.
301
+ * @property {Boolean} eventProcessing=false Specifies whether the control processes events.
302
+ * @since 1.8.0
303
+ */
304
+ get defaults() {
305
+ return {
306
+ disabled: false,
307
+ shadowMode: "open",
308
+ delegatesFocus: true,
309
+ templates: {
310
+ main: undefined,
311
+ },
312
+ templateMapping: {},
313
+ templateFormatter: {
314
+ marker: {
315
+ open: null,
316
+ close: null,
317
+ },
318
+ i18n: false,
319
+ },
320
+
321
+ eventProcessing: false,
322
+ };
323
+ }
324
+
325
+ /**
326
+ * This method updates the labels of the element.
327
+ * The labels are defined in the option object.
328
+ * The key of the label is used to retrieve the translation from the document.
329
+ * If the translation is different from the label, the label is updated.
330
+ *
331
+ * Before you can use this method, you must have loaded the translations.
332
+ *
333
+ * @return {CustomElement}
334
+ * @throws {Error} Cannot find an element with translations. Add a translation object to the document.
335
+ */
336
+ updateI18n() {
337
+ let translations;
338
+
339
+ try {
340
+ translations = getDocumentTranslations();
341
+ } catch (e) {
342
+ addErrorAttribute(this, e);
343
+ return this;
344
+ }
345
+
346
+ if (!translations) {
347
+ return this;
348
+ }
349
+
350
+ const labels = this.getOption("labels");
351
+ if (!(isObject(labels) || isIterable(labels))) {
352
+ return this;
353
+ }
354
+
355
+ for (const key in labels) {
356
+ const def = labels[key];
357
+
358
+ if (isString(def)) {
359
+ const text = translations.getText(key, def);
360
+ if (text !== def) {
361
+ this.setOption(`labels.${key}`, text);
362
+ }
363
+ continue;
364
+ } else if (isObject(def)) {
365
+ for (const k in def) {
366
+ const d = def[k];
367
+
368
+ const text = translations.getPluralRuleText(key, k, d);
369
+ if (!isString(text)) {
370
+ throw new Error("Invalid labels definition");
371
+ }
372
+ if (text !== d) {
373
+ this.setOption(`labels.${key}.${k}`, text);
374
+ }
375
+ }
376
+ continue;
377
+ }
378
+
379
+ throw new Error("Invalid labels definition");
380
+ }
381
+ return this;
382
+ }
383
+
384
+ /**
385
+ * The `getTag()` method returns the tag name associated with the custom element. This method should be overwritten
386
+ * by the derived class.
387
+ *
388
+ * Note that there is no check on the name of the tag in this class. It is the responsibility of
389
+ * the developer to assign an appropriate tag name. If the name is not valid, the
390
+ * `registerCustomElement()` method will issue an error.
391
+ *
392
+ * @see https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
393
+ * @throws {Error} This method must be overridden by the derived class.
394
+ * @return {string} The tag name associated with the custom element.
395
+ * @since 1.7.0
396
+ */
397
+ static getTag() {
398
+ throw new Error(
399
+ "The method `getTag()` must be overridden by the derived class.",
400
+ );
401
+ }
402
+
403
+ /**
404
+ * The `getCSSStyleSheet()` method returns a `CSSStyleSheet` object that defines the styles for the custom element.
405
+ * If the environment does not support the `CSSStyleSheet` constructor, then an object can be built using the provided detour.
406
+ *
407
+ * If `undefined` is returned, then the shadow root does not receive a stylesheet.
408
+ *
409
+ * Example usage:
410
+ *
411
+ * ```js
412
+ * class MyElement extends CustomElement {
413
+ * static getCSSStyleSheet() {
414
+ * const sheet = new CSSStyleSheet();
415
+ * sheet.replaceSync("p { color: red; }");
416
+ * return sheet;
417
+ * }
418
+ * }
419
+ * ```
420
+ *
421
+ * If the environment does not support the `CSSStyleSheet` constructor,
422
+ * you can use the following workaround to create the stylesheet:
423
+ *
424
+ * ```js
425
+ * const doc = document.implementation.createHTMLDocument('title');
426
+ * let style = doc.createElement("style");
427
+ * style.innerHTML = "p { color: red; }";
428
+ * style.appendChild(document.createTextNode(""));
429
+ * doc.head.appendChild(style);
430
+ * return doc.styleSheets[0];
431
+ * ```
432
+ *
433
+ * @return {CSSStyleSheet|CSSStyleSheet[]|string|undefined} A `CSSStyleSheet` object or an array of such objects that define the styles for the custom element, or `undefined` if no stylesheet should be applied.
434
+ */
435
+ static getCSSStyleSheet() {
436
+ return undefined;
437
+ }
438
+
439
+ /**
440
+ * attach a new observer
441
+ *
442
+ * @param {Observer} observer
443
+ * @return {CustomElement}
444
+ */
445
+ attachObserver(observer) {
446
+ this[internalSymbol].attachObserver(observer);
447
+ return this;
448
+ }
449
+
450
+ /**
451
+ * detach a observer
452
+ *
453
+ * @param {Observer} observer
454
+ * @return {CustomElement}
455
+ */
456
+ detachObserver(observer) {
457
+ this[internalSymbol].detachObserver(observer);
458
+ return this;
459
+ }
460
+
461
+ /**
462
+ * @param {Observer} observer
463
+ * @return {ProxyObserver}
464
+ */
465
+ containsObserver(observer) {
466
+ return this[internalSymbol].containsObserver(observer);
467
+ }
468
+
469
+ /**
470
+ * nested options can be specified by path `a.b.c`
471
+ *
472
+ * @param {string} path
473
+ * @param {*} defaultValue
474
+ * @return {*}
475
+ * @since 1.10.0
476
+ */
477
+ getOption(path, defaultValue = undefined) {
478
+ let value;
479
+
480
+ try {
481
+ value = new Pathfinder(
482
+ this[internalSymbol].getRealSubject()["options"],
483
+ ).getVia(path);
484
+ } catch (e) {}
485
+
486
+ if (value === undefined) return defaultValue;
487
+ return value;
488
+ }
489
+
490
+ /**
491
+ * Set option and inform elements
492
+ *
493
+ * @param {string} path
494
+ * @param {*} value
495
+ * @return {CustomElement}
496
+ * @since 1.14.0
497
+ */
498
+ setOption(path, value) {
499
+ new Pathfinder(this[internalSymbol].getSubject()["options"]).setVia(
500
+ path,
501
+ value,
502
+ );
503
+ return this;
504
+ }
505
+
506
+ /**
507
+ * @since 1.15.0
508
+ * @param {string|object} options
509
+ * @return {CustomElement}
510
+ */
511
+ setOptions(options) {
512
+ if (isString(options)) {
513
+ options = parseOptionsJSON.call(this, options);
514
+ }
515
+ // 2024-01-21: remove this.defaults, otherwise it will overwrite
516
+ // the current settings that have already been made.
517
+ // https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/136
518
+ extend(this[internalSymbol].getSubject()["options"], options);
519
+
520
+ return this;
521
+ }
522
+
523
+ /**
524
+ * Is called once via the constructor
525
+ *
526
+ * @return {CustomElement}
527
+ * @since 1.8.0
528
+ */
529
+ [initMethodSymbol]() {
530
+ return this;
531
+ }
532
+
533
+ /**
534
+ * This method is called once when the object is equipped with update for the dynamic change of the dom.
535
+ * The functions returned here can be used as pipe functions in the template.
536
+ *
537
+ * In the example, the function `my-transformer` is defined. In the template, you can use it as follows:
538
+ *
539
+ * ```html
540
+ * <my-element
541
+ * data-monster-option-transformer="path:my-value | call:my-transformer">
542
+ * </my-element>
543
+ * ```
544
+ *
545
+ * The function `my-transformer` is called with the value of `my-value` as a parameter.
546
+ *
547
+ * ```js
548
+ * class MyElement extends CustomElement {
549
+ * [updaterTransformerMethodsSymbol]() {
550
+ * return {
551
+ * "my-transformer": (value) => {
552
+ * switch (typeof Wert) {
553
+ * case "string":
554
+ * return value + "!";
555
+ * case "Zahl":
556
+ * return value + 1;
557
+ * default:
558
+ * return value;
559
+ * }
560
+ * }
561
+ * };
562
+ * };
563
+ * }
564
+ * ```
565
+ *
566
+ * @return {object}
567
+ * @since 2.43.0
568
+ */
569
+ [updaterTransformerMethodsSymbol]() {
570
+ return {};
571
+ }
572
+
573
+ /**
574
+ * This method is called once when the object is included in the DOM for the first time. It performs the following actions:
575
+ *
576
+ * <ol>
577
+ * <li>Extracts the options from the attributes and the script tag of the element and sets them.</li>
578
+ * <li>Initializes the shadow root and its CSS stylesheet (if specified).</li>
579
+ * <li>Initializes the HTML content of the element.</li>
580
+ * <li>Initializes the custom elements inside the shadow root and the slotted elements.</li>
581
+ * <li>Attaches a mutation observer to observe changes to the attributes of the element.</li>
582
+ *
583
+ * @return {CustomElement} - The updated custom element.
584
+ * @since 1.8.0
585
+ */
586
+ [assembleMethodSymbol]() {
587
+ let elements;
588
+ let nodeList;
589
+ // Extract options from attributes and set them
590
+ const AttributeOptions = getOptionsFromAttributes.call(this);
591
+ if (
592
+ isObject(AttributeOptions) &&
593
+ Object.keys(AttributeOptions).length > 0
594
+ ) {
595
+ this.setOptions(AttributeOptions);
596
+ }
597
+ // Extract options from script tag and set them
598
+ const ScriptOptions = getOptionsFromScriptTag.call(this);
599
+ if (isObject(ScriptOptions) && Object.keys(ScriptOptions).length > 0) {
600
+ this.setOptions(ScriptOptions);
601
+ }
602
+ // Initialize the shadow root and its CSS stylesheet
603
+ if (this.getOption("shadowMode", false) !== false) {
604
+ try {
605
+ initShadowRoot.call(this);
606
+ elements = this.shadowRoot.childNodes;
607
+ } catch (e) {
608
+ addErrorAttribute(this, e);
609
+ }
610
+ try {
611
+ initCSSStylesheet.call(this);
612
+ } catch (e) {
613
+ addErrorAttribute(this, e);
614
+ }
615
+ }
616
+ // If the elements are not found inside the shadow root, initialize the HTML content of the element
617
+ if (!(elements instanceof NodeList)) {
618
+ initHtmlContent.call(this);
619
+ elements = this.childNodes;
620
+ }
621
+ // Initialize the custom elements inside the shadow root and the slotted elements
622
+ initFromCallbackHost.call(this);
623
+ try {
624
+ nodeList = new Set([...elements, ...getSlottedElements.call(this)]);
625
+ } catch (e) {
626
+ nodeList = elements;
627
+ }
628
+ try {
629
+ this[updateCloneDataSymbol] = clone(
630
+ this[internalSymbol].getRealSubject()["options"],
631
+ );
632
+ } catch (e) {
633
+ addErrorAttribute(this, e);
634
+ }
635
+ const cfg = {};
636
+ if (this.getOption("eventProcessing") === true) {
637
+ cfg.eventProcessing = true;
638
+ }
639
+ addObjectWithUpdaterToElement.call(
640
+ this,
641
+ nodeList,
642
+ customElementUpdaterLinkSymbol,
643
+ this[updateCloneDataSymbol],
644
+ cfg,
645
+ );
646
+ // Attach a mutation observer to observe changes to the attributes of the element
647
+ attachAttributeChangeMutationObserver.call(this);
648
+
649
+ if (isFunction(this[internalSymbol]?.syncDisabledState)) {
650
+ this[internalSymbol].syncDisabledState();
651
+ }
652
+
653
+ return this;
654
+ }
655
+
656
+ /**
657
+ * You know what you are doing? This function is only for advanced users.
658
+ * The result is a clone of the internal data.
659
+ *
660
+ * @return {*}
661
+ */
662
+ getInternalUpdateCloneData() {
663
+ return clone(this[updateCloneDataSymbol]);
664
+ }
665
+
666
+ /**
667
+ * This method is called every time the element is inserted into the DOM. It checks if the custom element
668
+ * has already been initialized and if not, calls the assembleMethod to initialize it.
669
+ *
670
+ * @return {void}
671
+ * @since 1.7.0
672
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/connectedCallback
673
+ */
674
+ connectedCallback() {
675
+ // Check if the object has already been initialized
676
+ if (!hasObjectLink(this, customElementUpdaterLinkSymbol)) {
677
+ // If not, call the assembleMethod to initialize the object
678
+ this[assembleMethodSymbol]();
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Called every time the element is removed from the DOM. Useful for running clean up code.
684
+ *
685
+ * @return {void}
686
+ * @since 1.7.0
687
+ */
688
+ disconnectedCallback() {}
689
+
690
+ /**
691
+ * The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)).
692
+ *
693
+ * @return {void}
694
+ * @since 1.7.0
695
+ */
696
+ adoptedCallback() {}
697
+
698
+ /**
699
+ * Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial
700
+ * values when an element is created by the parser, or upgraded. Note: only attributes listed in the observedAttributes
701
+ * property will receive this callback.
702
+ *
703
+ * @param {string} attrName
704
+ * @param {string} oldVal
705
+ * @param {string} newVal
706
+ * @return {void}
707
+ * @since 1.15.0
708
+ */
709
+ attributeChangedCallback(attrName, oldVal, newVal) {
710
+ if (attrName.startsWith("data-monster-option-")) {
711
+ setOptionFromAttribute(
712
+ this,
713
+ attrName,
714
+ this[internalSymbol].getSubject()["options"],
715
+ );
716
+ }
717
+
718
+ const callback = this[attributeObserverSymbol]?.[attrName];
719
+ if (isFunction(callback)) {
720
+ try {
721
+ callback.call(this, newVal, oldVal);
722
+ } catch (e) {
723
+ addErrorAttribute(this, e);
724
+ }
725
+ }
726
+ }
727
+
728
+ /**
729
+ * Checks if the provided node is part of this component's child nodes,
730
+ * including those within the shadow root, if present.
731
+ *
732
+ * @param {Node} node - The node to check for within this component's child nodes.
733
+ * @return {boolean} Returns true if the given node is found, otherwise false.
734
+ * @throws {TypeError} value is not an instance of
735
+ * @since 1.19.0
736
+ */
737
+ hasNode(node) {
738
+ if (containChildNode.call(this, validateInstance(node, Node))) {
739
+ return true;
740
+ }
741
+
742
+ if (!(this.shadowRoot instanceof ShadowRoot)) {
743
+ return false;
744
+ }
745
+
746
+ return containChildNode.call(this.shadowRoot, node);
747
+ }
748
+
749
+ /**
750
+ * Invokes a callback function with the given name and arguments.
751
+ *
752
+ * @param {string} name - The name of the callback to be executed.
753
+ * @param {Array} args - An array of arguments to be passed to the callback function.
754
+ * @return {*} The result of the callback function execution.
755
+ */
756
+ callCallback(name, args) {
757
+ return callControlCallback.call(this, name, ...args);
758
+ }
759
759
  }
760
760
 
761
761
  /**
@@ -764,46 +764,46 @@ class CustomElement extends HTMLElement {
764
764
  * @return {any}
765
765
  */
766
766
  function callControlCallback(callBackFunctionName, ...args) {
767
- if (!isString(callBackFunctionName) || callBackFunctionName === "") {
768
- return;
769
- }
770
-
771
- if (callBackFunctionName in this) {
772
- return this[callBackFunctionName](this, ...args);
773
- }
774
-
775
- if (!this.hasAttribute(ATTRIBUTE_SCRIPT_HOST)) {
776
- return;
777
- }
778
-
779
- if (this[scriptHostElementSymbol].length === 0) {
780
- const targetId = this.getAttribute(ATTRIBUTE_SCRIPT_HOST);
781
- if (!targetId) {
782
- return;
783
- }
784
-
785
- const list = targetId.split(",");
786
- for (const id of list) {
787
- const host = findElementWithIdUpwards(this, targetId);
788
- if (!(host instanceof HTMLElement)) {
789
- continue;
790
- }
791
-
792
- this[scriptHostElementSymbol].push(host);
793
- }
794
- }
795
-
796
- for (const host of this[scriptHostElementSymbol]) {
797
- if (callBackFunctionName in host) {
798
- try {
799
- return host[callBackFunctionName](this, ...args);
800
- } catch (e) {
801
- addErrorAttribute(this, e);
802
- }
803
- }
804
- }
805
-
806
- addErrorAttribute(this, `callback ${callBackFunctionName} not found`);
767
+ if (!isString(callBackFunctionName) || callBackFunctionName === "") {
768
+ return;
769
+ }
770
+
771
+ if (callBackFunctionName in this) {
772
+ return this[callBackFunctionName](this, ...args);
773
+ }
774
+
775
+ if (!this.hasAttribute(ATTRIBUTE_SCRIPT_HOST)) {
776
+ return;
777
+ }
778
+
779
+ if (this[scriptHostElementSymbol].length === 0) {
780
+ const targetId = this.getAttribute(ATTRIBUTE_SCRIPT_HOST);
781
+ if (!targetId) {
782
+ return;
783
+ }
784
+
785
+ const list = targetId.split(",");
786
+ for (const id of list) {
787
+ const host = findElementWithIdUpwards(this, targetId);
788
+ if (!(host instanceof HTMLElement)) {
789
+ continue;
790
+ }
791
+
792
+ this[scriptHostElementSymbol].push(host);
793
+ }
794
+ }
795
+
796
+ for (const host of this[scriptHostElementSymbol]) {
797
+ if (callBackFunctionName in host) {
798
+ try {
799
+ return host[callBackFunctionName](this, ...args);
800
+ } catch (e) {
801
+ addErrorAttribute(this, e);
802
+ }
803
+ }
804
+ }
805
+
806
+ addErrorAttribute(this, `callback ${callBackFunctionName} not found`);
807
807
  }
808
808
 
809
809
  /**
@@ -820,16 +820,16 @@ function callControlCallback(callBackFunctionName, ...args) {
820
820
  * @since 1.8.0
821
821
  */
822
822
  function initFromCallbackHost() {
823
- // Set the default callback function name
824
- let callBackFunctionName = initControlCallbackName;
823
+ // Set the default callback function name
824
+ let callBackFunctionName = initControlCallbackName;
825
825
 
826
- // If the `data-monster-option-callback` attribute is set, use its value as the callback function name
827
- if (this.hasAttribute(ATTRIBUTE_INIT_CALLBACK)) {
828
- callBackFunctionName = this.getAttribute(ATTRIBUTE_INIT_CALLBACK);
829
- }
826
+ // If the `data-monster-option-callback` attribute is set, use its value as the callback function name
827
+ if (this.hasAttribute(ATTRIBUTE_INIT_CALLBACK)) {
828
+ callBackFunctionName = this.getAttribute(ATTRIBUTE_INIT_CALLBACK);
829
+ }
830
830
 
831
- // Call the callback function with the element as a parameter if it exists
832
- callControlCallback.call(this, callBackFunctionName);
831
+ // Call the callback function with the element as a parameter if it exists
832
+ callControlCallback.call(this, callBackFunctionName);
833
833
  }
834
834
 
835
835
  /**
@@ -839,35 +839,34 @@ function initFromCallbackHost() {
839
839
  * @this CustomElement
840
840
  */
841
841
  function attachAttributeChangeMutationObserver() {
842
- const self = this;
843
-
844
- if (typeof self[attributeMutationObserverSymbol] !== "undefined") {
845
- return;
846
- }
847
-
848
- self[attributeMutationObserverSymbol] = new MutationObserver(function (
849
- mutations,
850
- observer,
851
- ) {
852
- for (const mutation of mutations) {
853
- if (mutation.type === "attributes") {
854
- self.attributeChangedCallback(
855
- mutation.attributeName,
856
- mutation.oldValue,
857
- mutation.target.getAttribute(mutation.attributeName),
858
- );
859
- }
860
- }
861
- });
862
-
863
- try {
864
- self[attributeMutationObserverSymbol].observe(self, {
865
- attributes: true,
866
- attributeOldValue: true,
867
- });
868
- } catch (e) {
869
- addErrorAttribute(self, e);
870
- }
842
+ const self = this;
843
+
844
+ if (typeof self[attributeMutationObserverSymbol] !== "undefined") {
845
+ return;
846
+ }
847
+
848
+ self[attributeMutationObserverSymbol] = new MutationObserver(
849
+ function (mutations, observer) {
850
+ for (const mutation of mutations) {
851
+ if (mutation.type === "attributes") {
852
+ self.attributeChangedCallback(
853
+ mutation.attributeName,
854
+ mutation.oldValue,
855
+ mutation.target.getAttribute(mutation.attributeName),
856
+ );
857
+ }
858
+ }
859
+ },
860
+ );
861
+
862
+ try {
863
+ self[attributeMutationObserverSymbol].observe(self, {
864
+ attributes: true,
865
+ attributeOldValue: true,
866
+ });
867
+ } catch (e) {
868
+ addErrorAttribute(self, e);
869
+ }
871
870
  }
872
871
 
873
872
  /**
@@ -877,22 +876,21 @@ function attachAttributeChangeMutationObserver() {
877
876
  * @return {boolean}
878
877
  */
879
878
  function containChildNode(node) {
880
- if (this.contains(node)) {
881
- return true;
882
- }
879
+ if (this.contains(node)) {
880
+ return true;
881
+ }
883
882
 
884
- for (const [, e] of Object.entries(this.childNodes)) {
885
- if (e.contains(node)) {
886
- return true;
887
- }
883
+ for (const [, e] of Object.entries(this.childNodes)) {
884
+ if (e.contains(node)) {
885
+ return true;
886
+ }
888
887
 
889
- containChildNode.call(e, node);
890
- }
888
+ containChildNode.call(e, node);
889
+ }
891
890
 
892
- return false;
891
+ return false;
893
892
  }
894
893
 
895
-
896
894
  /**
897
895
  * @license AGPLv3
898
896
  * @since 4.43.0
@@ -900,95 +898,93 @@ function containChildNode(node) {
900
898
  * @this CustomElement
901
899
  */
902
900
  function initOptionObserver() {
903
- const self = this;
904
-
905
- self[internalSymbol].lastDisabledValue = undefined;
906
-
907
- const syncDisabledState = () => {
908
- const flag = self.getOption("disabled", false);
909
-
910
- if (flag === self[internalSymbol].lastDisabledValue) {
911
- return;
912
- }
913
-
914
- if (!(self.shadowRoot instanceof ShadowRoot) && !self.childNodes.length) {
915
- return;
916
- }
917
-
918
- self[internalSymbol].lastDisabledValue = flag;
919
-
920
- const query =
921
- "button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]";
922
-
923
- let elements = [];
924
- if (self.shadowRoot instanceof ShadowRoot) {
925
- elements = self.shadowRoot.querySelectorAll(query);
926
- }
927
-
928
- let nodeList;
929
- try {
930
- const baseElements =
931
- elements.length > 0 ? elements : self.querySelectorAll(query);
932
- nodeList = new Set([
933
- ...baseElements,
934
- ...getSlottedElements.call(self, query),
935
- ]);
936
- } catch (e) {
937
- nodeList = elements;
938
- }
939
-
940
- for (const element of [...nodeList]) {
941
- if (flag === true) {
942
- element.setAttribute(ATTRIBUTE_DISABLED, "");
943
- } else {
944
- element.removeAttribute(ATTRIBUTE_DISABLED);
945
- }
946
- }
947
- };
948
-
949
- self.attachObserver(
950
- new Observer(syncDisabledState),
951
- );
952
-
953
- self[internalSymbol].syncDisabledState = syncDisabledState;
954
-
955
- self.attachObserver(
956
- new Observer(function () {
957
- if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) {
958
- return;
959
- }
960
- const updaters = getLinkedObjects(self, customElementUpdaterLinkSymbol);
961
-
962
- for (const list of updaters) {
963
- for (const updater of list) {
964
- const d = clone(self[internalSymbol].getRealSubject()["options"]);
965
- Object.assign(updater.getSubject(), d);
966
- }
967
- }
968
- }),
969
- );
970
-
971
- self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => {
972
- if (self.hasAttribute(ATTRIBUTE_DISABLED)) {
973
- self.setOption(ATTRIBUTE_DISABLED, true);
974
- } else {
975
- self.setOption(ATTRIBUTE_DISABLED, false);
976
- }
977
- };
978
-
979
- self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => {
980
- const options = getOptionsFromAttributes.call(self);
981
- if (isObject(options) && Object.keys(options).length > 0) {
982
- self.setOptions(options);
983
- }
984
- };
985
-
986
- self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => {
987
- const options = getOptionsFromScriptTag.call(self);
988
- if (isObject(options) && Object.keys(options).length > 0) {
989
- self.setOptions(options);
990
- }
991
- };
901
+ const self = this;
902
+
903
+ self[internalSymbol].lastDisabledValue = undefined;
904
+
905
+ const syncDisabledState = () => {
906
+ const flag = self.getOption("disabled", false);
907
+
908
+ if (flag === self[internalSymbol].lastDisabledValue) {
909
+ return;
910
+ }
911
+
912
+ if (!(self.shadowRoot instanceof ShadowRoot) && !self.childNodes.length) {
913
+ return;
914
+ }
915
+
916
+ self[internalSymbol].lastDisabledValue = flag;
917
+
918
+ const query =
919
+ "button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]";
920
+
921
+ let elements = [];
922
+ if (self.shadowRoot instanceof ShadowRoot) {
923
+ elements = self.shadowRoot.querySelectorAll(query);
924
+ }
925
+
926
+ let nodeList;
927
+ try {
928
+ const baseElements =
929
+ elements.length > 0 ? elements : self.querySelectorAll(query);
930
+ nodeList = new Set([
931
+ ...baseElements,
932
+ ...getSlottedElements.call(self, query),
933
+ ]);
934
+ } catch (e) {
935
+ nodeList = elements;
936
+ }
937
+
938
+ for (const element of [...nodeList]) {
939
+ if (flag === true) {
940
+ element.setAttribute(ATTRIBUTE_DISABLED, "");
941
+ } else {
942
+ element.removeAttribute(ATTRIBUTE_DISABLED);
943
+ }
944
+ }
945
+ };
946
+
947
+ self.attachObserver(new Observer(syncDisabledState));
948
+
949
+ self[internalSymbol].syncDisabledState = syncDisabledState;
950
+
951
+ self.attachObserver(
952
+ new Observer(function () {
953
+ if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) {
954
+ return;
955
+ }
956
+ const updaters = getLinkedObjects(self, customElementUpdaterLinkSymbol);
957
+
958
+ for (const list of updaters) {
959
+ for (const updater of list) {
960
+ const d = clone(self[internalSymbol].getRealSubject()["options"]);
961
+ Object.assign(updater.getSubject(), d);
962
+ }
963
+ }
964
+ }),
965
+ );
966
+
967
+ self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => {
968
+ if (self.hasAttribute(ATTRIBUTE_DISABLED)) {
969
+ self.setOption(ATTRIBUTE_DISABLED, true);
970
+ } else {
971
+ self.setOption(ATTRIBUTE_DISABLED, false);
972
+ }
973
+ };
974
+
975
+ self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => {
976
+ const options = getOptionsFromAttributes.call(self);
977
+ if (isObject(options) && Object.keys(options).length > 0) {
978
+ self.setOptions(options);
979
+ }
980
+ };
981
+
982
+ self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => {
983
+ const options = getOptionsFromScriptTag.call(self);
984
+ if (isObject(options) && Object.keys(options).length > 0) {
985
+ self.setOptions(options);
986
+ }
987
+ };
992
988
  }
993
989
 
994
990
  /**
@@ -997,35 +993,35 @@ function initOptionObserver() {
997
993
  * @throws {TypeError} value is not an object
998
994
  */
999
995
  function getOptionsFromScriptTag() {
1000
- if (!this.hasAttribute(ATTRIBUTE_OPTIONS_SELECTOR)) {
1001
- return {};
1002
- }
1003
-
1004
- const node = document.querySelector(
1005
- this.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR),
1006
- );
1007
- if (!(node instanceof HTMLScriptElement)) {
1008
- addErrorAttribute(
1009
- this,
1010
- `the selector ${ATTRIBUTE_OPTIONS_SELECTOR} for options was specified (${this.getAttribute(
1011
- ATTRIBUTE_OPTIONS_SELECTOR,
1012
- )}) but not found.`,
1013
- );
1014
- return {};
1015
- }
1016
-
1017
- let obj = {};
1018
-
1019
- try {
1020
- obj = parseOptionsJSON.call(this, node.textContent.trim());
1021
- } catch (e) {
1022
- addErrorAttribute(
1023
- this,
1024
- `when analyzing the configuration from the script tag there was an error. ${e}`,
1025
- );
1026
- }
1027
-
1028
- return obj;
996
+ if (!this.hasAttribute(ATTRIBUTE_OPTIONS_SELECTOR)) {
997
+ return {};
998
+ }
999
+
1000
+ const node = document.querySelector(
1001
+ this.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR),
1002
+ );
1003
+ if (!(node instanceof HTMLScriptElement)) {
1004
+ addErrorAttribute(
1005
+ this,
1006
+ `the selector ${ATTRIBUTE_OPTIONS_SELECTOR} for options was specified (${this.getAttribute(
1007
+ ATTRIBUTE_OPTIONS_SELECTOR,
1008
+ )}) but not found.`,
1009
+ );
1010
+ return {};
1011
+ }
1012
+
1013
+ let obj = {};
1014
+
1015
+ try {
1016
+ obj = parseOptionsJSON.call(this, node.textContent.trim());
1017
+ } catch (e) {
1018
+ addErrorAttribute(
1019
+ this,
1020
+ `when analyzing the configuration from the script tag there was an error. ${e}`,
1021
+ );
1022
+ }
1023
+
1024
+ return obj;
1029
1025
  }
1030
1026
 
1031
1027
  /**
@@ -1033,29 +1029,29 @@ function getOptionsFromScriptTag() {
1033
1029
  * @return {object}
1034
1030
  */
1035
1031
  function getOptionsFromAttributes() {
1036
- if (
1037
- this.hasAttribute(ATTRIBUTE_DISABLED) &&
1038
- this.getAttribute(ATTRIBUTE_DISABLED) !== null
1039
- ) {
1040
- this.setOption(ATTRIBUTE_DISABLED, true);
1041
- } else {
1042
- this.setOption(ATTRIBUTE_DISABLED, undefined);
1043
- }
1044
-
1045
- if (this.hasAttribute(ATTRIBUTE_OPTIONS)) {
1046
- try {
1047
- return parseOptionsJSON.call(this, this.getAttribute(ATTRIBUTE_OPTIONS));
1048
- } catch (e) {
1049
- addErrorAttribute(
1050
- this,
1051
- `the options attribute ${ATTRIBUTE_OPTIONS} does not contain a valid json definition (actual: ${this.getAttribute(
1052
- ATTRIBUTE_OPTIONS,
1053
- )}).${e}`,
1054
- );
1055
- }
1056
- }
1057
-
1058
- return {};
1032
+ if (
1033
+ this.hasAttribute(ATTRIBUTE_DISABLED) &&
1034
+ this.getAttribute(ATTRIBUTE_DISABLED) !== null
1035
+ ) {
1036
+ this.setOption(ATTRIBUTE_DISABLED, true);
1037
+ } else {
1038
+ this.setOption(ATTRIBUTE_DISABLED, undefined);
1039
+ }
1040
+
1041
+ if (this.hasAttribute(ATTRIBUTE_OPTIONS)) {
1042
+ try {
1043
+ return parseOptionsJSON.call(this, this.getAttribute(ATTRIBUTE_OPTIONS));
1044
+ } catch (e) {
1045
+ addErrorAttribute(
1046
+ this,
1047
+ `the options attribute ${ATTRIBUTE_OPTIONS} does not contain a valid json definition (actual: ${this.getAttribute(
1048
+ ATTRIBUTE_OPTIONS,
1049
+ )}).${e}`,
1050
+ );
1051
+ }
1052
+ }
1053
+
1054
+ return {};
1059
1055
  }
1060
1056
 
1061
1057
  /**
@@ -1067,25 +1063,25 @@ function getOptionsFromAttributes() {
1067
1063
  * @throws {error} Throws an error if the JSON data is not valid.
1068
1064
  */
1069
1065
  function parseOptionsJSON(data) {
1070
- let obj = {};
1066
+ let obj = {};
1071
1067
 
1072
- if (!isString(data)) {
1073
- return obj;
1074
- }
1068
+ if (!isString(data)) {
1069
+ return obj;
1070
+ }
1075
1071
 
1076
- // the configuration can be specified as a data url.
1077
- try {
1078
- const dataUrl = parseDataURL(data);
1079
- data = dataUrl.content;
1080
- } catch (e) {}
1072
+ // the configuration can be specified as a data url.
1073
+ try {
1074
+ const dataUrl = parseDataURL(data);
1075
+ data = dataUrl.content;
1076
+ } catch (e) {}
1081
1077
 
1082
- try {
1083
- obj = JSON.parse(data);
1084
- } catch (e) {
1085
- throw e;
1086
- }
1078
+ try {
1079
+ obj = JSON.parse(data);
1080
+ } catch (e) {
1081
+ throw e;
1082
+ }
1087
1083
 
1088
- return validateObject(obj);
1084
+ return validateObject(obj);
1089
1085
  }
1090
1086
 
1091
1087
  /**
@@ -1094,18 +1090,18 @@ function parseOptionsJSON(data) {
1094
1090
  * @returns {*|string}
1095
1091
  */
1096
1092
  function substituteI18n(html) {
1097
- if (!this.getOption("templateFormatter.i18n", false)) {
1098
- return html;
1099
- }
1100
-
1101
- const labels = this.getOption("labels", {});
1102
- if (!(isObject(labels) || isIterable(labels))) {
1103
- return html;
1104
- }
1105
-
1106
- const formatter = new Formatter(labels, {});
1107
- formatter.setMarker("i18n{", "}");
1108
- return formatter.format(html);
1093
+ if (!this.getOption("templateFormatter.i18n", false)) {
1094
+ return html;
1095
+ }
1096
+
1097
+ const labels = this.getOption("labels", {});
1098
+ if (!(isObject(labels) || isIterable(labels))) {
1099
+ return html;
1100
+ }
1101
+
1102
+ const formatter = new Formatter(labels, {});
1103
+ formatter.setMarker("i18n{", "}");
1104
+ return formatter.format(html);
1109
1105
  }
1110
1106
 
1111
1107
  /**
@@ -1113,21 +1109,21 @@ function substituteI18n(html) {
1113
1109
  * @return {initHtmlContent}
1114
1110
  */
1115
1111
  function initHtmlContent() {
1116
- try {
1117
- const template = findDocumentTemplate(this.constructor.getTag());
1118
- this.appendChild(template.createDocumentFragment());
1119
- } catch (e) {
1120
- let html = this.getOption("templates.main", "");
1121
- if (isString(html) && html.length > 0) {
1122
- const mapping = this.getOption("templateMapping", {});
1123
- if (isObject(mapping)) {
1124
- html = new Formatter(mapping, {}).format(html);
1125
- }
1126
- this.innerHTML = substituteI18n.call(this, html);
1127
- }
1128
- }
1129
-
1130
- return this;
1112
+ try {
1113
+ const template = findDocumentTemplate(this.constructor.getTag());
1114
+ this.appendChild(template.createDocumentFragment());
1115
+ } catch (e) {
1116
+ let html = this.getOption("templates.main", "");
1117
+ if (isString(html) && html.length > 0) {
1118
+ const mapping = this.getOption("templateMapping", {});
1119
+ if (isObject(mapping)) {
1120
+ html = new Formatter(mapping, {}).format(html);
1121
+ }
1122
+ this.innerHTML = substituteI18n.call(this, html);
1123
+ }
1124
+ }
1125
+
1126
+ return this;
1131
1127
  }
1132
1128
 
1133
1129
  /**
@@ -1139,49 +1135,49 @@ function initHtmlContent() {
1139
1135
  * @throws {TypeError} value is not an instance of
1140
1136
  */
1141
1137
  function initCSSStylesheet() {
1142
- if (!(this.shadowRoot instanceof ShadowRoot)) {
1143
- return this;
1144
- }
1145
-
1146
- const styleSheet = this.constructor.getCSSStyleSheet();
1147
-
1148
- if (styleSheet instanceof CSSStyleSheet) {
1149
- if (styleSheet.cssRules.length > 0) {
1150
- this.shadowRoot.adoptedStyleSheets = [styleSheet];
1151
- }
1152
- } else if (isArray(styleSheet)) {
1153
- const assign = [];
1154
- for (const s of styleSheet) {
1155
- if (isString(s)) {
1156
- const trimedStyleSheet = s.trim();
1157
- if (trimedStyleSheet !== "") {
1158
- const style = document.createElement("style");
1159
- style.innerHTML = trimedStyleSheet;
1160
- this.shadowRoot.prepend(style);
1161
- }
1162
- continue;
1163
- }
1164
-
1165
- validateInstance(s, CSSStyleSheet);
1166
-
1167
- if (s.cssRules.length > 0) {
1168
- assign.push(s);
1169
- }
1170
- }
1171
-
1172
- if (assign.length > 0) {
1173
- this.shadowRoot.adoptedStyleSheets = assign;
1174
- }
1175
- } else if (isString(styleSheet)) {
1176
- const trimedStyleSheet = styleSheet.trim();
1177
- if (trimedStyleSheet !== "") {
1178
- const style = document.createElement("style");
1179
- style.innerHTML = styleSheet;
1180
- this.shadowRoot.prepend(style);
1181
- }
1182
- }
1183
-
1184
- return this;
1138
+ if (!(this.shadowRoot instanceof ShadowRoot)) {
1139
+ return this;
1140
+ }
1141
+
1142
+ const styleSheet = this.constructor.getCSSStyleSheet();
1143
+
1144
+ if (styleSheet instanceof CSSStyleSheet) {
1145
+ if (styleSheet.cssRules.length > 0) {
1146
+ this.shadowRoot.adoptedStyleSheets = [styleSheet];
1147
+ }
1148
+ } else if (isArray(styleSheet)) {
1149
+ const assign = [];
1150
+ for (const s of styleSheet) {
1151
+ if (isString(s)) {
1152
+ const trimedStyleSheet = s.trim();
1153
+ if (trimedStyleSheet !== "") {
1154
+ const style = document.createElement("style");
1155
+ style.innerHTML = trimedStyleSheet;
1156
+ this.shadowRoot.prepend(style);
1157
+ }
1158
+ continue;
1159
+ }
1160
+
1161
+ validateInstance(s, CSSStyleSheet);
1162
+
1163
+ if (s.cssRules.length > 0) {
1164
+ assign.push(s);
1165
+ }
1166
+ }
1167
+
1168
+ if (assign.length > 0) {
1169
+ this.shadowRoot.adoptedStyleSheets = assign;
1170
+ }
1171
+ } else if (isString(styleSheet)) {
1172
+ const trimedStyleSheet = styleSheet.trim();
1173
+ if (trimedStyleSheet !== "") {
1174
+ const style = document.createElement("style");
1175
+ style.innerHTML = styleSheet;
1176
+ this.shadowRoot.prepend(style);
1177
+ }
1178
+ }
1179
+
1180
+ return this;
1185
1181
  }
1186
1182
 
1187
1183
  /**
@@ -1193,42 +1189,42 @@ function initCSSStylesheet() {
1193
1189
  * @since 1.8.0
1194
1190
  */
1195
1191
  function initShadowRoot() {
1196
- let template;
1197
- let html;
1198
-
1199
- try {
1200
- template = findDocumentTemplate(this.constructor.getTag());
1201
- } catch (e) {
1202
- html = this.getOption("templates.main", "");
1203
- if (!isString(html) || html === undefined || html === "") {
1204
- throw new Error("html is not set.");
1205
- }
1206
- }
1207
-
1208
- this.attachShadow({
1209
- mode: this.getOption("shadowMode", "open"),
1210
- delegatesFocus: this.getOption("delegatesFocus", true),
1211
- });
1212
-
1213
- if (template instanceof Template) {
1214
- this.shadowRoot.appendChild(template.createDocumentFragment());
1215
- return this;
1216
- }
1217
-
1218
- const mapping = this.getOption("templateMapping", {});
1219
- if (isObject(mapping)) {
1220
- const formatter = new Formatter(mapping);
1221
- if (this.getOption("templateFormatter.marker.open") !== null) {
1222
- formatter.setMarker(
1223
- this.getOption("templateFormatter.marker.open"),
1224
- this.getOption("templateFormatter.marker.close"),
1225
- );
1226
- }
1227
- html = formatter.format(html);
1228
- }
1229
-
1230
- this.shadowRoot.innerHTML = substituteI18n.call(this, html);
1231
- return this;
1192
+ let template;
1193
+ let html;
1194
+
1195
+ try {
1196
+ template = findDocumentTemplate(this.constructor.getTag());
1197
+ } catch (e) {
1198
+ html = this.getOption("templates.main", "");
1199
+ if (!isString(html) || html === undefined || html === "") {
1200
+ throw new Error("html is not set.");
1201
+ }
1202
+ }
1203
+
1204
+ this.attachShadow({
1205
+ mode: this.getOption("shadowMode", "open"),
1206
+ delegatesFocus: this.getOption("delegatesFocus", true),
1207
+ });
1208
+
1209
+ if (template instanceof Template) {
1210
+ this.shadowRoot.appendChild(template.createDocumentFragment());
1211
+ return this;
1212
+ }
1213
+
1214
+ const mapping = this.getOption("templateMapping", {});
1215
+ if (isObject(mapping)) {
1216
+ const formatter = new Formatter(mapping);
1217
+ if (this.getOption("templateFormatter.marker.open") !== null) {
1218
+ formatter.setMarker(
1219
+ this.getOption("templateFormatter.marker.open"),
1220
+ this.getOption("templateFormatter.marker.close"),
1221
+ );
1222
+ }
1223
+ html = formatter.format(html);
1224
+ }
1225
+
1226
+ this.shadowRoot.innerHTML = substituteI18n.call(this, html);
1227
+ return this;
1232
1228
  }
1233
1229
 
1234
1230
  /**
@@ -1242,20 +1238,20 @@ function initShadowRoot() {
1242
1238
  * @throws {DOMException} Failed to execute 'define' on 'CustomElementRegistry': is not a valid custom element name
1243
1239
  */
1244
1240
  function registerCustomElement(element) {
1245
- validateFunction(element);
1246
- const customElements = getGlobalObject("customElements");
1247
- if (customElements === undefined) {
1248
- throw new Error("customElements is not supported.");
1249
- }
1250
-
1251
- const tag = element?.getTag();
1252
- if (!isString(tag) || tag === "") {
1253
- throw new Error("tag is not set.");
1254
- }
1255
-
1256
- if (customElements.get(tag) !== undefined) {
1257
- return;
1258
- }
1259
-
1260
- customElements.define(tag, element);
1241
+ validateFunction(element);
1242
+ const customElements = getGlobalObject("customElements");
1243
+ if (customElements === undefined) {
1244
+ throw new Error("customElements is not supported.");
1245
+ }
1246
+
1247
+ const tag = element?.getTag();
1248
+ if (!isString(tag) || tag === "") {
1249
+ throw new Error("tag is not set.");
1250
+ }
1251
+
1252
+ if (customElements.get(tag) !== undefined) {
1253
+ return;
1254
+ }
1255
+
1256
+ customElements.define(tag, element);
1261
1257
  }