@schukai/monster 4.42.2 → 4.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,583 +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
-
590
- // Extract options from attributes and set them
591
- const AttributeOptions = getOptionsFromAttributes.call(this);
592
- if (
593
- isObject(AttributeOptions) &&
594
- Object.keys(AttributeOptions).length > 0
595
- ) {
596
- this.setOptions(AttributeOptions);
597
- }
598
-
599
- // Extract options from script tag and set them
600
- const ScriptOptions = getOptionsFromScriptTag.call(this);
601
- if (isObject(ScriptOptions) && Object.keys(ScriptOptions).length > 0) {
602
- this.setOptions(ScriptOptions);
603
- }
604
-
605
- // Initialize the shadow root and its CSS stylesheet
606
- if (this.getOption("shadowMode", false) !== false) {
607
- try {
608
- initShadowRoot.call(this);
609
- elements = this.shadowRoot.childNodes;
610
- } catch (e) {
611
- addErrorAttribute(this, e);
612
- }
613
-
614
- try {
615
- initCSSStylesheet.call(this);
616
- } catch (e) {
617
- addErrorAttribute(this, e);
618
- }
619
- }
620
-
621
- // If the elements are not found inside the shadow root, initialize the HTML content of the element
622
- if (!(elements instanceof NodeList)) {
623
- initHtmlContent.call(this);
624
- elements = this.childNodes;
625
- }
626
-
627
- // Initialize the custom elements inside the shadow root and the slotted elements
628
- initFromCallbackHost.call(this);
629
- try {
630
- nodeList = new Set([...elements, ...getSlottedElements.call(this)]);
631
- } catch (e) {
632
- nodeList = elements;
633
- }
634
-
635
- try {
636
- this[updateCloneDataSymbol] = clone(
637
- this[internalSymbol].getRealSubject()["options"],
638
- );
639
- } catch (e) {
640
- addErrorAttribute(this, e);
641
- }
642
-
643
- const cfg = {};
644
- if (this.getOption("eventProcessing") === true) {
645
- cfg.eventProcessing = true;
646
- }
647
-
648
- addObjectWithUpdaterToElement.call(
649
- this,
650
- nodeList,
651
- customElementUpdaterLinkSymbol,
652
- this[updateCloneDataSymbol],
653
- cfg,
654
- );
655
-
656
- // Attach a mutation observer to observe changes to the attributes of the element
657
- attachAttributeChangeMutationObserver.call(this);
658
-
659
- return this;
660
- }
661
-
662
- /**
663
- * You know what you are doing? This function is only for advanced users.
664
- * The result is a clone of the internal data.
665
- *
666
- * @return {*}
667
- */
668
- getInternalUpdateCloneData() {
669
- return clone(this[updateCloneDataSymbol]);
670
- }
671
-
672
- /**
673
- * This method is called every time the element is inserted into the DOM. It checks if the custom element
674
- * has already been initialized and if not, calls the assembleMethod to initialize it.
675
- *
676
- * @return {void}
677
- * @since 1.7.0
678
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/connectedCallback
679
- */
680
- connectedCallback() {
681
- // Check if the object has already been initialized
682
- if (!hasObjectLink(this, customElementUpdaterLinkSymbol)) {
683
- // If not, call the assembleMethod to initialize the object
684
- this[assembleMethodSymbol]();
685
- }
686
- }
687
-
688
- /**
689
- * Called every time the element is removed from the DOM. Useful for running clean up code.
690
- *
691
- * @return {void}
692
- * @since 1.7.0
693
- */
694
- disconnectedCallback() {}
695
-
696
- /**
697
- * The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)).
698
- *
699
- * @return {void}
700
- * @since 1.7.0
701
- */
702
- adoptedCallback() {}
703
-
704
- /**
705
- * Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial
706
- * values when an element is created by the parser, or upgraded. Note: only attributes listed in the observedAttributes
707
- * property will receive this callback.
708
- *
709
- * @param {string} attrName
710
- * @param {string} oldVal
711
- * @param {string} newVal
712
- * @return {void}
713
- * @since 1.15.0
714
- */
715
- attributeChangedCallback(attrName, oldVal, newVal) {
716
- if (attrName.startsWith("data-monster-option-")) {
717
- setOptionFromAttribute(
718
- this,
719
- attrName,
720
- this[internalSymbol].getSubject()["options"],
721
- );
722
- }
723
-
724
- const callback = this[attributeObserverSymbol]?.[attrName];
725
- if (isFunction(callback)) {
726
- try {
727
- callback.call(this, newVal, oldVal);
728
- } catch (e) {
729
- addErrorAttribute(this, e);
730
- }
731
- }
732
- }
733
-
734
- /**
735
- * Checks if the provided node is part of this component's child nodes,
736
- * including those within the shadow root, if present.
737
- *
738
- * @param {Node} node - The node to check for within this component's child nodes.
739
- * @return {boolean} Returns true if the given node is found, otherwise false.
740
- * @throws {TypeError} value is not an instance of
741
- * @since 1.19.0
742
- */
743
- hasNode(node) {
744
- if (containChildNode.call(this, validateInstance(node, Node))) {
745
- return true;
746
- }
747
-
748
- if (!(this.shadowRoot instanceof ShadowRoot)) {
749
- return false;
750
- }
751
-
752
- return containChildNode.call(this.shadowRoot, node);
753
- }
754
-
755
- /**
756
- * Invokes a callback function with the given name and arguments.
757
- *
758
- * @param {string} name - The name of the callback to be executed.
759
- * @param {Array} args - An array of arguments to be passed to the callback function.
760
- * @return {*} The result of the callback function execution.
761
- */
762
- callCallback(name, args) {
763
- return callControlCallback.call(this, name, ...args);
764
- }
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
+ }
765
759
  }
766
760
 
767
761
  /**
@@ -770,46 +764,46 @@ class CustomElement extends HTMLElement {
770
764
  * @return {any}
771
765
  */
772
766
  function callControlCallback(callBackFunctionName, ...args) {
773
- if (!isString(callBackFunctionName) || callBackFunctionName === "") {
774
- return;
775
- }
776
-
777
- if (callBackFunctionName in this) {
778
- return this[callBackFunctionName](this, ...args);
779
- }
780
-
781
- if (!this.hasAttribute(ATTRIBUTE_SCRIPT_HOST)) {
782
- return;
783
- }
784
-
785
- if (this[scriptHostElementSymbol].length === 0) {
786
- const targetId = this.getAttribute(ATTRIBUTE_SCRIPT_HOST);
787
- if (!targetId) {
788
- return;
789
- }
790
-
791
- const list = targetId.split(",");
792
- for (const id of list) {
793
- const host = findElementWithIdUpwards(this, targetId);
794
- if (!(host instanceof HTMLElement)) {
795
- continue;
796
- }
797
-
798
- this[scriptHostElementSymbol].push(host);
799
- }
800
- }
801
-
802
- for (const host of this[scriptHostElementSymbol]) {
803
- if (callBackFunctionName in host) {
804
- try {
805
- return host[callBackFunctionName](this, ...args);
806
- } catch (e) {
807
- addErrorAttribute(this, e);
808
- }
809
- }
810
- }
811
-
812
- 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`);
813
807
  }
814
808
 
815
809
  /**
@@ -826,16 +820,16 @@ function callControlCallback(callBackFunctionName, ...args) {
826
820
  * @since 1.8.0
827
821
  */
828
822
  function initFromCallbackHost() {
829
- // Set the default callback function name
830
- let callBackFunctionName = initControlCallbackName;
823
+ // Set the default callback function name
824
+ let callBackFunctionName = initControlCallbackName;
831
825
 
832
- // If the `data-monster-option-callback` attribute is set, use its value as the callback function name
833
- if (this.hasAttribute(ATTRIBUTE_INIT_CALLBACK)) {
834
- callBackFunctionName = this.getAttribute(ATTRIBUTE_INIT_CALLBACK);
835
- }
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
+ }
836
830
 
837
- // Call the callback function with the element as a parameter if it exists
838
- callControlCallback.call(this, callBackFunctionName);
831
+ // Call the callback function with the element as a parameter if it exists
832
+ callControlCallback.call(this, callBackFunctionName);
839
833
  }
840
834
 
841
835
  /**
@@ -845,34 +839,35 @@ function initFromCallbackHost() {
845
839
  * @this CustomElement
846
840
  */
847
841
  function attachAttributeChangeMutationObserver() {
848
- const self = this;
849
-
850
- if (typeof self[attributeMutationObserverSymbol] !== "undefined") {
851
- return;
852
- }
853
-
854
- self[attributeMutationObserverSymbol] = new MutationObserver(
855
- function (mutations, observer) {
856
- for (const mutation of mutations) {
857
- if (mutation.type === "attributes") {
858
- self.attributeChangedCallback(
859
- mutation.attributeName,
860
- mutation.oldValue,
861
- mutation.target.getAttribute(mutation.attributeName),
862
- );
863
- }
864
- }
865
- },
866
- );
867
-
868
- try {
869
- self[attributeMutationObserverSymbol].observe(self, {
870
- attributes: true,
871
- attributeOldValue: true,
872
- });
873
- } catch (e) {
874
- addErrorAttribute(self, e);
875
- }
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
+ }
876
871
  }
877
872
 
878
873
  /**
@@ -882,111 +877,118 @@ function attachAttributeChangeMutationObserver() {
882
877
  * @return {boolean}
883
878
  */
884
879
  function containChildNode(node) {
885
- if (this.contains(node)) {
886
- return true;
887
- }
880
+ if (this.contains(node)) {
881
+ return true;
882
+ }
888
883
 
889
- for (const [, e] of Object.entries(this.childNodes)) {
890
- if (e.contains(node)) {
891
- return true;
892
- }
884
+ for (const [, e] of Object.entries(this.childNodes)) {
885
+ if (e.contains(node)) {
886
+ return true;
887
+ }
893
888
 
894
- containChildNode.call(e, node);
895
- }
889
+ containChildNode.call(e, node);
890
+ }
896
891
 
897
- return false;
892
+ return false;
898
893
  }
899
894
 
895
+
900
896
  /**
901
897
  * @license AGPLv3
902
- * @since 1.15.0
898
+ * @since 4.43.0
903
899
  * @private
904
900
  * @this CustomElement
905
901
  */
906
902
  function initOptionObserver() {
907
- const self = this;
908
-
909
- let lastDisabledValue = undefined;
910
- self.attachObserver(
911
- new Observer(function () {
912
- const flag = self.getOption("disabled");
913
-
914
- if (flag === lastDisabledValue) {
915
- return;
916
- }
917
-
918
- lastDisabledValue = flag;
919
-
920
- if (!(self.shadowRoot instanceof ShadowRoot)) {
921
- return;
922
- }
923
-
924
- const query =
925
- "button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]";
926
- const elements = self.shadowRoot.querySelectorAll(query);
927
-
928
- let nodeList;
929
- try {
930
- nodeList = new Set([
931
- ...elements,
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
-
948
- self.attachObserver(
949
- new Observer(function () {
950
- // not initialised
951
- if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) {
952
- return;
953
- }
954
- // inform every element
955
- const updaters = getLinkedObjects(self, customElementUpdaterLinkSymbol);
956
-
957
- for (const list of updaters) {
958
- for (const updater of list) {
959
- const d = clone(self[internalSymbol].getRealSubject()["options"]);
960
- Object.assign(updater.getSubject(), d);
961
- }
962
- }
963
- }),
964
- );
965
-
966
- // disabled
967
- self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => {
968
- if (self.hasAttribute(ATTRIBUTE_DISABLED)) {
969
- self.setOption(ATTRIBUTE_DISABLED, true);
970
- } else {
971
- self.setOption(ATTRIBUTE_DISABLED, undefined);
972
- }
973
- };
974
-
975
- // data-monster-options
976
- self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => {
977
- const options = getOptionsFromAttributes.call(self);
978
- if (isObject(options) && Object.keys(options).length > 0) {
979
- self.setOptions(options);
980
- }
981
- };
982
-
983
- // data-monster-options-selector
984
- self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => {
985
- const options = getOptionsFromScriptTag.call(self);
986
- if (isObject(options) && Object.keys(options).length > 0) {
987
- self.setOptions(options);
988
- }
989
- };
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
+ };
990
992
  }
991
993
 
992
994
  /**
@@ -995,35 +997,35 @@ function initOptionObserver() {
995
997
  * @throws {TypeError} value is not an object
996
998
  */
997
999
  function getOptionsFromScriptTag() {
998
- if (!this.hasAttribute(ATTRIBUTE_OPTIONS_SELECTOR)) {
999
- return {};
1000
- }
1001
-
1002
- const node = document.querySelector(
1003
- this.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR),
1004
- );
1005
- if (!(node instanceof HTMLScriptElement)) {
1006
- addErrorAttribute(
1007
- this,
1008
- `the selector ${ATTRIBUTE_OPTIONS_SELECTOR} for options was specified (${this.getAttribute(
1009
- ATTRIBUTE_OPTIONS_SELECTOR,
1010
- )}) but not found.`,
1011
- );
1012
- return {};
1013
- }
1014
-
1015
- let obj = {};
1016
-
1017
- try {
1018
- obj = parseOptionsJSON.call(this, node.textContent.trim());
1019
- } catch (e) {
1020
- addErrorAttribute(
1021
- this,
1022
- `when analyzing the configuration from the script tag there was an error. ${e}`,
1023
- );
1024
- }
1025
-
1026
- return obj;
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;
1027
1029
  }
1028
1030
 
1029
1031
  /**
@@ -1031,29 +1033,29 @@ function getOptionsFromScriptTag() {
1031
1033
  * @return {object}
1032
1034
  */
1033
1035
  function getOptionsFromAttributes() {
1034
- if (
1035
- this.hasAttribute(ATTRIBUTE_DISABLED) &&
1036
- this.getAttribute(ATTRIBUTE_DISABLED) !== null
1037
- ) {
1038
- this.setOption(ATTRIBUTE_DISABLED, true);
1039
- } else {
1040
- this.setOption(ATTRIBUTE_DISABLED, undefined);
1041
- }
1042
-
1043
- if (this.hasAttribute(ATTRIBUTE_OPTIONS)) {
1044
- try {
1045
- return parseOptionsJSON.call(this, this.getAttribute(ATTRIBUTE_OPTIONS));
1046
- } catch (e) {
1047
- addErrorAttribute(
1048
- this,
1049
- `the options attribute ${ATTRIBUTE_OPTIONS} does not contain a valid json definition (actual: ${this.getAttribute(
1050
- ATTRIBUTE_OPTIONS,
1051
- )}).${e}`,
1052
- );
1053
- }
1054
- }
1055
-
1056
- return {};
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 {};
1057
1059
  }
1058
1060
 
1059
1061
  /**
@@ -1065,25 +1067,25 @@ function getOptionsFromAttributes() {
1065
1067
  * @throws {error} Throws an error if the JSON data is not valid.
1066
1068
  */
1067
1069
  function parseOptionsJSON(data) {
1068
- let obj = {};
1070
+ let obj = {};
1069
1071
 
1070
- if (!isString(data)) {
1071
- return obj;
1072
- }
1072
+ if (!isString(data)) {
1073
+ return obj;
1074
+ }
1073
1075
 
1074
- // the configuration can be specified as a data url.
1075
- try {
1076
- const dataUrl = parseDataURL(data);
1077
- data = dataUrl.content;
1078
- } catch (e) {}
1076
+ // the configuration can be specified as a data url.
1077
+ try {
1078
+ const dataUrl = parseDataURL(data);
1079
+ data = dataUrl.content;
1080
+ } catch (e) {}
1079
1081
 
1080
- try {
1081
- obj = JSON.parse(data);
1082
- } catch (e) {
1083
- throw e;
1084
- }
1082
+ try {
1083
+ obj = JSON.parse(data);
1084
+ } catch (e) {
1085
+ throw e;
1086
+ }
1085
1087
 
1086
- return validateObject(obj);
1088
+ return validateObject(obj);
1087
1089
  }
1088
1090
 
1089
1091
  /**
@@ -1092,18 +1094,18 @@ function parseOptionsJSON(data) {
1092
1094
  * @returns {*|string}
1093
1095
  */
1094
1096
  function substituteI18n(html) {
1095
- if (!this.getOption("templateFormatter.i18n", false)) {
1096
- return html;
1097
- }
1098
-
1099
- const labels = this.getOption("labels", {});
1100
- if (!(isObject(labels) || isIterable(labels))) {
1101
- return html;
1102
- }
1103
-
1104
- const formatter = new Formatter(labels, {});
1105
- formatter.setMarker("i18n{", "}");
1106
- return formatter.format(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);
1107
1109
  }
1108
1110
 
1109
1111
  /**
@@ -1111,21 +1113,21 @@ function substituteI18n(html) {
1111
1113
  * @return {initHtmlContent}
1112
1114
  */
1113
1115
  function initHtmlContent() {
1114
- try {
1115
- const template = findDocumentTemplate(this.constructor.getTag());
1116
- this.appendChild(template.createDocumentFragment());
1117
- } catch (e) {
1118
- let html = this.getOption("templates.main", "");
1119
- if (isString(html) && html.length > 0) {
1120
- const mapping = this.getOption("templateMapping", {});
1121
- if (isObject(mapping)) {
1122
- html = new Formatter(mapping, {}).format(html);
1123
- }
1124
- this.innerHTML = substituteI18n.call(this, html);
1125
- }
1126
- }
1127
-
1128
- return this;
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;
1129
1131
  }
1130
1132
 
1131
1133
  /**
@@ -1137,49 +1139,49 @@ function initHtmlContent() {
1137
1139
  * @throws {TypeError} value is not an instance of
1138
1140
  */
1139
1141
  function initCSSStylesheet() {
1140
- if (!(this.shadowRoot instanceof ShadowRoot)) {
1141
- return this;
1142
- }
1143
-
1144
- const styleSheet = this.constructor.getCSSStyleSheet();
1145
-
1146
- if (styleSheet instanceof CSSStyleSheet) {
1147
- if (styleSheet.cssRules.length > 0) {
1148
- this.shadowRoot.adoptedStyleSheets = [styleSheet];
1149
- }
1150
- } else if (isArray(styleSheet)) {
1151
- const assign = [];
1152
- for (const s of styleSheet) {
1153
- if (isString(s)) {
1154
- const trimedStyleSheet = s.trim();
1155
- if (trimedStyleSheet !== "") {
1156
- const style = document.createElement("style");
1157
- style.innerHTML = trimedStyleSheet;
1158
- this.shadowRoot.prepend(style);
1159
- }
1160
- continue;
1161
- }
1162
-
1163
- validateInstance(s, CSSStyleSheet);
1164
-
1165
- if (s.cssRules.length > 0) {
1166
- assign.push(s);
1167
- }
1168
- }
1169
-
1170
- if (assign.length > 0) {
1171
- this.shadowRoot.adoptedStyleSheets = assign;
1172
- }
1173
- } else if (isString(styleSheet)) {
1174
- const trimedStyleSheet = styleSheet.trim();
1175
- if (trimedStyleSheet !== "") {
1176
- const style = document.createElement("style");
1177
- style.innerHTML = styleSheet;
1178
- this.shadowRoot.prepend(style);
1179
- }
1180
- }
1181
-
1182
- return this;
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;
1183
1185
  }
1184
1186
 
1185
1187
  /**
@@ -1191,42 +1193,42 @@ function initCSSStylesheet() {
1191
1193
  * @since 1.8.0
1192
1194
  */
1193
1195
  function initShadowRoot() {
1194
- let template;
1195
- let html;
1196
-
1197
- try {
1198
- template = findDocumentTemplate(this.constructor.getTag());
1199
- } catch (e) {
1200
- html = this.getOption("templates.main", "");
1201
- if (!isString(html) || html === undefined || html === "") {
1202
- throw new Error("html is not set.");
1203
- }
1204
- }
1205
-
1206
- this.attachShadow({
1207
- mode: this.getOption("shadowMode", "open"),
1208
- delegatesFocus: this.getOption("delegatesFocus", true),
1209
- });
1210
-
1211
- if (template instanceof Template) {
1212
- this.shadowRoot.appendChild(template.createDocumentFragment());
1213
- return this;
1214
- }
1215
-
1216
- const mapping = this.getOption("templateMapping", {});
1217
- if (isObject(mapping)) {
1218
- const formatter = new Formatter(mapping);
1219
- if (this.getOption("templateFormatter.marker.open") !== null) {
1220
- formatter.setMarker(
1221
- this.getOption("templateFormatter.marker.open"),
1222
- this.getOption("templateFormatter.marker.close"),
1223
- );
1224
- }
1225
- html = formatter.format(html);
1226
- }
1227
-
1228
- this.shadowRoot.innerHTML = substituteI18n.call(this, html);
1229
- return this;
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;
1230
1232
  }
1231
1233
 
1232
1234
  /**
@@ -1240,20 +1242,20 @@ function initShadowRoot() {
1240
1242
  * @throws {DOMException} Failed to execute 'define' on 'CustomElementRegistry': is not a valid custom element name
1241
1243
  */
1242
1244
  function registerCustomElement(element) {
1243
- validateFunction(element);
1244
- const customElements = getGlobalObject("customElements");
1245
- if (customElements === undefined) {
1246
- throw new Error("customElements is not supported.");
1247
- }
1248
-
1249
- const tag = element?.getTag();
1250
- if (!isString(tag) || tag === "") {
1251
- throw new Error("tag is not set.");
1252
- }
1253
-
1254
- if (customElements.get(tag) !== undefined) {
1255
- return;
1256
- }
1257
-
1258
- customElements.define(tag, 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);
1259
1261
  }