diff --git a/source/components/datatable/save-button.mjs b/source/components/datatable/save-button.mjs index a1188237f55fa4aa848a307dc3d76ca3c2cce9ee..4bc5d7736f3aac9c3b4a373202db3dc6c24b262d 100644 --- a/source/components/datatable/save-button.mjs +++ b/source/components/datatable/save-button.mjs @@ -199,6 +199,7 @@ class SaveButton extends CustomElement { const ignoreChanges = self.getOption("ignoreChanges"); const result = diff(self[originValuesSymbol], currentValues); + if (isArray(ignoreChanges) && ignoreChanges.length > 0) { const itemsToRemove = []; for (const item of result) { diff --git a/source/components/form/select.mjs b/source/components/form/select.mjs index 0a4871ecde805eedafc60b54d611a403d3d70a60..657a3821d38361a88970d97aa0b2fc161f1a3341 100644 --- a/source/components/form/select.mjs +++ b/source/components/form/select.mjs @@ -12,59 +12,59 @@ * SPDX-License-Identifier: AGPL-3.0 */ -import { instanceSymbol } from "../../constants.mjs"; -import { internalSymbol } from "../../constants.mjs"; -import { buildMap } from "../../data/buildmap.mjs"; -import { DeadMansSwitch } from "../../util/deadmansswitch.mjs"; -import { positionPopper } from "./util/floating-ui.mjs"; +import {instanceSymbol} from "../../constants.mjs"; +import {internalSymbol} from "../../constants.mjs"; +import {buildMap} from "../../data/buildmap.mjs"; +import {DeadMansSwitch} from "../../util/deadmansswitch.mjs"; +import {positionPopper} from "./util/floating-ui.mjs"; import { - addAttributeToken, - findClosestByAttribute, - removeAttributeToken, + addAttributeToken, + findClosestByAttribute, + removeAttributeToken, } from "../../dom/attributes.mjs"; -import { ATTRIBUTE_PREFIX, ATTRIBUTE_ROLE } from "../../dom/constants.mjs"; -import { CustomControl } from "../../dom/customcontrol.mjs"; +import {ATTRIBUTE_PREFIX, ATTRIBUTE_ROLE} from "../../dom/constants.mjs"; +import {CustomControl} from "../../dom/customcontrol.mjs"; import { - assembleMethodSymbol, - getSlottedElements, - registerCustomElement, + assembleMethodSymbol, + getSlottedElements, + registerCustomElement, } from "../../dom/customelement.mjs"; import { - findTargetElementFromEvent, - fireCustomEvent, - fireEvent, + findTargetElementFromEvent, + fireCustomEvent, + fireEvent, } from "../../dom/events.mjs"; -import { getDocument } from "../../dom/util.mjs"; -import { Formatter } from "../../text/formatter.mjs"; -import { getGlobal } from "../../types/global.mjs"; -import { ID } from "../../types/id.mjs"; +import {getDocument} from "../../dom/util.mjs"; +import {Formatter} from "../../text/formatter.mjs"; +import {getGlobal} from "../../types/global.mjs"; +import {ID} from "../../types/id.mjs"; import { - isArray, - isFunction, - isInteger, - isIterable, - isObject, - isPrimitive, - isString, + isArray, + isFunction, + isInteger, + isIterable, + isObject, + isPrimitive, + isString, } from "../../types/is.mjs"; -import { Observer } from "../../types/observer.mjs"; -import { ProxyObserver } from "../../types/proxyobserver.mjs"; -import { validateArray, validateString } from "../../types/validate.mjs"; -import { Processing } from "../../util/processing.mjs"; -import { STYLE_DISPLAY_MODE_BLOCK } from "./constants.mjs"; -import { SelectStyleSheet } from "./stylesheet/select.mjs"; +import {Observer} from "../../types/observer.mjs"; +import {ProxyObserver} from "../../types/proxyobserver.mjs"; +import {validateArray, validateString} from "../../types/validate.mjs"; +import {Processing} from "../../util/processing.mjs"; +import {STYLE_DISPLAY_MODE_BLOCK} from "./constants.mjs"; +import {SelectStyleSheet} from "./stylesheet/select.mjs"; import { - getDocumentTranslations, - Translations, + getDocumentTranslations, + Translations, } from "../../i18n/translations.mjs"; -import { getLocaleOfDocument } from "../../dom/locale.mjs"; -import { addErrorAttribute, removeErrorAttribute } from "../../dom/error.mjs"; +import {getLocaleOfDocument} from "../../dom/locale.mjs"; +import {addErrorAttribute, removeErrorAttribute} from "../../dom/error.mjs"; export { - Select, - popperElementSymbol, - getSummaryTemplate, - getSelectionTemplate, + Select, + popperElementSymbol, + getSummaryTemplate, + getSelectionTemplate, }; /** @@ -185,7 +185,7 @@ const popperFilterElementSymbol = Symbol("popperFilterElement"); * @type {Symbol} */ const popperFilterContainerElementSymbol = Symbol( - "popperFilterContainerElement", + "popperFilterContainerElement", ); /** @@ -283,498 +283,498 @@ const FILTER_POSITION_INLINE = "inline"; * @fires monster-changed */ class Select extends CustomControl { - /** - * - */ - constructor() { - super(); - initOptionObserver.call(this); - } - - /** - * This method is called by the `instanceof` operator. - * @return {Symbol} - */ - static get [instanceSymbol]() { - return Symbol.for("@schukai/monster/components/form/select@@instance"); - } - - /** - * The current selection of the Select - * - * ``` - * e = document.querySelector('monster-select'); - * console.log(e.value) - * // ↦ 1 - * // ↦ ['1','2'] - * ``` - * - * @return {string} - */ - get value() { - return convertSelectionToValue.call(this, this.getOption("selection")); - } - - /** - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals} - * @return {boolean} - */ - static get formAssociated() { - return true; - } - - /** - * Set selection - * - * ``` - * e = document.querySelector('monster-select'); - * e.value=1 - * ``` - * - * @property {string|array} value - * @throws {Error} unsupported type - * @fires monster-selected this event is fired when the selection is set - */ - set value(value) { - let ignoreValues = this.getOption("ignoreValues", []); - if (!isArray(ignoreValues)) { - ignoreValues = []; - } - - for (const v of ignoreValues) { - if (value === v) { - return; - } - } - - const result = convertValueToSelection.call(this, value); - - setSelection - .call(this, result.selection) - .then(() => {}) - .catch((e) => { - addErrorAttribute(this, e); - }); - } - - /** - * To set the options via the HTML tag, the attribute `data-monster-options` must be used. - * @see {@link https://monsterjs.org/en/doc/#configurate-a-monster-control} - * - * The individual configuration values can be found in the table. - * - * @property {Object} toggleEventType List of event types to be observed for opening the dropdown - * @property {boolean} delegatesFocus lorem [see mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/delegatesFocus) - * @property {Object[]} options Selection of key identifier pairs available for selection and displayed in the dropdown. - * @property {string} options[].label - * @property {string} options[].value - * @property {string} options[].visibility hidden or visible - * @property {Array} selection Selected options - * @property {Integer} showMaxOptions Maximum number of visible options before a scroll bar should be displayed. - * @property {string} type Multiple (checkbox) or single selection (radio) - * @property {string} name Name of the form field - * @property {string} url Load options from server per url - * @property {object} lookup Load options from server per url - * @property {string} lookup.url Load options from server per url - * @property {boolean} lookup.grouping Load all selected options from server per url at once (true) or one by one (false) - * @property {Object} fetch Fetch [see Using Fetch mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) - * @property {String} fetch.redirect - * @property {String} fetch.method - * @property {String} fetch.mode - * @property {String} fetch.credentials - * @property {Object} fetch.headers - * @property {Object} labels - * @property {string} labels.cannot-be-loaded cannot be loaded - * @property {string} labels.no-options-available no options available - * @property {string} labels.select-an-option select an option - * @property {string} labels.no-option no option in the list, maybe you have to change the filter - * @property {Object} features List with features - * @property {Boolean} features.clearAll Display of a delete button to delete the entire selection - * @property {Boolean} features.clear Display of a delete key for deleting the specific selection - * @property {Boolean} features.lazyLoad Load options when first opening the dropdown. (Hint; lazylLoad is not supported with remote filter) - * @property {Boolean} features.closeOnSelect Close the dropdown when an option is selected (since 3.54.0) - * @property {Boolean} features.emptyValueIfNoOptions If no options are available, the selection is set to an empty array - * @property {Boolean} features.storeFetchedData Store fetched data in the object - * @property {Boolean} features.useStrictValueComparison Use strict value comparison for the selection - * @property {string} filter.defaultValue Default filter value, if the filter is empty, if the default value is null, then no request is made - * @property {Boolean} filter.mode Filter mode, values: options, remote, disabled (Hint; lazylLoad is not supported with remote filter, if you use remote filter, the lazyLoad is disabled) - * @property {Object} templates Template definitions - * @property {string} templates.main Main template - * @property {string} templateMapping Mapping of the template placeholders - * @property {string} templateMapping.selected Selected Template - * @property {Object} popper [PopperJS Options](https://popper.js.org/docs/v2/) - * @property {string} popper.placement PopperJS placement - * @property {Object[]} modifiers PopperJS placement - * @property {Object} mapping - * @property {String} mapping.selector Path to select the appropriate entries - * @property {String} mapping.labelTemplate template with the label placeholders in the form ${name}, where name is the key (**) - * @property {String} mapping.valueTemplate template with the value placeholders in the form ${name}, where name is the key - * @property {function|undefined} mapping.filter Filtering of values via a function - * @property {Array} ignoreValues Ignore values in the selection and value - * @property {Object} formatter - * @property {function|undefined} formatter.selection format selection label - */ - get defaults() { - return Object.assign( - {}, - super.defaults, - { - toggleEventType: ["click", "touch"], - delegatesFocus: false, - options: [], - selection: [], - showMaxOptions: 10, - type: "radio", - name: new ID("s").toString(), - features: { - clearAll: true, - clear: true, - lazyLoad: false, - closeOnSelect: false, - emptyValueIfNoOptions: false, - storeFetchedData: false, - useStrictValueComparison: false, - }, - url: null, - lookup: { - url: null, - grouping: false, - }, - labels: getTranslations(), - messages: { - control: null, - selected: null, - emptyOptions: null, - }, - fetch: { - redirect: "error", - method: "GET", - mode: "same-origin", - credentials: "same-origin", - headers: { - accept: "application/json", - }, - }, - filter: { - defaultValue: null, - mode: FILTER_MODE_DISABLED, - position: FILTER_POSITION_INLINE, - marker: { - open: "{", - close: "}", - }, - }, - classes: { - badge: "monster-badge-primary", - statusOrRemoveBadge: "empty", - }, - mapping: { - selector: "*", - labelTemplate: "", - valueTemplate: "", - filter: null, - }, - ignoreValues: [undefined, null, ""], - formatter: { - selection: buildSelectionLabel, - }, - templates: { - main: getTemplate(), - }, - templateMapping: { - /** with the attribute `data-monster-selected-template` the template for the selected options can be defined. */ - selected: getSelectionTemplate(), - }, - - popper: { - placement: "bottom", - middleware: ["flip", "offset:1"], - }, - }, - initOptionsFromArguments.call(this), - ); - } - - /** - * @return {Select} - */ - [assembleMethodSymbol]() { - const self = this; - super[assembleMethodSymbol](); - - initControlReferences.call(self); - initEventHandler.call(self); - - let lazyLoadFlag = self.getOption("features.lazyLoad", false); - let remoteFilterFlag = getFilterMode.call(this) === FILTER_MODE_REMOTE; - - if (getFilterMode.call(this) === FILTER_MODE_REMOTE) { - self.getOption("features.lazyLoad", false); - if (lazyLoadFlag === true) { - addErrorAttribute(this, "lazyLoad is not supported with remote filter"); - lazyLoadFlag = false; - } - } - - if (self.hasAttribute("value")) { - new Processing(10, () => { - const oldValue = self.value; - const newValue = self.getAttribute("value"); - if (oldValue !== newValue) { - self.value = newValue; - } - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - } - - if (self.getOption("url") !== null) { - if (lazyLoadFlag || remoteFilterFlag) { - lookupSelection.call(self); - } else { - self.fetch().catch((e) => { - addErrorAttribute(self, e); - }); - } - } - - requestAnimationFrame(() => { - let lastValue = self.value; - self[internalSymbol].attachObserver( - new Observer(function () { - if (isObject(this) && this instanceof ProxyObserver) { - const n = this.getSubject()?.options?.value; - - if (lastValue !== n && n !== undefined) { - lastValue = n; - setSelection - .call(self, n) - .then(() => {}) - .catch((e) => { - addErrorAttribute(self, e); - }); - } - } - }), - ); - - areOptionsAvailableAndInit.call(self); - }); - - return this; - } - - /** - * - * @return {*} - * @throws {Error} storeFetchedData is not enabled - * @since 3.66.0 - */ - getLastFetchedData() { - if (this.getOption("features.storeFetchedData") === false) { - throw new Error("storeFetchedData is not enabled"); - } - - return this?.[lastFetchedDataSymbol]; - } - - /** - * The Button.click() method simulates a click on the internal button element. - * - * @since 3.27.0 - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click} - */ - click() { - if (this.getOption("disabled") === true) { - return; - } - - toggle.call(this); - } - - /** - * The Button.focus() method sets focus on the internal button element. - * - * @since 3.27.0 - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus} - */ - focus(options) { - if (this.getOption("disabled") === true) { - return; - } - - new Processing(() => { - gatherState.call(this); - focusFilter.call(this, options); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - } - - /** - * The Button.blur() method removes focus from the internal button element. - * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur - */ - blur() { - new Processing(() => { - gatherState.call(this); - blurFilter.call(this); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - } - - /** - * If no url is specified, the options are taken from the Component itself. - * - * @param {string|URL} url URL to fetch the options - * @return {Promise} - */ - fetch(url) { - return fetchIt.call(this, url); - } - - /** - * @return {void} - */ - connectedCallback() { - super.connectedCallback(); - const document = getDocument(); - - for (const [, type] of Object.entries(["click", "touch"])) { - // close on outside ui-events - document.addEventListener(type, this[closeEventHandler]); - } - - parseSlotsToOptions.call(this); - attachResizeObserver.call(this); - updatePopper.call(this); - - new Processing(() => { - gatherState.call(this); - focusFilter.call(this); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - } - - /** - * @return {void} - */ - disconnectedCallback() { - super.disconnectedCallback(); - const document = getDocument(); - - // close on outside ui-events - for (const [, type] of Object.entries(["click", "touch"])) { - document.removeEventListener(type, this[closeEventHandler]); - } - - disconnectResizeObserver.call(this); - } - - /** - * Import Select Options from dataset - * Not to be confused with the control defaults/options - * - * @param {array|object|Map|Set} data - * @return {Select} - * @throws {Error} map is not iterable - * @throws {Error} missing label configuration - * @fires monster-options-set this event is fired when the options are set - */ - importOptions(data) { - const mappingOptions = this.getOption("mapping", {}); - const selector = mappingOptions?.["selector"]; - const labelTemplate = mappingOptions?.["labelTemplate"]; - const valueTemplate = mappingOptions?.["valueTemplate"]; - const filter = mappingOptions?.["filter"]; - - let flag = false; - if (labelTemplate === "") { - addErrorAttribute(this, "empty label template"); - flag = true; - } - - if (valueTemplate === "") { - addErrorAttribute(this, "empty value template"); - flag = true; - } - - if (flag === true) { - throw new Error("missing label configuration"); - } - - const map = buildMap(data, selector, labelTemplate, valueTemplate, filter); - - const options = []; - - if (!isIterable(map)) { - throw new Error("map is not iterable"); - } - - const visibility = "visible"; - - map.forEach((label, value) => { - options.push({ - value, - label, - visibility, - data: map.get(value), - }); - }); - - runAsOptionLengthChanged.call(this, map.size); - this.setOption("options", options); - - fireCustomEvent(this, "monster-options-set", { - options, - }); - - setTimeout(() => { - setSelection - .call(this, this.getOption("selection")) - .then(() => {}) - .catch((e) => { - addErrorAttribute(this, e); - }); - }, 10); - - return this; - } - - /** - * @private - * @return {Select} - */ - calcAndSetOptionsDimension() { - calcAndSetOptionsDimension.call(this); - return this; - } - - /** - * - * @return {string} - */ - static getTag() { - return "monster-select"; - } - - /** - * - * @return {CSSStyleSheet[]} - */ - static getCSSStyleSheet() { - return [SelectStyleSheet]; - } + /** + * + */ + constructor() { + super(); + initOptionObserver.call(this); + } + + /** + * This method is called by the `instanceof` operator. + * @return {Symbol} + */ + static get [instanceSymbol]() { + return Symbol.for("@schukai/monster/components/form/select@@instance"); + } + + /** + * The current selection of the Select + * + * ``` + * e = document.querySelector('monster-select'); + * console.log(e.value) + * // ↦ 1 + * // ↦ ['1','2'] + * ``` + * + * @return {string} + */ + get value() { + return convertSelectionToValue.call(this, this.getOption("selection")); + } + + /** + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals} + * @return {boolean} + */ + static get formAssociated() { + return true; + } + + /** + * Set selection + * + * ``` + * e = document.querySelector('monster-select'); + * e.value=1 + * ``` + * + * @property {string|array} value + * @throws {Error} unsupported type + * @fires monster-selected this event is fired when the selection is set + */ + set value(value) { + + const result = convertValueToSelection.call(this, value); + + setSelection + .call(this, result.selection) + .then(() => { + }) + .catch((e) => { + addErrorAttribute(this, e); + }); + } + + /** + * To set the options via the HTML tag, the attribute `data-monster-options` must be used. + * @see {@link https://monsterjs.org/en/doc/#configurate-a-monster-control} + * + * The individual configuration values can be found in the table. + * + * @property {Object} toggleEventType List of event types to be observed for opening the dropdown + * @property {boolean} delegatesFocus lorem [see mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/delegatesFocus) + * @property {Object[]} options Selection of key identifier pairs available for selection and displayed in the dropdown. + * @property {string} options[].label + * @property {string} options[].value + * @property {string} options[].visibility hidden or visible + * @property {Array} selection Selected options + * @property {Integer} showMaxOptions Maximum number of visible options before a scroll bar should be displayed. + * @property {string} type Multiple (checkbox) or single selection (radio) + * @property {string} name Name of the form field + * @property {string} url Load options from server per url + * @property {object} lookup Load options from server per url + * @property {string} lookup.url Load options from server per url + * @property {boolean} lookup.grouping Load all selected options from server per url at once (true) or one by one (false) + * @property {Object} fetch Fetch [see Using Fetch mozilla.org](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) + * @property {String} fetch.redirect + * @property {String} fetch.method + * @property {String} fetch.mode + * @property {String} fetch.credentials + * @property {Object} fetch.headers + * @property {Object} labels + * @property {string} labels.cannot-be-loaded cannot be loaded + * @property {string} labels.no-options-available no options available + * @property {string} labels.select-an-option select an option + * @property {string} labels.no-option no option in the list, maybe you have to change the filter + * @property {Object} features List with features + * @property {Boolean} features.clearAll Display of a delete button to delete the entire selection + * @property {Boolean} features.clear Display of a delete key for deleting the specific selection + * @property {Boolean} features.lazyLoad Load options when first opening the dropdown. (Hint; lazylLoad is not supported with remote filter) + * @property {Boolean} features.closeOnSelect Close the dropdown when an option is selected (since 3.54.0) + * @property {Boolean} features.emptyValueIfNoOptions If no options are available, the selection is set to an empty array + * @property {Boolean} features.storeFetchedData Store fetched data in the object + * @property {Boolean} features.useStrictValueComparison Use strict value comparison for the selection + * @property {string} filter.defaultValue Default filter value, if the filter is empty, if the default value is null, then no request is made + * @property {Boolean} filter.mode Filter mode, values: options, remote, disabled (Hint; lazylLoad is not supported with remote filter, if you use remote filter, the lazyLoad is disabled) + * @property {Object} templates Template definitions + * @property {string} templates.main Main template + * @property {string} templateMapping Mapping of the template placeholders + * @property {string} templateMapping.selected Selected Template + * @property {Object} popper [PopperJS Options](https://popper.js.org/docs/v2/) + * @property {string} popper.placement PopperJS placement + * @property {Object[]} modifiers PopperJS placement + * @property {Object} mapping + * @property {String} mapping.selector Path to select the appropriate entries + * @property {String} mapping.labelTemplate template with the label placeholders in the form ${name}, where name is the key (**) + * @property {String} mapping.valueTemplate template with the value placeholders in the form ${name}, where name is the key + * @property {function|undefined} mapping.filter Filtering of values via a function + * @property {Object} empty + * @property {String} empty.defaultValueRadio Default value if you use radio buttons + * @property {Array} empty.defaultValueCheckbox Default value if you use checkboxes + * @property {Array} empty.equivalents Equivalents for empty values + * @property {Object} formatter + * @property {function|undefined} formatter.selection format selection label + */ + get defaults() { + return Object.assign( + {}, + super.defaults, + { + toggleEventType: ["click", "touch"], + delegatesFocus: false, + options: [], + selection: [], + showMaxOptions: 10, + type: "radio", + name: new ID("s").toString(), + features: { + clearAll: true, + clear: true, + lazyLoad: false, + closeOnSelect: false, + emptyValueIfNoOptions: false, + storeFetchedData: false, + useStrictValueComparison: false, + }, + url: null, + lookup: { + url: null, + grouping: false, + }, + labels: getTranslations(), + messages: { + control: null, + selected: null, + emptyOptions: null, + }, + fetch: { + redirect: "error", + method: "GET", + mode: "same-origin", + credentials: "same-origin", + headers: { + accept: "application/json", + }, + }, + filter: { + defaultValue: null, + mode: FILTER_MODE_DISABLED, + position: FILTER_POSITION_INLINE, + marker: { + open: "{", + close: "}", + }, + }, + classes: { + badge: "monster-badge-primary", + statusOrRemoveBadge: "empty", + }, + mapping: { + selector: "*", + labelTemplate: "", + valueTemplate: "", + filter: null, + }, + empty: { + defaultValueRadio: "", + defaultValueCheckbox: [], + equivalents: [undefined, null, "", NaN], + }, + formatter: { + selection: buildSelectionLabel, + }, + templates: { + main: getTemplate(), + }, + templateMapping: { + /** with the attribute `data-monster-selected-template` the template for the selected options can be defined. */ + selected: getSelectionTemplate(), + }, + + popper: { + placement: "bottom", + middleware: ["flip", "offset:1"], + }, + }, + initOptionsFromArguments.call(this), + ); + } + + /** + * @return {Select} + */ + [assembleMethodSymbol]() { + const self = this; + super[assembleMethodSymbol](); + + initControlReferences.call(self); + initEventHandler.call(self); + + let lazyLoadFlag = self.getOption("features.lazyLoad", false); + let remoteFilterFlag = getFilterMode.call(this) === FILTER_MODE_REMOTE; + + if (getFilterMode.call(this) === FILTER_MODE_REMOTE) { + self.getOption("features.lazyLoad", false); + if (lazyLoadFlag === true) { + addErrorAttribute(this, "lazyLoad is not supported with remote filter"); + lazyLoadFlag = false; + } + } + + if (self.hasAttribute("value")) { + new Processing(10, () => { + const oldValue = self.value; + const newValue = self.getAttribute("value"); + if (oldValue !== newValue) { + self.value = newValue; + } + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + } + + if (self.getOption("url") !== null) { + if (lazyLoadFlag || remoteFilterFlag) { + lookupSelection.call(self); + } else { + self.fetch().catch((e) => { + addErrorAttribute(self, e); + }); + } + } + + setTimeout(() => { + let lastValue = self.value; + self[internalSymbol].attachObserver( + new Observer(function () { + if (isObject(this) && this instanceof ProxyObserver) { + const n = this.getSubject()?.options?.value; + + if (lastValue !== n && n !== undefined) { + lastValue = n; + setSelection + .call(self, n) + .then(() => { + }) + .catch((e) => { + addErrorAttribute(self, e); + }); + } + } + }), + ); + + areOptionsAvailableAndInit.call(self); + },0); + + return this; + } + + /** + * + * @return {*} + * @throws {Error} storeFetchedData is not enabled + * @since 3.66.0 + */ + getLastFetchedData() { + if (this.getOption("features.storeFetchedData") === false) { + throw new Error("storeFetchedData is not enabled"); + } + + return this?.[lastFetchedDataSymbol]; + } + + /** + * The Button.click() method simulates a click on the internal button element. + * + * @since 3.27.0 + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click} + */ + click() { + if (this.getOption("disabled") === true) { + return; + } + + toggle.call(this); + } + + /** + * The Button.focus() method sets focus on the internal button element. + * + * @since 3.27.0 + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus} + */ + focus(options) { + if (this.getOption("disabled") === true) { + return; + } + + new Processing(() => { + gatherState.call(this); + focusFilter.call(this, options); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + } + + /** + * The Button.blur() method removes focus from the internal button element. + * @link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/blur + */ + blur() { + new Processing(() => { + gatherState.call(this); + blurFilter.call(this); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + } + + /** + * If no url is specified, the options are taken from the Component itself. + * + * @param {string|URL} url URL to fetch the options + * @return {Promise} + */ + fetch(url) { + return fetchIt.call(this, url); + } + + /** + * @return {void} + */ + connectedCallback() { + super.connectedCallback(); + const document = getDocument(); + + for (const [, type] of Object.entries(["click", "touch"])) { + // close on outside ui-events + document.addEventListener(type, this[closeEventHandler]); + } + + parseSlotsToOptions.call(this); + attachResizeObserver.call(this); + updatePopper.call(this); + + new Processing(() => { + gatherState.call(this); + focusFilter.call(this); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + } + + /** + * @return {void} + */ + disconnectedCallback() { + super.disconnectedCallback(); + const document = getDocument(); + + // close on outside ui-events + for (const [, type] of Object.entries(["click", "touch"])) { + document.removeEventListener(type, this[closeEventHandler]); + } + + disconnectResizeObserver.call(this); + } + + /** + * Import Select Options from dataset + * Not to be confused with the control defaults/options + * + * @param {array|object|Map|Set} data + * @return {Select} + * @throws {Error} map is not iterable + * @throws {Error} missing label configuration + * @fires monster-options-set this event is fired when the options are set + */ + importOptions(data) { + const mappingOptions = this.getOption("mapping", {}); + const selector = mappingOptions?.["selector"]; + const labelTemplate = mappingOptions?.["labelTemplate"]; + const valueTemplate = mappingOptions?.["valueTemplate"]; + const filter = mappingOptions?.["filter"]; + + let flag = false; + if (labelTemplate === "") { + addErrorAttribute(this, "empty label template"); + flag = true; + } + + if (valueTemplate === "") { + addErrorAttribute(this, "empty value template"); + flag = true; + } + + if (flag === true) { + throw new Error("missing label configuration"); + } + + const map = buildMap(data, selector, labelTemplate, valueTemplate, filter); + + const options = []; + + if (!isIterable(map)) { + throw new Error("map is not iterable"); + } + + const visibility = "visible"; + + map.forEach((label, value) => { + options.push({ + value, + label, + visibility, + data: map.get(value), + }); + }); + + runAsOptionLengthChanged.call(this, map.size); + this.setOption("options", options); + + fireCustomEvent(this, "monster-options-set", { + options, + }); + + setTimeout(() => { + setSelection + .call(this, this.getOption("selection")) + .then(() => { + }) + .catch((e) => { + addErrorAttribute(this, e); + }); + }, 10); + + return this; + } + + /** + * @private + * @return {Select} + */ + calcAndSetOptionsDimension() { + calcAndSetOptionsDimension.call(this); + return this; + } + + /** + * + * @return {string} + */ + static getTag() { + return "monster-select"; + } + + /** + * + * @return {CSSStyleSheet[]} + */ + static getCSSStyleSheet() { + return [SelectStyleSheet]; + } } /** @@ -782,285 +782,286 @@ class Select extends CustomControl { * @returns {object} */ function getTranslations() { - const locale = getLocaleOfDocument(); - switch (locale.language) { - case "de": - return { - "cannot-be-loaded": "Kann nicht geladen werden", - "no-options-available": "Keine Optionen verfügbar.", - "click-to-load-options": "Klicken, um Optionen zu laden.", - "select-an-option": "Wähle eine Option", - "summary-text": { - zero: "Keine Einträge ausgewählt", - one: '<span class="monster-badge-primary-pill">1</span> Eintrag ausgewählt', - other: - '<span class="monster-badge-primary-pill">${count}</span> Einträge ausgewählt', - }, - "no-options": "Leider gibt es keine Optionen in der Liste.", - "no-options-found": - "Keine Optionen in der Liste verfügbar. Bitte ändern Sie den Filter.", - }; - case "fr": - return { - "cannot-be-loaded": "Impossible de charger", - "no-options-available": "Aucune option disponible.", - "click-to-load-options": "Cliquez pour charger les options.", - "select-an-option": "Sélectionnez une option", - "summary-text": { - zero: "Aucune entrée sélectionnée", - one: '<span class="monster-badge-primary-pill">1</span> entrée sélectionnée', - other: - '<span class="monster-badge-primary-pill">${count}</span> entrées sélectionnées', - }, - "no-options": - "Malheureusement, il n'y a pas d'options disponibles dans la liste.", - "no-options-found": - "Aucune option disponible dans la liste. Veuillez modifier le filtre.", - }; - - case "sp": - return { - "cannot-be-loaded": "No se puede cargar", - "no-options-available": "No hay opciones disponibles.", - "click-to-load-options": "Haga clic para cargar opciones.", - "select-an-option": "Seleccione una opción", - "summary-text": { - zero: "No se seleccionaron entradas", - one: '<span class="monster-badge-primary-pill">1</span> entrada seleccionada', - other: - '<span class="monster-badge-primary-pill">${count}</span> entradas seleccionadas', - }, - "no-options": - "Desafortunadamente, no hay opciones disponibles en la lista.", - "no-options-found": - "No hay opciones disponibles en la lista. Considere modificar el filtro.", - }; - case "it": - return { - "cannot-be-loaded": "Non può essere caricato", - "no-options-available": "Nessuna opzione disponibile.", - "click-to-load-options": "Clicca per caricare le opzioni.", - "select-an-option": "Seleziona un'opzione", - "summary-text": { - zero: "Nessuna voce selezionata", - one: '<span class="monster-badge-primary-pill">1</span> voce selezionata', - other: - '<span class="monster-badge-primary-pill">${count}</span> voci selezionate', - }, - "no-options": "Purtroppo, non ci sono opzioni disponibili nella lista.", - "no-options-found": - "Nessuna opzione disponibile nella lista. Si prega di modificare il filtro.", - }; - case "pl": - return { - "cannot-be-loaded": "Nie można załadować", - "no-options-available": "Brak dostępnych opcji.", - "click-to-load-options": "Kliknij, aby załadować opcje.", - "select-an-option": "Wybierz opcję", - "summary-text": { - zero: "Nie wybrano żadnych wpisów", - one: '<span class="monster-badge-primary-pill">1</span> wpis został wybrany', - other: - '<span class="monster-badge-primary-pill">${count}</span> wpisy zostały wybrane', - }, - "no-options": "Niestety, nie ma dostępnych opcji na liście.", - "no-options-found": - "Brak dostępnych opcji na liście. Rozważ zmianę filtra.", - }; - case "no": - return { - "cannot-be-loaded": "Kan ikke lastes", - "no-options-available": "Ingen alternativer tilgjengelig.", - "click-to-load-options": "Klikk for å laste alternativer.", - "select-an-option": "Velg et alternativ", - "summary-text": { - zero: "Ingen oppføringer ble valgt", - one: '<span class="monster-badge-primary-pill">1</span> oppføring valgt', - other: - '<span class="monster-badge-primary-pill">${count}</span> oppføringer valgt', - }, - "no-options": - "Dessverre er det ingen alternativer tilgjengelig i listen.", - "no-options-found": - "Ingen alternativer tilgjengelig på listen. Vurder å endre filteret.", - }; - - case "dk": - return { - "cannot-be-loaded": "Kan ikke indlæses", - "no-options-available": "Ingen muligheder tilgængelige.", - "click-to-load-options": "Klik for at indlæse muligheder.", - "select-an-option": "Vælg en mulighed", - "summary-text": { - zero: "Ingen indlæg blev valgt", - one: '<span class="monster-badge-primary-pill">1</span> indlæg blev valgt', - other: - '<span class="monster-badge-primary-pill">${count}</span> indlæg blev valgt', - }, - "no-options": - "Desværre er der ingen muligheder tilgængelige på listen.", - "no-options-found": - "Ingen muligheder tilgængelige på listen. Overvej at ændre filteret.", - }; - case "sw": - return { - "cannot-be-loaded": "Kan inte laddas", - "no-options-available": "Inga alternativ tillgängliga.", - "click-to-load-options": "Klicka för att ladda alternativ.", - "select-an-option": "Välj ett alternativ", - "summary-text": { - zero: "Inga poster valdes", - one: '<span class="monster-badge-primary-pill">1</span> post valdes', - other: - '<span class="monster-badge-primary-pill">${count}</span> poster valdes', - }, - "no-options": "Tyvärr finns det inga alternativ tillgängliga i listan.", - "no-options-found": - "Inga alternativ finns tillgängliga i listan. Överväg att modifiera filtret.", - }; - - default: - case "en": - return { - "cannot-be-loaded": "Cannot be loaded", - "no-options-available": "No options available.", - "click-to-load-options": "Click to load options.", - "select-an-option": "Select an option", - "summary-text": { - zero: "No entries were selected", - one: '<span class="monster-badge-primary-pill">1</span> entry was selected', - other: - '<span class="monster-badge-primary-pill">${count}</span> entries were selected', - }, - "no-options": - "Unfortunately, there are no options available in the list.", - "no-options-found": - "No options are available in the list. Please consider modifying the filter.", - }; - } + const locale = getLocaleOfDocument(); + switch (locale.language) { + case "de": + return { + "cannot-be-loaded": "Kann nicht geladen werden", + "no-options-available": "Keine Optionen verfügbar.", + "click-to-load-options": "Klicken, um Optionen zu laden.", + "select-an-option": "Wähle eine Option", + "summary-text": { + zero: "Keine Einträge ausgewählt", + one: '<span class="monster-badge-primary-pill">1</span> Eintrag ausgewählt', + other: + '<span class="monster-badge-primary-pill">${count}</span> Einträge ausgewählt', + }, + "no-options": "Leider gibt es keine Optionen in der Liste.", + "no-options-found": + "Keine Optionen in der Liste verfügbar. Bitte ändern Sie den Filter.", + }; + case "fr": + return { + "cannot-be-loaded": "Impossible de charger", + "no-options-available": "Aucune option disponible.", + "click-to-load-options": "Cliquez pour charger les options.", + "select-an-option": "Sélectionnez une option", + "summary-text": { + zero: "Aucune entrée sélectionnée", + one: '<span class="monster-badge-primary-pill">1</span> entrée sélectionnée', + other: + '<span class="monster-badge-primary-pill">${count}</span> entrées sélectionnées', + }, + "no-options": + "Malheureusement, il n'y a pas d'options disponibles dans la liste.", + "no-options-found": + "Aucune option disponible dans la liste. Veuillez modifier le filtre.", + }; + + case "sp": + return { + "cannot-be-loaded": "No se puede cargar", + "no-options-available": "No hay opciones disponibles.", + "click-to-load-options": "Haga clic para cargar opciones.", + "select-an-option": "Seleccione una opción", + "summary-text": { + zero: "No se seleccionaron entradas", + one: '<span class="monster-badge-primary-pill">1</span> entrada seleccionada', + other: + '<span class="monster-badge-primary-pill">${count}</span> entradas seleccionadas', + }, + "no-options": + "Desafortunadamente, no hay opciones disponibles en la lista.", + "no-options-found": + "No hay opciones disponibles en la lista. Considere modificar el filtro.", + }; + case "it": + return { + "cannot-be-loaded": "Non può essere caricato", + "no-options-available": "Nessuna opzione disponibile.", + "click-to-load-options": "Clicca per caricare le opzioni.", + "select-an-option": "Seleziona un'opzione", + "summary-text": { + zero: "Nessuna voce selezionata", + one: '<span class="monster-badge-primary-pill">1</span> voce selezionata', + other: + '<span class="monster-badge-primary-pill">${count}</span> voci selezionate', + }, + "no-options": "Purtroppo, non ci sono opzioni disponibili nella lista.", + "no-options-found": + "Nessuna opzione disponibile nella lista. Si prega di modificare il filtro.", + }; + case "pl": + return { + "cannot-be-loaded": "Nie można załadować", + "no-options-available": "Brak dostępnych opcji.", + "click-to-load-options": "Kliknij, aby załadować opcje.", + "select-an-option": "Wybierz opcję", + "summary-text": { + zero: "Nie wybrano żadnych wpisów", + one: '<span class="monster-badge-primary-pill">1</span> wpis został wybrany', + other: + '<span class="monster-badge-primary-pill">${count}</span> wpisy zostały wybrane', + }, + "no-options": "Niestety, nie ma dostępnych opcji na liście.", + "no-options-found": + "Brak dostępnych opcji na liście. Rozważ zmianę filtra.", + }; + case "no": + return { + "cannot-be-loaded": "Kan ikke lastes", + "no-options-available": "Ingen alternativer tilgjengelig.", + "click-to-load-options": "Klikk for å laste alternativer.", + "select-an-option": "Velg et alternativ", + "summary-text": { + zero: "Ingen oppføringer ble valgt", + one: '<span class="monster-badge-primary-pill">1</span> oppføring valgt', + other: + '<span class="monster-badge-primary-pill">${count}</span> oppføringer valgt', + }, + "no-options": + "Dessverre er det ingen alternativer tilgjengelig i listen.", + "no-options-found": + "Ingen alternativer tilgjengelig på listen. Vurder å endre filteret.", + }; + + case "dk": + return { + "cannot-be-loaded": "Kan ikke indlæses", + "no-options-available": "Ingen muligheder tilgængelige.", + "click-to-load-options": "Klik for at indlæse muligheder.", + "select-an-option": "Vælg en mulighed", + "summary-text": { + zero: "Ingen indlæg blev valgt", + one: '<span class="monster-badge-primary-pill">1</span> indlæg blev valgt', + other: + '<span class="monster-badge-primary-pill">${count}</span> indlæg blev valgt', + }, + "no-options": + "Desværre er der ingen muligheder tilgængelige på listen.", + "no-options-found": + "Ingen muligheder tilgængelige på listen. Overvej at ændre filteret.", + }; + case "sw": + return { + "cannot-be-loaded": "Kan inte laddas", + "no-options-available": "Inga alternativ tillgängliga.", + "click-to-load-options": "Klicka för att ladda alternativ.", + "select-an-option": "Välj ett alternativ", + "summary-text": { + zero: "Inga poster valdes", + one: '<span class="monster-badge-primary-pill">1</span> post valdes', + other: + '<span class="monster-badge-primary-pill">${count}</span> poster valdes', + }, + "no-options": "Tyvärr finns det inga alternativ tillgängliga i listan.", + "no-options-found": + "Inga alternativ finns tillgängliga i listan. Överväg att modifiera filtret.", + }; + + default: + case "en": + return { + "cannot-be-loaded": "Cannot be loaded", + "no-options-available": "No options available.", + "click-to-load-options": "Click to load options.", + "select-an-option": "Select an option", + "summary-text": { + zero: "No entries were selected", + one: '<span class="monster-badge-primary-pill">1</span> entry was selected', + other: + '<span class="monster-badge-primary-pill">${count}</span> entries were selected', + }, + "no-options": + "Unfortunately, there are no options available in the list.", + "no-options-found": + "No options are available in the list. Please consider modifying the filter.", + }; + } } /** * @private */ function lookupSelection() { - const self = this; - - setTimeout(() => { - const selection = self.getOption("selection"); - if (selection.length === 0) { - return; - } - - if (self[isLoadingSymbol] === true) { - return; - } - - if (self[lazyLoadDoneSymbol] === true) { - return; - } - - let url = self.getOption("url"); - let lookupUrl = self.getOption("lookup.url"); - if (lookupUrl !== null) { - url = lookupUrl; - } - - if (this.getOption("lookup.grouping") === true) { - filterFromRemoteByValue - .call( - self, - url, - selection.map((s) => s?.["value"]), - ) - .catch((e) => { - addErrorAttribute(self, e); - }); - return; - } - - for (const s of selection) { - if (s?.["value"]) { - filterFromRemoteByValue.call(self, url, s?.["value"]).catch((e) => { - addErrorAttribute(self, e); - }); - } - } - }, 100); + const self = this; + + setTimeout(() => { + const selection = self.getOption("selection"); + if (selection.length === 0) { + return; + } + + if (self[isLoadingSymbol] === true) { + return; + } + + if (self[lazyLoadDoneSymbol] === true) { + return; + } + + let url = self.getOption("url"); + let lookupUrl = self.getOption("lookup.url"); + if (lookupUrl !== null) { + url = lookupUrl; + } + + if (this.getOption("lookup.grouping") === true) { + filterFromRemoteByValue + .call( + self, + url, + selection.map((s) => s?.["value"]), + ) + .catch((e) => { + addErrorAttribute(self, e); + }); + return; + } + + for (const s of selection) { + if (s?.["value"]) { + filterFromRemoteByValue.call(self, url, s?.["value"]).catch((e) => { + addErrorAttribute(self, e); + }); + } + } + }, 100); } function fetchIt(url, controlOptions) { - if (url instanceof URL) { - url = url.toString(); - } - - if (url !== undefined && url !== null) { - url = validateString(url); - } else { - url = this.getOption("url"); - if (url === null) { - return Promise.reject(new Error("No url defined")); - } - } - - return new Promise((resolve, reject) => { - setStatusOrRemoveBadges.call(this, "loading"); - - new Processing(10, () => { - fetchData - .call(this, url) - .then((map) => { - if ( - isObject(map) || - isArray(map) || - map instanceof Set || - map instanceof Map - ) { - try { - this.importOptions(map); - } catch (e) { - setStatusOrRemoveBadges.call(this, "error"); - reject(e); - return; - } - - this[lastFetchedDataSymbol] = map; - - let result; - const selection = this.getOption("selection"); - let newValue = []; - if (selection) { - newValue = selection; - } else if (this.hasAttribute("value")) { - newValue = this.getAttribute("value"); - } - - result = setSelection.call(this, newValue); - requestAnimationFrame(() => { - checkOptionState.call(this); - setStatusOrRemoveBadges.call(this, "closed"); - updatePopper.call(this); - resolve(result); - }); - - return; - } - - setStatusOrRemoveBadges.call(this, "error"); - reject(new Error("invalid response")); - }) - .catch((e) => { - setStatusOrRemoveBadges.call(this, "error"); - reject(e); - }); - }) - .run() - .catch((e) => { - setStatusOrRemoveBadges.call(this, "error"); - addErrorAttribute(this, e); - reject(e); - }); - }); + if (url instanceof URL) { + url = url.toString(); + } + + if (url !== undefined && url !== null) { + url = validateString(url); + } else { + url = this.getOption("url"); + if (url === null) { + return Promise.reject(new Error("No url defined")); + } + } + + return new Promise((resolve, reject) => { + setStatusOrRemoveBadges.call(this, "loading"); + + new Processing(10, () => { + fetchData + .call(this, url) + .then((map) => { + if ( + isObject(map) || + isArray(map) || + map instanceof Set || + map instanceof Map + ) { + try { + this.importOptions(map); + } catch (e) { + setStatusOrRemoveBadges.call(this, "error"); + reject(e); + return; + } + + this[lastFetchedDataSymbol] = map; + + let result; + const selection = this.getOption("selection"); + let newValue = []; + if (selection) { + newValue = selection; + } else if (this.hasAttribute("value")) { + newValue = this.getAttribute("value"); + } + + result = setSelection.call(this, newValue); + + requestAnimationFrame(() => { + checkOptionState.call(this); + setStatusOrRemoveBadges.call(this, "closed"); + updatePopper.call(this); + resolve(result); + }); + + return; + } + + setStatusOrRemoveBadges.call(this, "error"); + reject(new Error("invalid response")); + }) + .catch((e) => { + setStatusOrRemoveBadges.call(this, "error"); + reject(e); + }); + }) + .run() + .catch((e) => { + setStatusOrRemoveBadges.call(this, "error"); + addErrorAttribute(this, e); + reject(e); + }); + }); } /** @@ -1075,68 +1076,68 @@ function fetchIt(url, controlOptions) { * @return {object} */ function initOptionsFromArguments() { - const options = {}; - - const template = this.getAttribute("data-monster-selected-template"); - if (isString(template)) { - if (!options["templateMapping"]) options["templateMapping"] = {}; - - switch (template) { - case "summary": - case "default": - options["templateMapping"]["selected"] = getSummaryTemplate(); - break; - case "selected": - options["templateMapping"]["selected"] = getSelectionTemplate(); - break; - default: - addErrorAttribute(this, "invalid template, use summary or selected"); - } - } - - return options; + const options = {}; + + const template = this.getAttribute("data-monster-selected-template"); + if (isString(template)) { + if (!options["templateMapping"]) options["templateMapping"] = {}; + + switch (template) { + case "summary": + case "default": + options["templateMapping"]["selected"] = getSummaryTemplate(); + break; + case "selected": + options["templateMapping"]["selected"] = getSelectionTemplate(); + break; + default: + addErrorAttribute(this, "invalid template, use summary or selected"); + } + } + + return options; } /** * @private */ function attachResizeObserver() { - // against flickering - this[resizeObserverSymbol] = new ResizeObserver((entries) => { - if (this[timerCallbackSymbol] instanceof DeadMansSwitch) { - try { - this[timerCallbackSymbol].touch(); - return; - } catch (e) { - delete this[timerCallbackSymbol]; - } - } - - this[timerCallbackSymbol] = new DeadMansSwitch(200, () => { - updatePopper.call(this); - delete this[timerCallbackSymbol]; - }); - }); - - requestAnimationFrame(() => { - let parent = this.parentNode; - while (!(parent instanceof HTMLElement) && parent !== null) { - parent = parent.parentNode; - } - - if (parent instanceof HTMLElement) { - this[resizeObserverSymbol].observe(parent); - } - }); + // against flickering + this[resizeObserverSymbol] = new ResizeObserver((entries) => { + if (this[timerCallbackSymbol] instanceof DeadMansSwitch) { + try { + this[timerCallbackSymbol].touch(); + return; + } catch (e) { + delete this[timerCallbackSymbol]; + } + } + + this[timerCallbackSymbol] = new DeadMansSwitch(200, () => { + updatePopper.call(this); + delete this[timerCallbackSymbol]; + }); + }); + + + let parent = this.parentNode; + while (!(parent instanceof HTMLElement) && parent !== null) { + parent = parent.parentNode; + } + + if (parent instanceof HTMLElement) { + this[resizeObserverSymbol].observe(parent); + } + } /** * @private */ function disconnectResizeObserver() { - if (this[resizeObserverSymbol] instanceof ResizeObserver) { - this[resizeObserverSymbol].disconnect(); - } + if (this[resizeObserverSymbol] instanceof ResizeObserver) { + this[resizeObserverSymbol].disconnect(); + } } /** @@ -1144,7 +1145,7 @@ function disconnectResizeObserver() { * @returns {string} */ function getSelectionTemplate() { - return `<div data-monster-role="selection" part="selection" + return `<div data-monster-role="selection" part="selection" data-monster-insert="selection path:selection" role="search" ><input type="text" role="searchbox" part="inline-filter" name="inline-filter" @@ -1160,7 +1161,7 @@ function getSelectionTemplate() { * @returns {string} */ function getSummaryTemplate() { - return `<div data-monster-role="selection" role="search" part="summary"> + return `<div data-monster-role="selection" role="search" part="summary"> <input type="text" role="searchbox" part="inline-filter" name="inline-filter" data-monster-role="filter" @@ -1176,35 +1177,35 @@ function getSummaryTemplate() { * @private */ function parseSlotsToOptions() { - let options = this.getOption("options"); - if (!isIterable(options)) { - options = []; - } - - let counter = 1; - getSlottedElements.call(this, "div").forEach((node) => { - let value = (counter++).toString(); - let visibility = "visible"; - - if (node.hasAttribute("data-monster-value")) { - value = node.getAttribute("data-monster-value"); - } - - let label = node.outerHTML; - - if (node.style.display === "none") { - visibility = "hidden"; - } - - options.push({ - value, - label, - visibility, - }); - }); - - runAsOptionLengthChanged.call(this, options.length); - this.setOption("options", options); + let options = this.getOption("options"); + if (!isIterable(options)) { + options = []; + } + + let counter = 1; + getSlottedElements.call(this, "div").forEach((node) => { + let value = (counter++).toString(); + let visibility = "visible"; + + if (node.hasAttribute("data-monster-value")) { + value = node.getAttribute("data-monster-value"); + } + + let label = node.outerHTML; + + if (node.style.display === "none") { + visibility = "hidden"; + } + + options.push({ + value, + label, + visibility, + }); + }); + + runAsOptionLengthChanged.call(this, options.length); + this.setOption("options", options); } /** @@ -1214,39 +1215,39 @@ function parseSlotsToOptions() { * @param {int} targetLength */ function runAsOptionLengthChanged(targetLength) { - const self = this; - - if (!self[optionsElementSymbol]) { - return; - } - - const callback = function (mutationsList, observer) { - const run = false; - for (const mutation of mutationsList) { - if (mutation.type === "childList") { - const run = true; - break; - } - } - - if (run === true) { - const nodes = self[optionsElementSymbol].querySelectorAll( - `div[${ATTRIBUTE_ROLE}=option]`, - ); - - if (nodes.length === targetLength) { - checkOptionState.call(self); - observer.disconnect(); - } - } - }; - - const observer = new MutationObserver(callback); - observer.observe(self[optionsElementSymbol], { - attributes: false, - childList: true, - subtree: true, - }); + const self = this; + + if (!self[optionsElementSymbol]) { + return; + } + + const callback = function (mutationsList, observer) { + const run = false; + for (const mutation of mutationsList) { + if (mutation.type === "childList") { + const run = true; + break; + } + } + + if (run === true) { + const nodes = self[optionsElementSymbol].querySelectorAll( + `div[${ATTRIBUTE_ROLE}=option]`, + ); + + if (nodes.length === targetLength) { + checkOptionState.call(self); + observer.disconnect(); + } + } + }; + + const observer = new MutationObserver(callback); + observer.observe(self[optionsElementSymbol], { + attributes: false, + childList: true, + subtree: true, + }); } /** @@ -1255,38 +1256,38 @@ function runAsOptionLengthChanged(targetLength) { * @return {*} */ function buildSelectionLabel(value) { - const options = this.getOption("options"); - - for (let i = 0; i < options.length; i++) { - let o = options?.[i]; - let l, v, v2; - - if (this.getOption("features.useStrictValueComparison") === true) { - v = value; - } else { - v = `${value}`; - } - - if (isPrimitive(o) && o === value) { - return o; - } else if (!isObject(o)) { - continue; - } - - if (this.getOption("features.useStrictValueComparison") === true) { - l = o?.["label"]; - v2 = o?.["value"]; - } else { - l = `${o?.["label"]}`; - v2 = `${o?.["value"]}`; - } - - if (v2 === v) { - return l; - } - } - - return undefined; + const options = this.getOption("options"); + + for (let i = 0; i < options.length; i++) { + let o = options?.[i]; + let l, v, v2; + + if (this.getOption("features.useStrictValueComparison") === true) { + v = value; + } else { + v = `${value}`; + } + + if (isPrimitive(o) && o === value) { + return o; + } else if (!isObject(o)) { + continue; + } + + if (this.getOption("features.useStrictValueComparison") === true) { + l = o?.["label"]; + v2 = o?.["value"]; + } else { + l = `${o?.["label"]}`; + v2 = `${o?.["value"]}`; + } + + if (v2 === v) { + return l; + } + } + + return undefined; } /** @@ -1296,17 +1297,17 @@ function buildSelectionLabel(value) { * @throws {Error} no value found */ function getSelectionLabel(value) { - const callback = this.getOption("formatter.selection"); - if (isFunction(callback)) { - const label = callback.call(this, value); - if (isString(label)) return label; - } + const callback = this.getOption("formatter.selection"); + if (isFunction(callback)) { + const label = callback.call(this, value); + if (isString(label)) return label; + } - if (isString(value) || isInteger(value)) { - return `${value}`; - } + if (isString(value) || isInteger(value)) { + return `${value}`; + } - return this.getOption("labels.cannot-be-loaded", value); + return this.getOption("labels.cannot-be-loaded", value); } /** @@ -1314,25 +1315,25 @@ function getSelectionLabel(value) { * @param {Event} event */ function handleToggleKeyboardEvents(event) { - switch (event?.["code"]) { - case "Escape": - toggle.call(this); - event.preventDefault(); - break; - case "Space": - toggle.call(this); - event.preventDefault(); - break; - case "ArrowDown": - show.call(this); - activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); - event.preventDefault(); - break; - case "ArrowUp": - hide.call(this); - event.preventDefault(); - break; - } + switch (event?.["code"]) { + case "Escape": + toggle.call(this); + event.preventDefault(); + break; + case "Space": + toggle.call(this); + event.preventDefault(); + break; + case "ArrowDown": + show.call(this); + activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); + event.preventDefault(); + break; + case "ArrowUp": + hide.call(this); + event.preventDefault(); + break; + } } /** @@ -1342,32 +1343,28 @@ function handleToggleKeyboardEvents(event) { * @this CustomElement */ function initOptionObserver() { - const self = this; - - self.attachObserver( - new Observer(function () { - new Processing(() => { - try { - self.updateI18n(); - } catch (e) { - addErrorAttribute(self, e); - requestAnimationFrame(() => { - setStatusOrRemoveBadges.call(self, "error"); - }); - } - try { - areOptionsAvailableAndInit.call(self); - } catch (e) { - addErrorAttribute(self, e); - requestAnimationFrame(() => { - setStatusOrRemoveBadges.call(self, "error"); - }); - } - - setSummaryAndControlText.call(self); - }).run(); - }), - ); + const self = this; + + self.attachObserver( + new Observer(function () { + new Processing(() => { + try { + self.updateI18n(); + } catch (e) { + addErrorAttribute(self, e); + setStatusOrRemoveBadges.call(self, "error"); + } + try { + areOptionsAvailableAndInit.call(self); + } catch (e) { + addErrorAttribute(self, e); + setStatusOrRemoveBadges.call(self, "error"); + } + + setSummaryAndControlText.call(self); + }).run(); + }), + ); } /** @@ -1375,16 +1372,17 @@ function initOptionObserver() { * @returns {Translations} */ function getDefaultTranslation() { - const translation = new Translations("en").assignTranslations( - this.getOption("labels", {}), - ); + const translation = new Translations("en").assignTranslations( + this.getOption("labels", {}), + ); - try { - const doc = getDocumentTranslations(); - translation.locale = doc.locale; - } catch (e) {} + try { + const doc = getDocumentTranslations(); + translation.locale = doc.locale; + } catch (e) { + } - return translation; + return translation; } /** @@ -1392,36 +1390,36 @@ function getDefaultTranslation() { * @return {string|*} */ function setSummaryAndControlText() { - const translations = getDefaultTranslation.call(this); - const selections = this.getOption("selection"); - - const text = translations.getPluralRuleText( - "summary-text", - selections.length, - "", - ); - - const selectedText = new Formatter({ - count: String(selections.length), - }).format(text); - - this.setOption("messages.selected", selectedText); - - const current = this.getOption("messages.control"); - const msg = this.getOption("labels.select-an-option"); - - if ( - current === "" || - current === undefined || - current === msg || - current === null - ) { - if (selections.length === 0) { - this.setOption("messages.control", msg); - } else { - this.setOption("messages.control", ""); - } - } + const translations = getDefaultTranslation.call(this); + const selections = this.getOption("selection"); + + const text = translations.getPluralRuleText( + "summary-text", + selections.length, + "", + ); + + const selectedText = new Formatter({ + count: String(selections.length), + }).format(text); + + this.setOption("messages.selected", selectedText); + + const current = this.getOption("messages.control"); + const msg = this.getOption("labels.select-an-option"); + + if ( + current === "" || + current === undefined || + current === msg || + current === null + ) { + if (selections.length === 0) { + this.setOption("messages.control", msg); + } else { + this.setOption("messages.control", ""); + } + } } /** @@ -1429,9 +1427,9 @@ function setSummaryAndControlText() { * @return {NodeList} */ function getOptionElements() { - return this[optionsElementSymbol].querySelectorAll( - `[${ATTRIBUTE_ROLE}=option]`, - ); + return this[optionsElementSymbol].querySelectorAll( + `[${ATTRIBUTE_ROLE}=option]`, + ); } /** @@ -1455,75 +1453,75 @@ function getOptionElements() { * @private */ function calcAndSetOptionsDimension() { - const options = getOptionElements.call(this); - const container = this[optionsElementSymbol]; - if (!(container instanceof HTMLElement && options instanceof NodeList)) { - return; - } - - let visible = 0; - let optionHeight = 0; - const max = this.getOption("showMaxOptions", 10); - - let scrollFlag = false; - for (const [, option] of Object.entries(options)) { - const computedStyle = getGlobal().getComputedStyle(option); - if (computedStyle.display === "none") continue; - - let h = option.getBoundingClientRect().height; - h += parseInt(computedStyle.getPropertyValue("margin-top"), 10); - h += parseInt(computedStyle.getPropertyValue("margin-bottom"), 10); - optionHeight += h; - - visible++; - - if (visible > max) { - break; - } - } - - if (visible > max) { - visible = max; - scrollFlag = true; - } - - if (visible === 0) { - if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { - this.setOption( - "messages.emptyOptions", - this.getOption("labels.no-options-available"), - ); - } else { - this.setOption( - "messages.emptyOptions", - this.getOption("labels.no-options-found"), - ); - } - this[noOptionsAvailableElementSymbol].classList.remove("d-none"); - } else { - this[noOptionsAvailableElementSymbol].classList.add("d-none"); - } - - const styles = getGlobal().getComputedStyle(this[optionsElementSymbol]); - let padding = parseInt(styles.getPropertyValue("padding-top"), 10); - padding += parseInt(styles.getPropertyValue("padding-bottom"), 10); - - let margin = parseInt(styles.getPropertyValue("margin-top"), 10); - margin += parseInt(styles.getPropertyValue("margin-bottom"), 10); - - const containerHeight = optionHeight + padding + margin; - container.style.height = `${containerHeight}px`; - - if (scrollFlag === true) { - container.style.overflowY = "scroll"; - } else { - container.style.overflowY = "auto"; - } - - const domRect = this[controlElementSymbol].getBoundingClientRect(); - - this[popperElementSymbol].style.width = `${domRect.width}px`; - container.style.overflowX = "auto"; + const options = getOptionElements.call(this); + const container = this[optionsElementSymbol]; + if (!(container instanceof HTMLElement && options instanceof NodeList)) { + return; + } + + let visible = 0; + let optionHeight = 0; + const max = this.getOption("showMaxOptions", 10); + + let scrollFlag = false; + for (const [, option] of Object.entries(options)) { + const computedStyle = getGlobal().getComputedStyle(option); + if (computedStyle.display === "none") continue; + + let h = option.getBoundingClientRect().height; + h += parseInt(computedStyle.getPropertyValue("margin-top"), 10); + h += parseInt(computedStyle.getPropertyValue("margin-bottom"), 10); + optionHeight += h; + + visible++; + + if (visible > max) { + break; + } + } + + if (visible > max) { + visible = max; + scrollFlag = true; + } + + if (visible === 0) { + if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { + this.setOption( + "messages.emptyOptions", + this.getOption("labels.no-options-available"), + ); + } else { + this.setOption( + "messages.emptyOptions", + this.getOption("labels.no-options-found"), + ); + } + this[noOptionsAvailableElementSymbol].classList.remove("d-none"); + } else { + this[noOptionsAvailableElementSymbol].classList.add("d-none"); + } + + const styles = getGlobal().getComputedStyle(this[optionsElementSymbol]); + let padding = parseInt(styles.getPropertyValue("padding-top"), 10); + padding += parseInt(styles.getPropertyValue("padding-bottom"), 10); + + let margin = parseInt(styles.getPropertyValue("margin-top"), 10); + margin += parseInt(styles.getPropertyValue("margin-bottom"), 10); + + const containerHeight = optionHeight + padding + margin; + container.style.height = `${containerHeight}px`; + + if (scrollFlag === true) { + container.style.overflowY = "scroll"; + } else { + container.style.overflowY = "auto"; + } + + const domRect = this[controlElementSymbol].getBoundingClientRect(); + + this[popperElementSymbol].style.width = `${domRect.width}px`; + container.style.overflowX = "auto"; } /** @@ -1532,126 +1530,126 @@ function calcAndSetOptionsDimension() { * @throws {Error} no shadow-root is defined */ function activateCurrentOption(direction) { - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - let focused = this.shadowRoot.querySelector(`[${ATTRIBUTE_PREFIX}focused]`); - - if ( - !(focused instanceof HTMLElement) || - focused.matches("[data-monster-visibility=hidden]") - ) { - for (const [, e] of Object.entries( - this.shadowRoot.querySelectorAll(`[${ATTRIBUTE_ROLE}=option]`), - )) { - if (e.matches("[data-monster-visibility=visible]")) { - focused = e; - break; - } - } - } else { - if (direction === FOCUS_DIRECTION_DOWN) { - while (focused.nextSibling) { - focused = focused.nextSibling; - - if ( - focused instanceof HTMLElement && - focused.hasAttribute(ATTRIBUTE_ROLE) && - focused.getAttribute(ATTRIBUTE_ROLE) === "option" && - focused.matches("[data-monster-visibility=visible]") && - focused.matches(":not([data-monster-filtered=true])") - ) { - break; - } - } - } else { - let found = false; - while (focused.previousSibling) { - focused = focused.previousSibling; - if ( - focused instanceof HTMLElement && - focused.hasAttribute(ATTRIBUTE_ROLE) && - focused.getAttribute(ATTRIBUTE_ROLE) === "option" && - focused.matches("[data-monster-visibility=visible]") && - focused.matches(":not([data-monster-filtered=true])") - ) { - found = true; - break; - } - } - if (found === false) { - focusFilter.call(this); - } - } - } - - new Processing(() => { - if (focused instanceof HTMLElement) { - this.shadowRoot - .querySelectorAll(`[${ATTRIBUTE_PREFIX}focused]`) - .forEach((e) => { - e.removeAttribute(`${ATTRIBUTE_PREFIX}focused`); - }); - - focused.focus(); - focused.setAttribute(`${ATTRIBUTE_PREFIX}focused`, true); - } - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + let focused = this.shadowRoot.querySelector(`[${ATTRIBUTE_PREFIX}focused]`); + + if ( + !(focused instanceof HTMLElement) || + focused.matches("[data-monster-visibility=hidden]") + ) { + for (const [, e] of Object.entries( + this.shadowRoot.querySelectorAll(`[${ATTRIBUTE_ROLE}=option]`), + )) { + if (e.matches("[data-monster-visibility=visible]")) { + focused = e; + break; + } + } + } else { + if (direction === FOCUS_DIRECTION_DOWN) { + while (focused.nextSibling) { + focused = focused.nextSibling; + + if ( + focused instanceof HTMLElement && + focused.hasAttribute(ATTRIBUTE_ROLE) && + focused.getAttribute(ATTRIBUTE_ROLE) === "option" && + focused.matches("[data-monster-visibility=visible]") && + focused.matches(":not([data-monster-filtered=true])") + ) { + break; + } + } + } else { + let found = false; + while (focused.previousSibling) { + focused = focused.previousSibling; + if ( + focused instanceof HTMLElement && + focused.hasAttribute(ATTRIBUTE_ROLE) && + focused.getAttribute(ATTRIBUTE_ROLE) === "option" && + focused.matches("[data-monster-visibility=visible]") && + focused.matches(":not([data-monster-filtered=true])") + ) { + found = true; + break; + } + } + if (found === false) { + focusFilter.call(this); + } + } + } + + new Processing(() => { + if (focused instanceof HTMLElement) { + this.shadowRoot + .querySelectorAll(`[${ATTRIBUTE_PREFIX}focused]`) + .forEach((e) => { + e.removeAttribute(`${ATTRIBUTE_PREFIX}focused`); + }); + + focused.focus(); + focused.setAttribute(`${ATTRIBUTE_PREFIX}focused`, true); + } + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); } /** * @private */ function filterOptions() { - new Processing(() => { - let filterValue; - - switch (this.getOption("filter.position")) { - case FILTER_POSITION_INLINE: - if (this[inlineFilterElementSymbol] instanceof HTMLElement) { - filterValue = this[inlineFilterElementSymbol].value.toLowerCase(); - } else { - return; - } - - break; - case FILTER_POSITION_POPPER: - default: - if (this[popperFilterElementSymbol] instanceof HTMLInputElement) { - filterValue = this[popperFilterElementSymbol].value.toLowerCase(); - } else { - return; - } - } - - const options = this.getOption("options"); - for (const [i, option] of Object.entries(options)) { - if (option.label.toLowerCase().indexOf(filterValue) === -1) { - this.setOption(`options.${i}.filtered`, "true"); - } else { - this.setOption(`options.${i}.filtered`, undefined); - } - } - }) - .run() - .then(() => { - new Processing(100, () => { - calcAndSetOptionsDimension.call(this); - focusFilter.call(this); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - }) - .catch((e) => { - addErrorAttribute(this, e); - }); + new Processing(() => { + let filterValue; + + switch (this.getOption("filter.position")) { + case FILTER_POSITION_INLINE: + if (this[inlineFilterElementSymbol] instanceof HTMLElement) { + filterValue = this[inlineFilterElementSymbol].value.toLowerCase(); + } else { + return; + } + + break; + case FILTER_POSITION_POPPER: + default: + if (this[popperFilterElementSymbol] instanceof HTMLInputElement) { + filterValue = this[popperFilterElementSymbol].value.toLowerCase(); + } else { + return; + } + } + + const options = this.getOption("options"); + for (const [i, option] of Object.entries(options)) { + if (option.label.toLowerCase().indexOf(filterValue) === -1) { + this.setOption(`options.${i}.filtered`, "true"); + } else { + this.setOption(`options.${i}.filtered`, undefined); + } + } + }) + .run() + .then(() => { + new Processing(100, () => { + calcAndSetOptionsDimension.call(this); + focusFilter.call(this); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + }) + .catch((e) => { + addErrorAttribute(this, e); + }); } /** @@ -1659,37 +1657,37 @@ function filterOptions() { * @param {Event} event */ function handleFilterKeyboardEvents(event) { - const shiftKey = event?.["shiftKey"]; - - switch (event?.["code"]) { - case "Tab": - activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); - event.preventDefault(); - break; - case "Escape": - toggle.call(this); - event.preventDefault(); - break; - case "Tab" && shiftKey === true: - case "ArrowUp": - activateCurrentOption.call(this, FOCUS_DIRECTION_UP); - event.preventDefault(); - break; - case "Tab" && !shiftKey: - case "ArrowDown": - activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); - event.preventDefault(); - break; - default: - if ( - this.getOption("features.lazyLoad") === true && - this[lazyLoadDoneSymbol] !== true - ) { - this.click(); - } - - handleFilterKeyEvents.call(this); - } + const shiftKey = event?.["shiftKey"]; + + switch (event?.["code"]) { + case "Tab": + activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); + event.preventDefault(); + break; + case "Escape": + toggle.call(this); + event.preventDefault(); + break; + case "Tab" && shiftKey === true: + case "ArrowUp": + activateCurrentOption.call(this, FOCUS_DIRECTION_UP); + event.preventDefault(); + break; + case "Tab" && !shiftKey: + case "ArrowDown": + activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); + event.preventDefault(); + break; + default: + if ( + this.getOption("features.lazyLoad") === true && + this[lazyLoadDoneSymbol] !== true + ) { + this.click(); + } + + handleFilterKeyEvents.call(this); + } } /** @@ -1703,86 +1701,86 @@ function handleFilterKeyboardEvents(event) { * @return {void} This method does not return anything. */ function handleFilterKeyEvents() { - if (this[keyFilterEventSymbol] instanceof DeadMansSwitch) { - try { - this[keyFilterEventSymbol].touch(); - return; - } catch (e) { - delete this[keyFilterEventSymbol]; - } - } - - this[keyFilterEventSymbol] = new DeadMansSwitch(200, () => { - if (getFilterMode.call(this) !== FILTER_MODE_REMOTE) { - filterOptions.call(this); - } else { - filterFromRemote.call(this).catch((e) => { - addErrorAttribute(this, e); - }); - } - - delete this[keyFilterEventSymbol]; - }); + if (this[keyFilterEventSymbol] instanceof DeadMansSwitch) { + try { + this[keyFilterEventSymbol].touch(); + return; + } catch (e) { + delete this[keyFilterEventSymbol]; + } + } + + this[keyFilterEventSymbol] = new DeadMansSwitch(200, () => { + if (getFilterMode.call(this) !== FILTER_MODE_REMOTE) { + filterOptions.call(this); + } else { + filterFromRemote.call(this).catch((e) => { + addErrorAttribute(this, e); + }); + } + + delete this[keyFilterEventSymbol]; + }); } /** * @private */ function filterFromRemote() { - if ( - !(this[inlineFilterElementSymbol] instanceof HTMLElement) && - !(this[popperFilterElementSymbol] instanceof HTMLElement) - ) { - return; - } - - show.call(this); - - const url = this.getOption("url"); - if (!url) { - addErrorAttribute(this, "Missing URL for Remote Filter."); - return; - } - - let filterValue; - - switch (this.getOption("filter.position")) { - case FILTER_POSITION_INLINE: - if (this[inlineFilterElementSymbol] instanceof HTMLElement) { - filterValue = this[inlineFilterElementSymbol].value.toLowerCase(); - } - - break; - case FILTER_POSITION_POPPER: - default: - if (this[popperFilterElementSymbol] instanceof HTMLInputElement) { - filterValue = this[popperFilterElementSymbol].value.toLowerCase(); - } - } - - return filterFromRemoteByValue.call(this, url, filterValue); + if ( + !(this[inlineFilterElementSymbol] instanceof HTMLElement) && + !(this[popperFilterElementSymbol] instanceof HTMLElement) + ) { + return; + } + + show.call(this); + + const url = this.getOption("url"); + if (!url) { + addErrorAttribute(this, "Missing URL for Remote Filter."); + return; + } + + let filterValue; + + switch (this.getOption("filter.position")) { + case FILTER_POSITION_INLINE: + if (this[inlineFilterElementSymbol] instanceof HTMLElement) { + filterValue = this[inlineFilterElementSymbol].value.toLowerCase(); + } + + break; + case FILTER_POSITION_POPPER: + default: + if (this[popperFilterElementSymbol] instanceof HTMLInputElement) { + filterValue = this[popperFilterElementSymbol].value.toLowerCase(); + } + } + + return filterFromRemoteByValue.call(this, url, filterValue); } function formatURL(url, value) { - if (value === undefined || value === null || value === "") { - value = this.getOption("filter.defaultValue"); - if (value === undefined || value === null || value === "") { - value = disabledRequestMarker.toString(); - } - } - - const formatter = new Formatter({ filter: encodeURI(value) }); - const openMarker = this.getOption("filter.marker.open"); - let closeMarker = this.getOption("filter.marker.close"); - if (!closeMarker) { - closeMarker = openMarker; - } - - if (openMarker && closeMarker) { - formatter.setMarker(openMarker, closeMarker); - } - - return formatter.format(url); + if (value === undefined || value === null || value === "") { + value = this.getOption("filter.defaultValue"); + if (value === undefined || value === null || value === "") { + value = disabledRequestMarker.toString(); + } + } + + const formatter = new Formatter({filter: encodeURI(value)}); + const openMarker = this.getOption("filter.marker.open"); + let closeMarker = this.getOption("filter.marker.close"); + if (!closeMarker) { + closeMarker = openMarker; + } + + if (openMarker && closeMarker) { + formatter.setMarker(openMarker, closeMarker); + } + + return formatter.format(url); } /** @@ -1792,28 +1790,28 @@ function formatURL(url, value) { * @returns {Promise<unknown>} */ function filterFromRemoteByValue(optionUrl, value) { - return new Processing(() => { - let url = formatURL.call(this, optionUrl, value); - if (url.indexOf(disabledRequestMarker.toString()) !== -1) { - return; - } - - fetchIt - .call(this, url, { - disableHiding: true, - }) - .then(() => { - checkOptionState.call(this); - show.call(this); - }) - .catch((e) => { - throw e; - }); - }) - .run() - .catch((e) => { - throw e; - }); + return new Processing(() => { + let url = formatURL.call(this, optionUrl, value); + if (url.indexOf(disabledRequestMarker.toString()) !== -1) { + return; + } + + fetchIt + .call(this, url, { + disableHiding: true, + }) + .then(() => { + checkOptionState.call(this); + show.call(this); + }) + .catch((e) => { + throw e; + }); + }) + .run() + .catch((e) => { + throw e; + }); } /** @@ -1821,50 +1819,50 @@ function filterFromRemoteByValue(optionUrl, value) { * @private */ function handleOptionKeyboardEvents(event) { - const shiftKey = event?.["shiftKey"]; - - switch (event?.["code"]) { - case "Escape": - toggle.call(this); - event.preventDefault(); - break; - case "Enter": - case "Space": - const path = event.composedPath(); - const element = path?.[0]; - if (element instanceof HTMLElement) { - const input = element.getElementsByTagName("input"); - if (!input) { - return; - } - fireEvent(input, "click"); - } - event.preventDefault(); - break; - - case "Tab" && shiftKey === true: - case "ArrowUp": - activateCurrentOption.call(this, FOCUS_DIRECTION_UP); - event.preventDefault(); - break; - - case "Tab" && !shiftKey: - case "ArrowLeft": - case "ArrowRight": - // handled by tree select - break; - case "ArrowDown": - activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); - event.preventDefault(); - break; - default: - const p = event.composedPath(); - if (p?.[0] instanceof HTMLInputElement) { - return; - } - focusFilter.call(this); - break; - } + const shiftKey = event?.["shiftKey"]; + + switch (event?.["code"]) { + case "Escape": + toggle.call(this); + event.preventDefault(); + break; + case "Enter": + case "Space": + const path = event.composedPath(); + const element = path?.[0]; + if (element instanceof HTMLElement) { + const input = element.getElementsByTagName("input"); + if (!input) { + return; + } + fireEvent(input, "click"); + } + event.preventDefault(); + break; + + case "Tab" && shiftKey === true: + case "ArrowUp": + activateCurrentOption.call(this, FOCUS_DIRECTION_UP); + event.preventDefault(); + break; + + case "Tab" && !shiftKey: + case "ArrowLeft": + case "ArrowRight": + // handled by tree select + break; + case "ArrowDown": + activateCurrentOption.call(this, FOCUS_DIRECTION_DOWN); + event.preventDefault(); + break; + default: + const p = event.composedPath(); + if (p?.[0] instanceof HTMLInputElement) { + return; + } + focusFilter.call(this); + break; + } } /** @@ -1872,33 +1870,33 @@ function handleOptionKeyboardEvents(event) { * @return {string} */ function getFilterMode() { - switch (this.getOption("filter.mode")) { - case FILTER_MODE_OPTIONS: - return FILTER_MODE_OPTIONS; - case FILTER_MODE_REMOTE: - return FILTER_MODE_REMOTE; - default: - return FILTER_MODE_DISABLED; - } + switch (this.getOption("filter.mode")) { + case FILTER_MODE_OPTIONS: + return FILTER_MODE_OPTIONS; + case FILTER_MODE_REMOTE: + return FILTER_MODE_REMOTE; + default: + return FILTER_MODE_DISABLED; + } } /** * @private */ function blurFilter() { - if (!(this[inlineFilterElementSymbol] instanceof HTMLElement)) { - return; - } + if (!(this[inlineFilterElementSymbol] instanceof HTMLElement)) { + return; + } - if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { - return; - } + if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { + return; + } - this[popperFilterContainerElementSymbol].classList.remove("active"); - this[popperFilterContainerElementSymbol].blur(); + this[popperFilterContainerElementSymbol].classList.remove("active"); + this[popperFilterContainerElementSymbol].blur(); - this[inlineFilterElementSymbol].classList.remove("active"); - this[inlineFilterElementSymbol].blur(); + this[inlineFilterElementSymbol].classList.remove("active"); + this[inlineFilterElementSymbol].blur(); } /** @@ -1906,25 +1904,25 @@ function blurFilter() { * @param focusOptions */ function focusPopperFilter(focusOptions) { - this[popperFilterContainerElementSymbol].classList.remove("d-none"); - this[popperFilterElementSymbol].classList.add("active"); - this[inlineFilterElementSymbol].classList.remove("active"); - this[inlineFilterElementSymbol].classList.add("d-none"); - - if (!(this[popperFilterElementSymbol] instanceof HTMLElement)) { - addErrorAttribute(this, "Missing Popper Filter Element."); - return; - } - - // visibility is set to visible, because focus() does not work on invisible elements - // and the class definition is assigned later in the processing - setTimeout(() => { - if (focusOptions === undefined || focusOptions === null) { - this[popperFilterElementSymbol].focus(); - } else { - this[popperFilterElementSymbol].focus(focusOptions); - } - }, 100); + this[popperFilterContainerElementSymbol].classList.remove("d-none"); + this[popperFilterElementSymbol].classList.add("active"); + this[inlineFilterElementSymbol].classList.remove("active"); + this[inlineFilterElementSymbol].classList.add("d-none"); + + if (!(this[popperFilterElementSymbol] instanceof HTMLElement)) { + addErrorAttribute(this, "Missing Popper Filter Element."); + return; + } + + // visibility is set to visible, because focus() does not work on invisible elements + // and the class definition is assigned later in the processing + setTimeout(() => { + if (focusOptions === undefined || focusOptions === null) { + this[popperFilterElementSymbol].focus(); + } else { + this[popperFilterElementSymbol].focus(focusOptions); + } + }, 100); } /** @@ -1932,44 +1930,44 @@ function focusPopperFilter(focusOptions) { * @param focusOptions */ function focusInlineFilter(focusOptions) { - const options = this.getOption("options"); - if ( - (!isArray(options) || options.length === 0) && - getFilterMode.call(this) !== FILTER_MODE_REMOTE - ) { - return; - } - - this[popperFilterContainerElementSymbol].classList.add("d-none"); - this[inlineFilterElementSymbol].classList.add("active"); - this[inlineFilterElementSymbol].classList.remove("d-none"); - - // visibility is set to visible, because focus() does not work on invisible elements - // and the class definition is assigned later in the processing - setTimeout(() => { - if (focusOptions === undefined || focusOptions === null) { - this[inlineFilterElementSymbol].focus(); - } else { - this[inlineFilterElementSymbol].focus(focusOptions); - } - }, 100); + const options = this.getOption("options"); + if ( + (!isArray(options) || options.length === 0) && + getFilterMode.call(this) !== FILTER_MODE_REMOTE + ) { + return; + } + + this[popperFilterContainerElementSymbol].classList.add("d-none"); + this[inlineFilterElementSymbol].classList.add("active"); + this[inlineFilterElementSymbol].classList.remove("d-none"); + + // visibility is set to visible, because focus() does not work on invisible elements + // and the class definition is assigned later in the processing + setTimeout(() => { + if (focusOptions === undefined || focusOptions === null) { + this[inlineFilterElementSymbol].focus(); + } else { + this[inlineFilterElementSymbol].focus(focusOptions); + } + }, 100); } /** * @private */ function focusFilter(focusOptions) { - if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { - this[popperFilterContainerElementSymbol].classList.add("d-none"); - this[inlineFilterElementSymbol].classList.add("d-none"); - return; - } + if (getFilterMode.call(this) === FILTER_MODE_DISABLED) { + this[popperFilterContainerElementSymbol].classList.add("d-none"); + this[inlineFilterElementSymbol].classList.add("d-none"); + return; + } - if (this.getOption("filter.position") === FILTER_POSITION_INLINE) { - return focusInlineFilter.call(this, focusOptions); - } + if (this.getOption("filter.position") === FILTER_POSITION_INLINE) { + return focusInlineFilter.call(this, focusOptions); + } - return focusPopperFilter.call(this, focusOptions); + return focusPopperFilter.call(this, focusOptions); } /** @@ -1979,39 +1977,40 @@ function focusFilter(focusOptions) { * @throws {Error} unsupported type */ function gatherState() { - const type = this.getOption("type"); - if (["radio", "checkbox"].indexOf(type) === -1) { - throw new Error("unsupported type"); - } - - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - const selection = []; - const elements = this.shadowRoot.querySelectorAll( - `input[type=${type}]:checked`, - ); - - for (const e of elements) { - selection.push({ - label: getSelectionLabel.call(this, e.value), - value: e.value, - }); - } - - setSelection - .call(this, selection) - .then(() => {}) - .catch((e) => { - addErrorAttribute(this, e); - }); - - if (this.getOption("features.closeOnSelect") === true) { - toggle.call(this); - } - - return this; + const type = this.getOption("type"); + if (["radio", "checkbox"].indexOf(type) === -1) { + throw new Error("unsupported type"); + } + + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + const selection = []; + const elements = this.shadowRoot.querySelectorAll( + `input[type=${type}]:checked`, + ); + + for (const e of elements) { + selection.push({ + label: getSelectionLabel.call(this, e.value), + value: e.value, + }); + } + + setSelection + .call(this, selection) + .then(() => { + }) + .catch((e) => { + addErrorAttribute(this, e); + }); + + if (this.getOption("features.closeOnSelect") === true) { + toggle.call(this); + } + + return this; } /** @@ -2020,120 +2019,121 @@ function gatherState() { * @throws {Error} unsupported type */ function clearSelection() { - const type = this.getOption("type"); - if (["radio", "checkbox"].indexOf(type) === -1) { - throw new Error("unsupported type"); - } - - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - setSelection - .call(this, []) - .then(() => {}) - .catch((e) => { - addErrorAttribute(this, e); - }); + const type = this.getOption("type"); + if (["radio", "checkbox"].indexOf(type) === -1) { + throw new Error("unsupported type"); + } + + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + setSelection + .call(this, []) + .then(() => { + }) + .catch((e) => { + addErrorAttribute(this, e); + }); } /** * @private */ function areOptionsAvailableAndInit() { - // prevent multiple calls - if (this[areOptionsAvailableAndInitSymbol] === undefined) { - this[areOptionsAvailableAndInitSymbol] = 0; - } - - if (this[areOptionsAvailableAndInitSymbol] > 0) { - this[areOptionsAvailableAndInitSymbol]--; - return true; - } - - this[areOptionsAvailableAndInitSymbol]++; - - const options = this.getOption("options"); - - if ( - options === undefined || - options === null || - (isArray(options) && options.length === 0) - ) { - setStatusOrRemoveBadges.call(this, "empty"); - - // hide.call(this); - - let msg = this.getOption("labels.no-options-available"); - - if ( - this.getOption("url") !== null && - this.getOption("features.lazyLoad") === true && - this[lazyLoadDoneSymbol] !== true - ) { - msg = this.getOption("labels.click-to-load-options"); - } - - this.setOption("messages.control", msg); - this.setOption("messages.summary", ""); - - if (this.getOption("features.emptyValueIfNoOptions") === true) { - this.value = ""; - } - addErrorAttribute(this, "No options available."); - return false; - } - - const selections = this.getOption("selection"); - if ( - selections === undefined || - selections === null || - selections.length === 0 - ) { - this.setOption( - "messages.control", - this.getOption("labels.select-an-option"), - ); - } else { - this.setOption("messages.control", ""); - } - - this.setOption("messages.summary", setSummaryAndControlText.call(this)); - - let updated = false; - let valueCounter = 1; - for (const option of options) { - if (option?.visibility === undefined) { - option.visibility = "visible"; - updated = true; - } - - if (option?.value === undefined && option?.label === undefined) { - option.value = `${valueCounter++}`; - option.label = option.value; - updated = true; - continue; - } - - if (option?.value === undefined) { - option.value = option.label; - updated = true; - } - - if (option?.label === undefined) { - option.label = option.value; - updated = true; - } - } - - if (updated) { - this.setOption("options", options); - } - - setStatusOrRemoveBadges.call(this); - - removeErrorAttribute(this, "No options available."); - return true; + // prevent multiple calls + if (this[areOptionsAvailableAndInitSymbol] === undefined) { + this[areOptionsAvailableAndInitSymbol] = 0; + } + + if (this[areOptionsAvailableAndInitSymbol] > 0) { + this[areOptionsAvailableAndInitSymbol]--; + return true; + } + + this[areOptionsAvailableAndInitSymbol]++; + + const options = this.getOption("options"); + + if ( + options === undefined || + options === null || + (isArray(options) && options.length === 0) + ) { + setStatusOrRemoveBadges.call(this, "empty"); + + // hide.call(this); + + let msg = this.getOption("labels.no-options-available"); + + if ( + this.getOption("url") !== null && + this.getOption("features.lazyLoad") === true && + this[lazyLoadDoneSymbol] !== true + ) { + msg = this.getOption("labels.click-to-load-options"); + } + + this.setOption("messages.control", msg); + this.setOption("messages.summary", ""); + + if (this.getOption("features.emptyValueIfNoOptions") === true) { + this.value = ""; + } + addErrorAttribute(this, "No options available."); + return false; + } + + const selections = this.getOption("selection"); + if ( + selections === undefined || + selections === null || + selections.length === 0 + ) { + this.setOption( + "messages.control", + this.getOption("labels.select-an-option"), + ); + } else { + this.setOption("messages.control", ""); + } + + this.setOption("messages.summary", setSummaryAndControlText.call(this)); + + let updated = false; + let valueCounter = 1; + for (const option of options) { + if (option?.visibility === undefined) { + option.visibility = "visible"; + updated = true; + } + + if (option?.value === undefined && option?.label === undefined) { + option.value = `${valueCounter++}`; + option.label = option.value; + updated = true; + continue; + } + + if (option?.value === undefined) { + option.value = option.label; + updated = true; + } + + if (option?.label === undefined) { + option.label = option.value; + updated = true; + } + } + + if (updated) { + this.setOption("options", options); + } + + setStatusOrRemoveBadges.call(this); + + removeErrorAttribute(this, "No options available."); + return true; } /** @@ -2141,30 +2141,30 @@ function areOptionsAvailableAndInit() { * @throws {Error} no shadow-root is defined */ function checkOptionState() { - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - const elements = this.shadowRoot.querySelectorAll( - `[${ATTRIBUTE_ROLE}=option] input`, - ); - - let selection = this.getOption("selection"); - if (!isArray(selection)) { - selection = []; - } - - const checkedValues = selection.map((a) => { - return a.value; - }); - - for (const e of elements) { - if (checkedValues.indexOf(e.value) !== -1) { - if (e.checked !== true) e.checked = true; - } else { - if (e.checked !== false) e.checked = false; - } - } + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + const elements = this.shadowRoot.querySelectorAll( + `[${ATTRIBUTE_ROLE}=option] input`, + ); + + let selection = this.getOption("selection"); + if (!isArray(selection)) { + selection = []; + } + + const checkedValues = selection.map((a) => { + return a.value; + }); + + for (const e of elements) { + if (checkedValues.indexOf(e.value) !== -1) { + if (e.checked !== true) e.checked = true; + } else { + if (e.checked !== false) e.checked = false; + } + } } /** @@ -2173,41 +2173,41 @@ function checkOptionState() { * @return {Object} */ function convertValueToSelection(value) { - const selection = []; - - if (isString(value)) { - value = value - .split(",") - .map((a) => { - return a.trim(); - }) - .filter((a) => { - return a !== ""; - }); - } - - if (isString(value) || isInteger(value)) { - selection.push({ - label: getSelectionLabel.call(this, value), - value: value, - }); - } else if (isArray(value)) { - for (const v of value) { - selection.push({ - label: getSelectionLabel.call(this, v), - value: v, - }); - } - - value = value.join(","); - } else { - throw new Error("unsupported type"); - } - - return { - selection: selection, - value: value, - }; + const selection = []; + + if (isString(value)) { + value = value + .split(",") + .map((a) => { + return a.trim(); + }) + .filter((a) => { + return a !== ""; + }); + } + + if (isString(value) || isInteger(value)) { + selection.push({ + label: getSelectionLabel.call(this, value), + value: value, + }); + } else if (isArray(value)) { + for (const v of value) { + selection.push({ + label: getSelectionLabel.call(this, v), + value: v, + }); + } + + value = value.join(","); + } else { + throw new Error("unsupported type"); + } + + return { + selection: selection, + value: value, + }; } /** @@ -2216,123 +2216,151 @@ function convertValueToSelection(value) { * @return {string} */ function convertSelectionToValue(selection) { - const value = []; - - if (isArray(selection)) { - for (const obj of selection) { - const v = obj?.["value"]; - if (v !== undefined) value.push(`${v}`); - } - } - - if (value.length === 0) { - return ""; - } else if (value.length === 1) { - const v = value.pop(); - if (v === undefined) return ""; - if (v === null) return ""; - return `${v}`; - } - - return value.join(","); + const value = []; + + if (isArray(selection)) { + for (const obj of selection) { + const v = obj?.["value"]; + if (v !== undefined) value.push(`${v}`); + } + } + + if (value.length === 0) { + return ""; + } else if (value.length === 1) { + const v = value.pop(); + if (v === undefined) return ""; + if (v === null) return ""; + return `${v}`; + } + + return value.join(","); } /** * @private - * @param {array|string} selection - * @return {Promise} - * @throws {Error} no shadow-root is defined + * @param value + * @returns {boolean} + */ +function isValueIsEmpty(value) { + let equivalents = this.getOption("empty.equivalents"); + if (!isArray(equivalents)) { + if (equivalents === undefined) { + return false; + } + equivalents = [equivalents]; + } + + return equivalents.indexOf(value) !== -1; + +} + +/** + * @private + * @param value + * @returns {*} + */ +function isValueIsEmptyThenGetNormalize(value) { + let emptyDefault = null + if (this.getOption("type")==="checkbox") { + emptyDefault = this.getOption("empty.defaultValueCheckbox"); + } else { + emptyDefault = this.getOption("empty.defaultValueRadio"); + } + + if (isValueIsEmpty.call(this,value)) { + return emptyDefault; + } + + return value; + +} + +/** + * @private + * @param selection + * @returns {Promise<unknown | void>} */ function setSelection(selection) { - if (isString(selection) || isInteger(selection)) { - const result = convertValueToSelection.call(this, selection); - selection = result?.selection; - } else if (selection === undefined || selection === null) { - selection = []; - } - - validateArray(selection); - let ignoreValues = this.getOption("ignoreValues", []); - if (!isArray(ignoreValues)) { - ignoreValues = []; - } - - let resultSelection = []; - for (let i = 0; i < selection.length; i++) { - let ignore = false; - - for (const v of ignoreValues) { - if (selection[i].value === v) { - ignore = true; - break; - } - } - if (ignore) { - continue; - } - - let l = getSelectionLabel.call(this, selection[i].value); - if (l === selection[i].value) { - l = selection[i].label; - } - - resultSelection.push({ - label: l, - value: selection[i].value, - }); - } - - selection = resultSelection; - - this.setOption("selection", selection); - checkOptionState.call(this); - setSummaryAndControlText.call(this); - - try { - this?.setFormValue(this.value); - } catch (e) { - addErrorAttribute(this, e); - } - - fireCustomEvent(this, "monster-selected", { - selection, - }); - - //fireEvent(this, "change"); // https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/291 - - return new Processing(() => { - const CLASSNAME = "selected"; - - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - const notSelected = this.shadowRoot.querySelectorAll(":not(:checked)"); - - if (notSelected) { - notSelected.forEach((node) => { - const parent = node.closest(`[${ATTRIBUTE_ROLE}=option]`); - if (parent) { - parent.classList.remove(CLASSNAME); - } - }); - } - - const selected = this.shadowRoot.querySelectorAll(":checked"); - - if (selected) { - selected.forEach((node) => { - const parent = node.closest(`[${ATTRIBUTE_ROLE}=option]`); - if (parent) { - parent.classList.add(CLASSNAME); - } - }); - } - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); + + if (isString(selection) || isInteger(selection)) { + const result = convertValueToSelection.call(this, selection); + selection = result?.selection; + } + + selection = isValueIsEmptyThenGetNormalize.call(this,selection); + validateArray(selection); + + let resultSelection = []; + for (let i = 0; i < selection.length; i++) { + + if(isValueIsEmpty.call(this,selection[i].value)) { + continue + } + + let l = getSelectionLabel.call(this, selection[i].value); + if (l === selection[i].value) { + l = selection[i].label; + } + + resultSelection.push({ + label: l, + value: selection[i].value, + }); + } + + selection = resultSelection; + + this.setOption("selection", selection); + + checkOptionState.call(this); + setSummaryAndControlText.call(this); + + try { + this?.setFormValue(this.value); + } catch (e) { + addErrorAttribute(this, e); + } + + fireCustomEvent(this, "monster-selected", { + selection, + }); + + fireEvent(this, "change"); // https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/291 + + return new Processing(() => { + const CLASSNAME = "selected"; + + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + const notSelected = this.shadowRoot.querySelectorAll(":not(:checked)"); + + if (notSelected) { + notSelected.forEach((node) => { + const parent = node.closest(`[${ATTRIBUTE_ROLE}=option]`); + if (parent) { + parent.classList.remove(CLASSNAME); + } + }); + } + + const selected = this.shadowRoot.querySelectorAll(":checked"); + + if (selected) { + selected.forEach((node) => { + const parent = node.closest(`[${ATTRIBUTE_ROLE}=option]`); + if (parent) { + parent.classList.add(CLASSNAME); + } + }); + } + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); } /** @@ -2343,139 +2371,139 @@ function setSelection(selection) { * @throws {TypeError} unsupported response */ function fetchData(url) { - const self = this; - if (!url) url = this.getOption("url"); - if (!url) return Promise.resolve(); - - const fetchOptions = this.getOption("fetch", {}); - - let delayWatch = false; - - // if fetch short time, do not show loading badge, because of flickering - requestAnimationFrame(() => { - if (delayWatch === true) return; - setStatusOrRemoveBadges.call(this, "loading"); - delayWatch = true; - }); - - url = formatURL.call(this, url); - - self[isLoadingSymbol] = true; - const global = getGlobal(); - return global - .fetch(url, fetchOptions) - .then((response) => { - self[isLoadingSymbol] = false; - delayWatch = true; - const contentType = response.headers.get("content-type"); - if (contentType && contentType.indexOf("application/json") !== -1) { - return response.text(); - } - - throw new TypeError(`unsupported response ${contentType}`); - }) - .then((text) => { - try { - return Promise.resolve(JSON.parse(String(text))); - } catch (e) { - throw new TypeError("the result cannot be parsed, check the URL"); - } - }) - .catch((e) => { - self[isLoadingSymbol] = false; - delayWatch = true; - throw e; - }); + const self = this; + if (!url) url = this.getOption("url"); + if (!url) return Promise.resolve(); + + const fetchOptions = this.getOption("fetch", {}); + + let delayWatch = false; + + // if fetch short time, do not show loading badge, because of flickering + requestAnimationFrame(() => { + if (delayWatch === true) return; + setStatusOrRemoveBadges.call(this, "loading"); + delayWatch = true; + }); + + url = formatURL.call(this, url); + + self[isLoadingSymbol] = true; + const global = getGlobal(); + return global + .fetch(url, fetchOptions) + .then((response) => { + self[isLoadingSymbol] = false; + delayWatch = true; + const contentType = response.headers.get("content-type"); + if (contentType && contentType.indexOf("application/json") !== -1) { + return response.text(); + } + + throw new TypeError(`unsupported response ${contentType}`); + }) + .then((text) => { + try { + return Promise.resolve(JSON.parse(String(text))); + } catch (e) { + throw new TypeError("the result cannot be parsed, check the URL"); + } + }) + .catch((e) => { + self[isLoadingSymbol] = false; + delayWatch = true; + throw e; + }); } /** * @private */ function hide() { - this[popperElementSymbol].style.display = "none"; - setStatusOrRemoveBadges.call(this, "closed"); - removeAttributeToken(this[controlElementSymbol], "class", "open"); + this[popperElementSymbol].style.display = "none"; + setStatusOrRemoveBadges.call(this, "closed"); + removeAttributeToken(this[controlElementSymbol], "class", "open"); } /** * @private */ function show() { - if (this.getOption("disabled", undefined) === true) { - return; - } - - if (this[popperElementSymbol].style.display === STYLE_DISPLAY_MODE_BLOCK) { - return; - } - - focusFilter.call(this); - - const lazyLoadFlag = - this.getOption("features.lazyLoad") && this[lazyLoadDoneSymbol] !== true; - - if (lazyLoadFlag === true) { - this[lazyLoadDoneSymbol] = true; - setStatusOrRemoveBadges.call(this, "loading"); - - new Processing(200, () => { - this.fetch() - .then(() => { - checkOptionState.call(this); - requestAnimationFrame(() => { - show.call(this); - }); - }) - .catch((e) => { - addErrorAttribute(this, e); - setStatusOrRemoveBadges.call(this, "error"); - }); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - setStatusOrRemoveBadges.call(this, "error"); - }); - - return; - } - - const hasPopperFilterFlag = - this.getOption("filter.position") === FILTER_POSITION_POPPER && - getFilterMode.call(this) !== FILTER_MODE_DISABLED; - - const options = getOptionElements.call(this); - if (options.length === 0 && hasPopperFilterFlag === false) { - return; - } - - this[popperElementSymbol].style.visibility = "hidden"; - this[popperElementSymbol].style.display = STYLE_DISPLAY_MODE_BLOCK; - setStatusOrRemoveBadges.call(this, "open"); - - addAttributeToken(this[controlElementSymbol], "class", "open"); - - new Processing(() => { - calcAndSetOptionsDimension.call(this); - focusFilter.call(this); - this[popperElementSymbol].style.removeProperty("visibility"); - updatePopper.call(this); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); + if (this.getOption("disabled", undefined) === true) { + return; + } + + if (this[popperElementSymbol].style.display === STYLE_DISPLAY_MODE_BLOCK) { + return; + } + + focusFilter.call(this); + + const lazyLoadFlag = + this.getOption("features.lazyLoad") && this[lazyLoadDoneSymbol] !== true; + + if (lazyLoadFlag === true) { + this[lazyLoadDoneSymbol] = true; + setStatusOrRemoveBadges.call(this, "loading"); + + new Processing(200, () => { + this.fetch() + .then(() => { + checkOptionState.call(this); + requestAnimationFrame(() => { + show.call(this); + }); + }) + .catch((e) => { + addErrorAttribute(this, e); + setStatusOrRemoveBadges.call(this, "error"); + }); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + setStatusOrRemoveBadges.call(this, "error"); + }); + + return; + } + + const hasPopperFilterFlag = + this.getOption("filter.position") === FILTER_POSITION_POPPER && + getFilterMode.call(this) !== FILTER_MODE_DISABLED; + + const options = getOptionElements.call(this); + if (options.length === 0 && hasPopperFilterFlag === false) { + return; + } + + this[popperElementSymbol].style.visibility = "hidden"; + this[popperElementSymbol].style.display = STYLE_DISPLAY_MODE_BLOCK; + setStatusOrRemoveBadges.call(this, "open"); + + addAttributeToken(this[controlElementSymbol], "class", "open"); + + new Processing(() => { + calcAndSetOptionsDimension.call(this); + focusFilter.call(this); + this[popperElementSymbol].style.removeProperty("visibility"); + updatePopper.call(this); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); } /** * @private */ function toggle() { - if (this[popperElementSymbol].style.display === STYLE_DISPLAY_MODE_BLOCK) { - hide.call(this); - } else { - show.call(this); - } + if (this[popperElementSymbol].style.display === STYLE_DISPLAY_MODE_BLOCK) { + hide.call(this); + } else { + show.call(this); + } } /** @@ -2484,188 +2512,188 @@ function toggle() { * @fires monster-selection-cleared */ function initEventHandler() { - const self = this; - - /** - * @param {Event} event - */ - self[clearOptionEventHandler] = (event) => { - const element = findTargetElementFromEvent( - event, - ATTRIBUTE_ROLE, - "remove-badge", - ); - - if (element instanceof HTMLElement) { - const badge = findClosestByAttribute(element, ATTRIBUTE_ROLE, "badge"); - if (badge instanceof HTMLElement) { - const value = badge.getAttribute(`${ATTRIBUTE_PREFIX}value`); - - let selection = self.getOption("selection"); - selection = selection.filter((b) => { - return value !== b.value; - }); - - setSelection - .call(self, selection) - .then(() => { - fireCustomEvent(self, "monster-selection-removed", { - value, - }); - }) - .catch((e) => { - addErrorAttribute(self, e); - }); - } - } - }; - - /** - * @param {Event} event - */ - self[closeEventHandler] = (event) => { - const path = event.composedPath(); - - for (const [, element] of Object.entries(path)) { - if (element === self) { - return; - } - } - hide.call(self); - }; - - /** - * @param {Event} event - */ - self[inputEventHandler] = (event) => { - const path = event.composedPath(); - const element = path?.[0]; - - if (element instanceof HTMLElement) { - if ( - element.hasAttribute(ATTRIBUTE_ROLE) && - element.getAttribute(ATTRIBUTE_ROLE) === "option-control" - ) { - fireCustomEvent(self, "monster-change", { - type: event.type, - value: element.value, - checked: element.checked, - }); - } else if ( - element.hasAttribute(ATTRIBUTE_ROLE) && - element.getAttribute(ATTRIBUTE_ROLE) === "filter" - ) { - } - } - }; - - /** - * @param {Event} event - */ - self[changeEventHandler] = (event) => { - gatherState.call(self); - fireCustomEvent(self, "monster-changed", event?.detail); - }; - - self[keyEventHandler] = (event) => { - const path = event.composedPath(); - const element = path.shift(); - - let role; - - if (element instanceof HTMLElement) { - if (element.hasAttribute(ATTRIBUTE_ROLE)) { - role = element.getAttribute(ATTRIBUTE_ROLE); - } else if (element === this) { - show.call(this); - // focusFilter.call(self); - } else { - const e = element.closest(`[${ATTRIBUTE_ROLE}]`); - if (e instanceof HTMLElement && e.hasAttribute(ATTRIBUTE_ROLE)) { - role = e.getAttribute(ATTRIBUTE_ROLE); - } - } - } else { - return; - } - - switch (role) { - case "filter": - handleFilterKeyboardEvents.call(self, event); - break; - case "option-label": - case "option-control": - case "option": - handleOptionKeyboardEvents.call(self, event); - break; - case "control": - case "toggle": - handleToggleKeyboardEvents.call(self, event); - break; - } - }; - - const types = self.getOption("toggleEventType", ["click"]); - - for (const [, type] of Object.entries(types)) { - self[controlElementSymbol] - .querySelector(`[${ATTRIBUTE_ROLE}="container"]`) - .addEventListener(type, function (event) { - const element = findTargetElementFromEvent( - event, - ATTRIBUTE_ROLE, - "remove-badge", - ); - if (element instanceof HTMLElement) { - return; - } - - toggle.call(self); - }); - - self[controlElementSymbol] - .querySelector(`[${ATTRIBUTE_ROLE}="status-or-remove-badges"]`) - .addEventListener(type, function (event) { - if (self.getOption("disabled", undefined) === true) { - return; - } - - const path = event.composedPath(); - const element = path?.[0]; - if (element instanceof HTMLElement) { - const control = element.closest( - `[${ATTRIBUTE_ROLE}="status-or-remove-badges"]`, - ); - if (control instanceof HTMLElement) { - if (control.classList.contains("clear")) { - clearSelection.call(self); - - fireCustomEvent(self, "monster-selection-cleared", {}); - } else { - const element = findTargetElementFromEvent( - event, - ATTRIBUTE_ROLE, - "remove-badge", - ); - if (element instanceof HTMLElement) { - return; - } - - toggle.call(self); - } - } - } - }); - - // badge, selection - self.addEventListener(type, self[clearOptionEventHandler]); - } - - self.addEventListener("monster-change", self[changeEventHandler]); - self.addEventListener("input", self[inputEventHandler]); - self.addEventListener("keydown", self[keyEventHandler]); - - return self; + const self = this; + + /** + * @param {Event} event + */ + self[clearOptionEventHandler] = (event) => { + const element = findTargetElementFromEvent( + event, + ATTRIBUTE_ROLE, + "remove-badge", + ); + + if (element instanceof HTMLElement) { + const badge = findClosestByAttribute(element, ATTRIBUTE_ROLE, "badge"); + if (badge instanceof HTMLElement) { + const value = badge.getAttribute(`${ATTRIBUTE_PREFIX}value`); + + let selection = self.getOption("selection"); + selection = selection.filter((b) => { + return value !== b.value; + }); + + setSelection + .call(self, selection) + .then(() => { + fireCustomEvent(self, "monster-selection-removed", { + value, + }); + }) + .catch((e) => { + addErrorAttribute(self, e); + }); + } + } + }; + + /** + * @param {Event} event + */ + self[closeEventHandler] = (event) => { + const path = event.composedPath(); + + for (const [, element] of Object.entries(path)) { + if (element === self) { + return; + } + } + hide.call(self); + }; + + /** + * @param {Event} event + */ + self[inputEventHandler] = (event) => { + const path = event.composedPath(); + const element = path?.[0]; + + if (element instanceof HTMLElement) { + if ( + element.hasAttribute(ATTRIBUTE_ROLE) && + element.getAttribute(ATTRIBUTE_ROLE) === "option-control" + ) { + fireCustomEvent(self, "monster-change", { + type: event.type, + value: element.value, + checked: element.checked, + }); + } else if ( + element.hasAttribute(ATTRIBUTE_ROLE) && + element.getAttribute(ATTRIBUTE_ROLE) === "filter" + ) { + } + } + }; + + /** + * @param {Event} event + */ + self[changeEventHandler] = (event) => { + gatherState.call(self); + fireCustomEvent(self, "monster-changed", event?.detail); + }; + + self[keyEventHandler] = (event) => { + const path = event.composedPath(); + const element = path.shift(); + + let role; + + if (element instanceof HTMLElement) { + if (element.hasAttribute(ATTRIBUTE_ROLE)) { + role = element.getAttribute(ATTRIBUTE_ROLE); + } else if (element === this) { + show.call(this); + // focusFilter.call(self); + } else { + const e = element.closest(`[${ATTRIBUTE_ROLE}]`); + if (e instanceof HTMLElement && e.hasAttribute(ATTRIBUTE_ROLE)) { + role = e.getAttribute(ATTRIBUTE_ROLE); + } + } + } else { + return; + } + + switch (role) { + case "filter": + handleFilterKeyboardEvents.call(self, event); + break; + case "option-label": + case "option-control": + case "option": + handleOptionKeyboardEvents.call(self, event); + break; + case "control": + case "toggle": + handleToggleKeyboardEvents.call(self, event); + break; + } + }; + + const types = self.getOption("toggleEventType", ["click"]); + + for (const [, type] of Object.entries(types)) { + self[controlElementSymbol] + .querySelector(`[${ATTRIBUTE_ROLE}="container"]`) + .addEventListener(type, function (event) { + const element = findTargetElementFromEvent( + event, + ATTRIBUTE_ROLE, + "remove-badge", + ); + if (element instanceof HTMLElement) { + return; + } + + toggle.call(self); + }); + + self[controlElementSymbol] + .querySelector(`[${ATTRIBUTE_ROLE}="status-or-remove-badges"]`) + .addEventListener(type, function (event) { + if (self.getOption("disabled", undefined) === true) { + return; + } + + const path = event.composedPath(); + const element = path?.[0]; + if (element instanceof HTMLElement) { + const control = element.closest( + `[${ATTRIBUTE_ROLE}="status-or-remove-badges"]`, + ); + if (control instanceof HTMLElement) { + if (control.classList.contains("clear")) { + clearSelection.call(self); + + fireCustomEvent(self, "monster-selection-cleared", {}); + } else { + const element = findTargetElementFromEvent( + event, + ATTRIBUTE_ROLE, + "remove-badge", + ); + if (element instanceof HTMLElement) { + return; + } + + toggle.call(self); + } + } + } + }); + + // badge, selection + self.addEventListener(type, self[clearOptionEventHandler]); + } + + self.addEventListener("monster-change", self[changeEventHandler]); + self.addEventListener("input", self[inputEventHandler]); + self.addEventListener("keydown", self[keyEventHandler]); + + return self; } /** @@ -2673,70 +2701,70 @@ function initEventHandler() { * @return {Select} */ function setStatusOrRemoveBadges(suggestion) { - requestAnimationFrame(() => { - const selection = this.getOption("selection"); - - const clearAllFlag = - isArray(selection) && - selection.length > 0 && - this.getOption("features.clearAll") === true; - - const current = this.getOption("classes.statusOrRemoveBadge"); - - if (suggestion === "error") { - if (current !== "error") { - this.setOption("classes.statusOrRemoveBadge", "error"); - } - return; - } - - if (this[isLoadingSymbol] === true) { - if (current !== "loading") { - this.setOption("classes.statusOrRemoveBadge", "loading"); - } - return; - } - - if (suggestion === "loading") { - if (current !== "loading") { - this.setOption("classes.statusOrRemoveBadge", "loading"); - } - return; - } - - if (clearAllFlag) { - if (current !== "clear") { - this.setOption("classes.statusOrRemoveBadge", "clear"); - } - return; - } - - if (this[controlElementSymbol].classList.contains("open")) { - if (current !== "open") { - this.setOption("classes.statusOrRemoveBadge", "open"); - } - return; - } - - const options = this.getOption("options"); - if ( - options === undefined || - options === null || - (isArray(options) && options.length === 0) - ) { - if (current !== "empty") { - this.setOption("classes.statusOrRemoveBadge", "empty"); - } - return; - } - - if (suggestion) { - if (current !== suggestion) { - this.setOption("classes.statusOrRemoveBadge", suggestion); - } - return; - } - }); + requestAnimationFrame(() => { + const selection = this.getOption("selection"); + + const clearAllFlag = + isArray(selection) && + selection.length > 0 && + this.getOption("features.clearAll") === true; + + const current = this.getOption("classes.statusOrRemoveBadge"); + + if (suggestion === "error") { + if (current !== "error") { + this.setOption("classes.statusOrRemoveBadge", "error"); + } + return; + } + + if (this[isLoadingSymbol] === true) { + if (current !== "loading") { + this.setOption("classes.statusOrRemoveBadge", "loading"); + } + return; + } + + if (suggestion === "loading") { + if (current !== "loading") { + this.setOption("classes.statusOrRemoveBadge", "loading"); + } + return; + } + + if (clearAllFlag) { + if (current !== "clear") { + this.setOption("classes.statusOrRemoveBadge", "clear"); + } + return; + } + + if (this[controlElementSymbol].classList.contains("open")) { + if (current !== "open") { + this.setOption("classes.statusOrRemoveBadge", "open"); + } + return; + } + + const options = this.getOption("options"); + if ( + options === undefined || + options === null || + (isArray(options) && options.length === 0) + ) { + if (current !== "empty") { + this.setOption("classes.statusOrRemoveBadge", "empty"); + } + return; + } + + if (suggestion) { + if (current !== suggestion) { + this.setOption("classes.statusOrRemoveBadge", suggestion); + } + return; + } + }); } /** @@ -2745,68 +2773,68 @@ function setStatusOrRemoveBadges(suggestion) { * @throws {Error} no shadow-root is defined */ function initControlReferences() { - if (!this.shadowRoot) { - throw new Error("no shadow-root is defined"); - } - - this[controlElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=control]`, - ); - this[selectionElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=selection]`, - ); - this[containerElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=container]`, - ); - this[popperElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=popper]`, - ); - this[inlineFilterElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=filter][name="inline-filter"]`, - ); - this[popperFilterElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=filter][name="popper-filter"]`, - ); - this[popperFilterContainerElementSymbol] = - this[popperFilterElementSymbol].parentElement; - this[optionsElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=options]`, - ); - this[noOptionsAvailableElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}="no-options"]`, - ); - this[statusOrRemoveBadgesElementSymbol] = this.shadowRoot.querySelector( - `[${ATTRIBUTE_ROLE}=status-or-remove-badges]`, - ); + if (!this.shadowRoot) { + throw new Error("no shadow-root is defined"); + } + + this[controlElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=control]`, + ); + this[selectionElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=selection]`, + ); + this[containerElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=container]`, + ); + this[popperElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=popper]`, + ); + this[inlineFilterElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=filter][name="inline-filter"]`, + ); + this[popperFilterElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=filter][name="popper-filter"]`, + ); + this[popperFilterContainerElementSymbol] = + this[popperFilterElementSymbol].parentElement; + this[optionsElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=options]`, + ); + this[noOptionsAvailableElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}="no-options"]`, + ); + this[statusOrRemoveBadgesElementSymbol] = this.shadowRoot.querySelector( + `[${ATTRIBUTE_ROLE}=status-or-remove-badges]`, + ); } /** * @private */ function updatePopper() { - if (this[popperElementSymbol].style.display !== STYLE_DISPLAY_MODE_BLOCK) { - return; - } - - if (this.getOption("disabled", false) === true) { - return; - } - - new Processing(() => { - calcAndSetOptionsDimension.call(this); - positionPopper.call( - this, - this[controlElementSymbol], - this[popperElementSymbol], - this.getOption("popper", {}), - ); - }) - .run() - .catch((e) => { - addErrorAttribute(this, e); - }); - - return this; + if (this[popperElementSymbol].style.display !== STYLE_DISPLAY_MODE_BLOCK) { + return; + } + + if (this.getOption("disabled", false) === true) { + return; + } + + new Processing(() => { + calcAndSetOptionsDimension.call(this); + positionPopper.call( + this, + this[controlElementSymbol], + this[popperElementSymbol], + this.getOption("popper", {}), + ); + }) + .run() + .catch((e) => { + addErrorAttribute(this, e); + }); + + return this; } /** @@ -2814,8 +2842,8 @@ function updatePopper() { * @return {string} */ function getTemplate() { - // language=HTML - return ` + // language=HTML + return ` <template id="options"> <div data-monster-role="option" tabindex="-1" data-monster-attributes=" diff --git a/source/dom/updater.mjs b/source/dom/updater.mjs index 5f94b079f45f2dfaafee6bc9d611c629e2154dff..693cf5487e4c4a061d5e435284d72f2ee364f19e 100644 --- a/source/dom/updater.mjs +++ b/source/dom/updater.mjs @@ -12,39 +12,49 @@ * SPDX-License-Identifier: AGPL-3.0 */ -import { internalSymbol } from "../constants.mjs"; -import { diff } from "../data/diff.mjs"; -import { Pathfinder } from "../data/pathfinder.mjs"; -import { Pipe } from "../data/pipe.mjs"; +import {internalSymbol} from "../constants.mjs"; +import {diff} from "../data/diff.mjs"; +import {Pathfinder} from "../data/pathfinder.mjs"; +import {Pipe} from "../data/pipe.mjs"; import { - ATTRIBUTE_ERRORMESSAGE, - ATTRIBUTE_UPDATER_ATTRIBUTES, - ATTRIBUTE_UPDATER_BIND, - ATTRIBUTE_UPDATER_BIND_TYPE, - ATTRIBUTE_UPDATER_INSERT, - ATTRIBUTE_UPDATER_INSERT_REFERENCE, - ATTRIBUTE_UPDATER_REMOVE, - ATTRIBUTE_UPDATER_REPLACE, - ATTRIBUTE_UPDATER_SELECT_THIS, + ATTRIBUTE_ERRORMESSAGE, + ATTRIBUTE_UPDATER_ATTRIBUTES, + ATTRIBUTE_UPDATER_BIND, + ATTRIBUTE_UPDATER_BIND_TYPE, + ATTRIBUTE_UPDATER_INSERT, + ATTRIBUTE_UPDATER_INSERT_REFERENCE, + ATTRIBUTE_UPDATER_REMOVE, + ATTRIBUTE_UPDATER_REPLACE, + ATTRIBUTE_UPDATER_SELECT_THIS, } from "./constants.mjs"; -import { Base } from "../types/base.mjs"; -import { isArray, isString, isInstance, isIterable } from "../types/is.mjs"; -import { Observer } from "../types/observer.mjs"; -import { ProxyObserver } from "../types/proxyobserver.mjs"; -import { validateArray, validateInstance } from "../types/validate.mjs"; -import { clone } from "../util/clone.mjs"; -import { trimSpaces } from "../util/trimspaces.mjs"; -import { addAttributeToken, addToObjectLink } from "./attributes.mjs"; +import {Base} from "../types/base.mjs"; +import {isArray, isInteger, isString, isInstance, isIterable} from "../types/is.mjs"; +import {Observer} from "../types/observer.mjs"; +import {ProxyObserver} from "../types/proxyobserver.mjs"; +import {validateArray, validateInstance} from "../types/validate.mjs"; +import {clone} from "../util/clone.mjs"; +import {trimSpaces} from "../util/trimspaces.mjs"; +import {addAttributeToken, addToObjectLink} from "./attributes.mjs"; import { - CustomElement, - updaterTransformerMethodsSymbol, + CustomElement, + updaterTransformerMethodsSymbol, } from "./customelement.mjs"; -import { findTargetElementFromEvent } from "./events.mjs"; -import { findDocumentTemplate } from "./template.mjs"; -import { getWindow } from "./util.mjs"; +import {findTargetElementFromEvent} from "./events.mjs"; +import {findDocumentTemplate} from "./template.mjs"; +import {getWindow} from "./util.mjs"; +import {DeadMansSwitch} from "../util/deadmansswitch.mjs"; +import {addErrorAttribute, removeErrorAttribute} from "./error.mjs"; + + +export {Updater, addObjectWithUpdaterToElement}; -export { Updater, addObjectWithUpdaterToElement }; + +/** + * @private + * @type {symbol} + */ +const timerElementEventHandlerSymbol = Symbol("timerElementEventHandler"); /** * The updater class connects an object with the DOM. In this way, structures and contents in the DOM can be @@ -71,190 +81,190 @@ export { Updater, addObjectWithUpdaterToElement }; * @summary The updater class connects an object with the dom */ class Updater extends Base { - /** - * @since 1.8.0 - * @param {HTMLElement} element - * @param {object|ProxyObserver|undefined} subject - * @throws {TypeError} value is not a object - * @throws {TypeError} value is not an instance of HTMLElement - * @see {@link findDocumentTemplate} - */ - constructor(element, subject) { - super(); - - /** - * @type {HTMLElement} - */ - if (subject === undefined) subject = {}; - if (!isInstance(subject, ProxyObserver)) { - subject = new ProxyObserver(subject); - } - - this[internalSymbol] = { - element: validateInstance(element, HTMLElement), - last: {}, - callbacks: new Map(), - eventTypes: ["keyup", "click", "change", "drop", "touchend", "input"], - subject: subject, - }; - - this[internalSymbol].callbacks.set( - "checkstate", - getCheckStateCallback.call(this), - ); - - this[internalSymbol].subject.attachObserver( - new Observer(() => { - const s = this[internalSymbol].subject.getRealSubject(); - - const diffResult = diff(this[internalSymbol].last, s); - this[internalSymbol].last = clone(s); - - const promises = []; - - for (const [, change] of Object.entries(diffResult)) { - promises.push( - new Promise((resolve, reject) => { - getWindow().requestAnimationFrame(() => { - try { - removeElement.call(this, change); - insertElement.call(this, change); - updateContent.call(this, change); - updateAttributes.call(this, change); - - resolve(); - } catch (error) { - reject(error); - } - }); - }), - ); - } - - return Promise.all(promises); - }), - ); - } - - /** - * Defaults: 'keyup', 'click', 'change', 'drop', 'touchend' - * - * @see {@link https://developer.mozilla.org/de/docs/Web/Events} - * @since 1.9.0 - * @param {Array} types - * @return {Updater} - */ - setEventTypes(types) { - this[internalSymbol].eventTypes = validateArray(types); - return this; - } - - /** - * With this method, the eventlisteners are hooked in and the magic begins. - * - * ```js - * updater.run().then(() => { - * updater.enableEventProcessing(); - * }); - * ``` - * - * @since 1.9.0 - * @return {Updater} - * @throws {Error} the bind argument must start as a value with a path - */ - enableEventProcessing() { - this.disableEventProcessing(); - - for (const type of this[internalSymbol].eventTypes) { - // @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener - this[internalSymbol].element.addEventListener( - type, - getControlEventHandler.call(this), - { - capture: true, - passive: true, - }, - ); - } - - return this; - } - - /** - * This method turns off the magic or who loves it more profane it removes the eventListener. - * - * @since 1.9.0 - * @return {Updater} - */ - disableEventProcessing() { - for (const type of this[internalSymbol].eventTypes) { - this[internalSymbol].element.removeEventListener( - type, - getControlEventHandler.call(this), - ); - } - - return this; - } - - /** - * The run method must be called for the update to start working. - * The method ensures that changes are detected. - * - * ```js - * updater.run().then(() => { - * updater.enableEventProcessing(); - * }); - * ``` - * - * @summary Let the magic begin - * @return {Promise} - */ - run() { - // the key __init__has no further meaning and is only - // used to create the diff for empty objects. - this[internalSymbol].last = { __init__: true }; - return this[internalSymbol].subject.notifyObservers(); - } - - /** - * Gets the values of bound elements and changes them in subject - * - * @since 1.27.0 - * @return {Monster.DOM.Updater} - */ - retrieve() { - retrieveFromBindings.call(this); - return this; - } - - /** - * If you have passed a ProxyObserver in the constructor, you will get the object that the ProxyObserver manages here. - * However, if you passed a simple object, here you will get a proxy for that object. - * - * For changes, the ProxyObserver must be used. - * - * @since 1.8.0 - * @return {Proxy} - */ - getSubject() { - return this[internalSymbol].subject.getSubject(); - } - - /** - * This method can be used to register commands that can be called via call: instruction. - * This can be used to provide a pipe with its own functionality. - * - * @param {string} name - * @param {function} callback - * @return {Transformer} - * @throws {TypeError} value is not a string - * @throws {TypeError} value is not a function - */ - setCallback(name, callback) { - this[internalSymbol].callbacks.set(name, callback); - return this; - } + /** + * @since 1.8.0 + * @param {HTMLElement} element + * @param {object|ProxyObserver|undefined} subject + * @throws {TypeError} value is not a object + * @throws {TypeError} value is not an instance of HTMLElement + * @see {@link findDocumentTemplate} + */ + constructor(element, subject) { + super(); + + /** + * @type {HTMLElement} + */ + if (subject === undefined) subject = {}; + if (!isInstance(subject, ProxyObserver)) { + subject = new ProxyObserver(subject); + } + + this[internalSymbol] = { + element: validateInstance(element, HTMLElement), + last: {}, + callbacks: new Map(), + eventTypes: ["keyup", "click", "change", "drop", "touchend", "input"], + subject: subject, + }; + + this[internalSymbol].callbacks.set( + "checkstate", + getCheckStateCallback.call(this), + ); + + this[internalSymbol].subject.attachObserver( + new Observer(() => { + const s = this[internalSymbol].subject.getRealSubject(); + + const diffResult = diff(this[internalSymbol].last, s); + this[internalSymbol].last = clone(s); + + const promises = []; + + for (const [, change] of Object.entries(diffResult)) { + promises.push( + new Promise((resolve, reject) => { + getWindow().requestAnimationFrame(() => { + try { + removeElement.call(this, change); + insertElement.call(this, change); + updateContent.call(this, change); + updateAttributes.call(this, change); + + resolve(); + } catch (error) { + reject(error); + } + }); + }), + ); + } + + return Promise.all(promises); + }), + ); + } + + /** + * Defaults: 'keyup', 'click', 'change', 'drop', 'touchend' + * + * @see {@link https://developer.mozilla.org/de/docs/Web/Events} + * @since 1.9.0 + * @param {Array} types + * @return {Updater} + */ + setEventTypes(types) { + this[internalSymbol].eventTypes = validateArray(types); + return this; + } + + /** + * With this method, the eventlisteners are hooked in and the magic begins. + * + * ```js + * updater.run().then(() => { + * updater.enableEventProcessing(); + * }); + * ``` + * + * @since 1.9.0 + * @return {Updater} + * @throws {Error} the bind argument must start as a value with a path + */ + enableEventProcessing() { + this.disableEventProcessing(); + + for (const type of this[internalSymbol].eventTypes) { + // @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener + this[internalSymbol].element.addEventListener( + type, + getControlEventHandler.call(this), + { + capture: true, + passive: true, + }, + ); + } + + return this; + } + + /** + * This method turns off the magic or who loves it more profane it removes the eventListener. + * + * @since 1.9.0 + * @return {Updater} + */ + disableEventProcessing() { + for (const type of this[internalSymbol].eventTypes) { + this[internalSymbol].element.removeEventListener( + type, + getControlEventHandler.call(this), + ); + } + + return this; + } + + /** + * The run method must be called for the update to start working. + * The method ensures that changes are detected. + * + * ```js + * updater.run().then(() => { + * updater.enableEventProcessing(); + * }); + * ``` + * + * @summary Let the magic begin + * @return {Promise} + */ + run() { + // the key __init__has no further meaning and is only + // used to create the diff for empty objects. + this[internalSymbol].last = {__init__: true}; + return this[internalSymbol].subject.notifyObservers(); + } + + /** + * Gets the values of bound elements and changes them in subject + * + * @since 1.27.0 + * @return {Monster.DOM.Updater} + */ + retrieve() { + retrieveFromBindings.call(this); + return this; + } + + /** + * If you have passed a ProxyObserver in the constructor, you will get the object that the ProxyObserver manages here. + * However, if you passed a simple object, here you will get a proxy for that object. + * + * For changes, the ProxyObserver must be used. + * + * @since 1.8.0 + * @return {Proxy} + */ + getSubject() { + return this[internalSymbol].subject.getSubject(); + } + + /** + * This method can be used to register commands that can be called via call: instruction. + * This can be used to provide a pipe with its own functionality. + * + * @param {string} name + * @param {function} callback + * @return {Transformer} + * @throws {TypeError} value is not a string + * @throws {TypeError} value is not a function + */ + setCallback(name, callback) { + this[internalSymbol].callbacks.set(name, callback); + return this; + } } /** @@ -265,20 +275,20 @@ class Updater extends Base { * @this Updater */ function getCheckStateCallback() { - return function (current) { - // this is a reference to the current object (therefore no array function here) - if (this instanceof HTMLInputElement) { - if (["radio", "checkbox"].indexOf(this.type) !== -1) { - return `${this.value}` === `${current}` ? "true" : undefined; - } - } else if (this instanceof HTMLOptionElement) { - if (isArray(current) && current.indexOf(this.value) !== -1) { - return "true"; - } - - return undefined; - } - }; + return function (current) { + // this is a reference to the current object (therefore no array function here) + if (this instanceof HTMLInputElement) { + if (["radio", "checkbox"].indexOf(this.type) !== -1) { + return `${this.value}` === `${current}` ? "true" : undefined; + } + } else if (this instanceof HTMLOptionElement) { + if (isArray(current) && current.indexOf(this.value) !== -1) { + return "true"; + } + + return undefined; + } + }; } /** @@ -293,32 +303,41 @@ const symbol = Symbol("@schukai/monster/updater@@EventHandler"); * @throws {Error} the bind argument must start as a value with a path */ function getControlEventHandler() { - if (this[symbol]) { - return this[symbol]; - } - - /** - * @throws {Error} the bind argument must start as a value with a path. - * @throws {Error} unsupported object - * @param {Event} event - */ - this[symbol] = (event) => { - const element = findTargetElementFromEvent(event, ATTRIBUTE_UPDATER_BIND); - - if (element === undefined) { - return; - } - - queueMicrotask(() => { - try { - retrieveAndSetValue.call(this, element); - } catch (e) { - addAttributeToken(element, ATTRIBUTE_ERRORMESSAGE, e.message || `${e}`); - } - }); - }; - - return this[symbol]; + if (this[symbol]) { + return this[symbol]; + } + + /** + * @throws {Error} the bind argument must start as a value with a path. + * @throws {Error} unsupported object + * @param {Event} event + */ + this[symbol] = (event) => { + const element = findTargetElementFromEvent(event, ATTRIBUTE_UPDATER_BIND); + + if (element === undefined) { + return; + } + + if (this[timerElementEventHandlerSymbol] instanceof DeadMansSwitch) { + try { + this[timerElementEventHandlerSymbol].touch(); + return; + } catch (e) { + delete this[timerElementEventHandlerSymbol]; + } + } + + this[timerElementEventHandlerSymbol] = new DeadMansSwitch(50, () => { + try { + retrieveAndSetValue.call(this, element); + } catch (e) { + addErrorAttribute(element, e); + } + }); + }; + + return this[symbol]; } /** @@ -328,128 +347,176 @@ function getControlEventHandler() { * @private */ function retrieveAndSetValue(element) { - const pathfinder = new Pathfinder(this[internalSymbol].subject.getSubject()); - - let path = element.getAttribute(ATTRIBUTE_UPDATER_BIND); - if (path === null) - throw new Error("the bind argument must start as a value with a path"); - - if (path.indexOf("path:") !== 0) { - throw new Error("the bind argument must start as a value with a path"); - } - - path = path.substring(5); // remove path: from the string - - let value; - - if (element instanceof HTMLInputElement) { - switch (element.type) { - case "checkbox": - value = element.checked ? element.value : undefined; - break; - default: - value = element.value; - break; - } - } else if (element instanceof HTMLTextAreaElement) { - value = element.value; - } else if (element instanceof HTMLSelectElement) { - switch (element.type) { - case "select-one": - value = element.value; - break; - case "select-multiple": - value = element.value; - - let options = element?.selectedOptions; - if (options === undefined) - options = element.querySelectorAll(":scope option:checked"); - value = Array.from(options).map(({ value }) => value); - - break; - } - - // values from custom elements - } else if ( - (element?.constructor?.prototype && - !!Object.getOwnPropertyDescriptor( - element.constructor.prototype, - "value", - )?.["get"]) || - element.hasOwnProperty("value") - ) { - value = element?.["value"]; - } else { - throw new Error("unsupported object"); - } - - if (isString(value)) { - const type = element.getAttribute(ATTRIBUTE_UPDATER_BIND_TYPE); - switch (type) { - case "number": - case "int": - case "float": - case "integer": - value = Number(value); - if (isNaN(value)) { - value = 0; - } - break; - case "boolean": - case "bool": - case "checkbox": - value = value === "true" || value === "1" || value === "on"; - break; - - case "string[]": - if (value === "") { - value = []; - } - - value = value.split(",").map((v) => `${v}`); - break; - - case "int[]": - case "integer[]": - if (value === "") { - value = []; - } else { - value = value - .split(",") - .map((v) => { - try { - return parseInt(v, 10); - } catch (e) {} - return -1; - }) - .filter((v) => v !== -1); - } - - break; - case "[]": - case "array": - case "list": - value = value.split(","); - break; - case "object": - case "json": - value = JSON.parse(value); - break; - default: - break; - } - } - - const copy = clone(this[internalSymbol].subject.getRealSubject()); - - const pf = new Pathfinder(copy); - pf.setVia(path, value); - - const diffResult = diff(copy, this[internalSymbol].subject.getRealSubject()); - - if (diffResult.length > 0) { - pathfinder.setVia(path, value); - } + const pathfinder = new Pathfinder(this[internalSymbol].subject.getSubject()); + + let path = element.getAttribute(ATTRIBUTE_UPDATER_BIND); + if (path === null) + throw new Error("the bind argument must start as a value with a path"); + + if (path.indexOf("path:") !== 0) { + throw new Error("the bind argument must start as a value with a path"); + } + + path = path.substring(5); // remove path: from the string + + let value; + + if (element instanceof HTMLInputElement) { + switch (element.type) { + case "checkbox": + value = element.checked ? element.value : undefined; + break; + default: + value = element.value; + break; + } + } else if (element instanceof HTMLTextAreaElement) { + value = element.value; + } else if (element instanceof HTMLSelectElement) { + switch (element.type) { + case "select-one": + value = element.value; + break; + case "select-multiple": + value = element.value; + + let options = element?.selectedOptions; + if (options === undefined) + options = element.querySelectorAll(":scope option:checked"); + value = Array.from(options).map(({value}) => value); + + break; + } + + // values from custom elements + } else if ( + (element?.constructor?.prototype && + !!Object.getOwnPropertyDescriptor( + element.constructor.prototype, + "value", + )?.["get"]) || + element.hasOwnProperty("value") + ) { + value = element?.["value"]; + } else { + throw new Error("unsupported object"); + } + + const type = element.getAttribute(ATTRIBUTE_UPDATER_BIND_TYPE); + switch (type) { + case "number": + case "int": + case "float": + case "integer": + value = Number(value); + if (isNaN(value)) { + value = 0; + } + break; + case "boolean": + case "bool": + case "checkbox": + value = value === "true" || value === "1" || value === "on" || value === true; + break; + + case "string[]": + if (isString(value)) { + + if (value.trim() === "") { + value = []; + } else { + value = value.split(",").map((v) => `${v}`); + } + } else if (isInteger(value)) { + value = [`${value}`]; + } else if (value === undefined || value === null) { + value = []; + } else if (isArray(value)) { + value = value.map((v) => `${v}`); + } else { + throw new Error("unsupported value"); + } + + break; + + case "int[]": + case "integer[]": + + if (isString(value)) { + + if (value.trim() === "") { + value = []; + } else { + value = value.split(",").map((v) => { + try { + return parseInt(v, 10); + } catch (e) { + } + return -1; + }).filter((v) => v !== -1); + } + + } else if (isInteger(value)) { + value = [value]; + } else if (value === undefined || value === null) { + value = []; + } else if (isArray(value)) { + value = value.split(",").map((v) => { + try { + return parseInt(v, 10); + } catch (e) { + } + return -1; + }).filter((v) => v !== -1); + } else { + throw new Error("unsupported value"); + } + + break; + case "[]": + case "array": + case "list": + + if (isString(value)) { + if (value.trim() === "") { + value = []; + } else { + value = value.split(","); + } + } else if (isInteger(value)) { + value = [value]; + } else if (value === undefined || value === null) { + value = []; + } else if (isArray(value)) { + // nothing to do + } else { + throw new Error("unsupported value for array"); + } + break; + case "object": + case "json": + + if (isString(value)) { + value = JSON.parse(value); + } else { + throw new Error("unsupported value for object"); + } + + break; + default: + break; + } + + const copy = clone(this[internalSymbol].subject.getRealSubject()); + + const pf = new Pathfinder(copy); + pf.setVia(path, value); + + const diffResult = diff(copy, this[internalSymbol].subject.getRealSubject()); + + if (diffResult.length > 0) { + pathfinder.setVia(path, value); + } } /** @@ -459,15 +526,15 @@ function retrieveAndSetValue(element) { * @private */ function retrieveFromBindings() { - if (this[internalSymbol].element.matches(`[${ATTRIBUTE_UPDATER_BIND}]`)) { - retrieveAndSetValue.call(this, this[internalSymbol].element); - } - - for (const [, element] of this[internalSymbol].element - .querySelectorAll(`[${ATTRIBUTE_UPDATER_BIND}]`) - .entries()) { - retrieveAndSetValue.call(this, element); - } + if (this[internalSymbol].element.matches(`[${ATTRIBUTE_UPDATER_BIND}]`)) { + retrieveAndSetValue.call(this, this[internalSymbol].element); + } + + for (const [, element] of this[internalSymbol].element + .querySelectorAll(`[${ATTRIBUTE_UPDATER_BIND}]`) + .entries()) { + retrieveAndSetValue.call(this, element); + } } /** @@ -478,11 +545,11 @@ function retrieveFromBindings() { * @return {void} */ function removeElement(change) { - for (const [, element] of this[internalSymbol].element - .querySelectorAll(`:scope [${ATTRIBUTE_UPDATER_REMOVE}]`) - .entries()) { - element.parentNode.removeChild(element); - } + for (const [, element] of this[internalSymbol].element + .querySelectorAll(`:scope [${ATTRIBUTE_UPDATER_REMOVE}]`) + .entries()) { + element.parentNode.removeChild(element); + } } /** @@ -498,133 +565,128 @@ function removeElement(change) { * @this Updater */ function insertElement(change) { - const subject = this[internalSymbol].subject.getRealSubject(); + const subject = this[internalSymbol].subject.getRealSubject(); - const mem = new WeakSet(); - let wd = 0; + const mem = new WeakSet(); + let wd = 0; - const container = this[internalSymbol].element; + const container = this[internalSymbol].element; - while (true) { - let found = false; - wd++; - - const p = clone(change?.["path"]); - if (!isArray(p)) return; - - while (p.length > 0) { - const current = p.join("."); - - let iterator = new Set(); - const query = `[${ATTRIBUTE_UPDATER_INSERT}*="path:${current}"]`; - - const e = container.querySelectorAll(query); - - if (e.length > 0) { - iterator = new Set([...e]); - } - - if (container.matches(query)) { - iterator.add(container); - } - - for (const [, containerElement] of iterator.entries()) { - if (mem.has(containerElement)) continue; - mem.add(containerElement); - - found = true; - - const attributes = containerElement.getAttribute( - ATTRIBUTE_UPDATER_INSERT, - ); - if (attributes === null) continue; - - const def = trimSpaces(attributes); - const i = def.indexOf(" "); - const key = trimSpaces(def.substr(0, i)); - const refPrefix = `${key}-`; - const cmd = trimSpaces(def.substr(i)); - - // this case is actually excluded by the query but is nevertheless checked again here - if (cmd.indexOf("|") > 0) { - throw new Error("pipes are not allowed when cloning a node."); - } - - const pipe = new Pipe(cmd); - this[internalSymbol].callbacks.forEach((f, n) => { - pipe.setCallback(n, f); - }); - - let value; - try { - containerElement.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject); - } catch (e) { - containerElement.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); - } - - const dataPath = cmd.split(":").pop(); - - let insertPoint; - if (containerElement.hasChildNodes()) { - insertPoint = containerElement.lastChild; - } - - if (!isIterable(value)) { - throw new Error("the value is not iterable"); - } - - const available = new Set(); - - for (const [i] of Object.entries(value)) { - const ref = refPrefix + i; - const currentPath = `${dataPath}.${i}`; - - available.add(ref); - const refElement = containerElement.querySelector( - `[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}="${ref}"]`, - ); - - if (refElement instanceof HTMLElement) { - insertPoint = refElement; - continue; - } - - appendNewDocumentFragment(containerElement, key, ref, currentPath); - } - - const nodes = containerElement.querySelectorAll( - `[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}*="${refPrefix}"]`, - ); - - for (const [, node] of Object.entries(nodes)) { - if ( - !available.has( - node.getAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE), - ) - ) { - try { - containerElement.removeChild(node); - } catch (e) { - containerElement.setAttribute( - ATTRIBUTE_ERRORMESSAGE, - `${containerElement.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${ - e.message - }`.trim(), - ); - } - } - } - } - - p.pop(); - } - - if (found === false) break; - if (wd++ > 200) { - throw new Error("the maximum depth for the recursion is reached."); - } - } + while (true) { + let found = false; + wd++; + + const p = clone(change?.["path"]); + if (!isArray(p)) return; + + while (p.length > 0) { + const current = p.join("."); + + let iterator = new Set(); + const query = `[${ATTRIBUTE_UPDATER_INSERT}*="path:${current}"]`; + + const e = container.querySelectorAll(query); + + if (e.length > 0) { + iterator = new Set([...e]); + } + + if (container.matches(query)) { + iterator.add(container); + } + + for (const [, containerElement] of iterator.entries()) { + if (mem.has(containerElement)) continue; + mem.add(containerElement); + + found = true; + + const attributes = containerElement.getAttribute( + ATTRIBUTE_UPDATER_INSERT, + ); + if (attributes === null) continue; + + const def = trimSpaces(attributes); + const i = def.indexOf(" "); + const key = trimSpaces(def.substr(0, i)); + const refPrefix = `${key}-`; + const cmd = trimSpaces(def.substr(i)); + + // this case is actually excluded by the query but is nevertheless checked again here + if (cmd.indexOf("|") > 0) { + throw new Error("pipes are not allowed when cloning a node."); + } + + const pipe = new Pipe(cmd); + this[internalSymbol].callbacks.forEach((f, n) => { + pipe.setCallback(n, f); + }); + + let value; + try { + containerElement.removeAttribute(ATTRIBUTE_ERRORMESSAGE); + value = pipe.run(subject); + } catch (e) { + addErrorAttribute(containerElement, e); + } + + const dataPath = cmd.split(":").pop(); + + let insertPoint; + if (containerElement.hasChildNodes()) { + insertPoint = containerElement.lastChild; + } + + if (!isIterable(value)) { + throw new Error("the value is not iterable"); + } + + const available = new Set(); + + for (const [i] of Object.entries(value)) { + const ref = refPrefix + i; + const currentPath = `${dataPath}.${i}`; + + available.add(ref); + const refElement = containerElement.querySelector( + `[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}="${ref}"]`, + ); + + if (refElement instanceof HTMLElement) { + insertPoint = refElement; + continue; + } + + appendNewDocumentFragment(containerElement, key, ref, currentPath); + } + + const nodes = containerElement.querySelectorAll( + `[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}*="${refPrefix}"]`, + ); + + for (const [, node] of Object.entries(nodes)) { + if ( + !available.has( + node.getAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE), + ) + ) { + try { + containerElement.removeChild(node); + } catch (e) { + addErrorAttribute(containerElement, e); + } + } + } + } + + p.pop(); + } + + if (found === false) break; + if (wd++ > 200) { + throw new Error("the maximum depth for the recursion is reached."); + } + } } /** @@ -639,17 +701,17 @@ function insertElement(change) { * @throws {Error} no template was found with the specified key. */ function appendNewDocumentFragment(container, key, ref, path) { - const template = findDocumentTemplate(key, container); + const template = findDocumentTemplate(key, container); - const nodes = template.createDocumentFragment(); - for (const [, node] of Object.entries(nodes.childNodes)) { - if (node instanceof HTMLElement) { - applyRecursive(node, key, path); - node.setAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE, ref); - } + const nodes = template.createDocumentFragment(); + for (const [, node] of Object.entries(nodes.childNodes)) { + if (node instanceof HTMLElement) { + applyRecursive(node, key, path); + node.setAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE, ref); + } - container.appendChild(node); - } + container.appendChild(node); + } } /** @@ -662,27 +724,32 @@ function appendNewDocumentFragment(container, key, ref, path) { * @return {void} */ function applyRecursive(node, key, path) { - if (node instanceof HTMLElement) { - if (node.hasAttribute(ATTRIBUTE_UPDATER_REPLACE)) { - const value = node.getAttribute(ATTRIBUTE_UPDATER_REPLACE); - node.setAttribute( - ATTRIBUTE_UPDATER_REPLACE, - value.replaceAll(`path:${key}`, `path:${path}`), - ); - } - - if (node.hasAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES)) { - const value = node.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES); - node.setAttribute( - ATTRIBUTE_UPDATER_ATTRIBUTES, - value.replaceAll(`path:${key}`, `path:${path}`), - ); - } - - for (const [, child] of Object.entries(node.childNodes)) { - applyRecursive(child, key, path); - } - } + if (!(node instanceof HTMLElement)) { + return + } + + if (node.hasAttribute(ATTRIBUTE_UPDATER_REPLACE)) { + const value = node.getAttribute(ATTRIBUTE_UPDATER_REPLACE); + node.setAttribute( + ATTRIBUTE_UPDATER_REPLACE, + value.replaceAll(`path:${key}`, `path:${path}`), + ); + } + + if (node.hasAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES)) { + const value = node.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES); + node.setAttribute( + ATTRIBUTE_UPDATER_ATTRIBUTES, + value.replaceAll(`path:${key}`, `path:${path}`), + ); + } + + for (const [, child] of Object.entries(node.childNodes)) { + if (child instanceof HTMLElement) { + applyRecursive(child, key, path); + } + } + } /** @@ -694,19 +761,19 @@ function applyRecursive(node, key, path) { * @this Updater */ function updateContent(change) { - const subject = this[internalSymbol].subject.getRealSubject(); - - const p = clone(change?.["path"]); - runUpdateContent.call(this, this[internalSymbol].element, p, subject); - - const slots = this[internalSymbol].element.querySelectorAll("slot"); - if (slots.length > 0) { - for (const [, slot] of Object.entries(slots)) { - for (const [, element] of Object.entries(slot.assignedNodes())) { - runUpdateContent.call(this, element, p, subject); - } - } - } + const subject = this[internalSymbol].subject.getRealSubject(); + + const p = clone(change?.["path"]); + runUpdateContent.call(this, this[internalSymbol].element, p, subject); + + const slots = this[internalSymbol].element.querySelectorAll("slot"); + if (slots.length > 0) { + for (const [, slot] of Object.entries(slots)) { + for (const [, element] of Object.entries(slot.assignedNodes())) { + runUpdateContent.call(this, element, p, subject); + } + } + } } /** @@ -719,69 +786,64 @@ function updateContent(change) { * @return {void} */ function runUpdateContent(container, parts, subject) { - if (!isArray(parts)) return; - if (!(container instanceof HTMLElement)) return; - parts = clone(parts); - - const mem = new WeakSet(); - - while (parts.length > 0) { - const current = parts.join("."); - parts.pop(); - - // Unfortunately, static data is always changed as well, since it is not possible to react to changes here. - const query = `[${ATTRIBUTE_UPDATER_REPLACE}^="path:${current}"], [${ATTRIBUTE_UPDATER_REPLACE}^="static:"], [${ATTRIBUTE_UPDATER_REPLACE}^="i18n:"]`; - const e = container.querySelectorAll(`${query}`); - - const iterator = new Set([...e]); - - if (container.matches(query)) { - iterator.add(container); - } - - /** - * @type {HTMLElement} - */ - for (const [element] of iterator.entries()) { - if (mem.has(element)) return; - mem.add(element); - - const attributes = element.getAttribute(ATTRIBUTE_UPDATER_REPLACE); - const cmd = trimSpaces(attributes); - - const pipe = new Pipe(cmd); - this[internalSymbol].callbacks.forEach((f, n) => { - pipe.setCallback(n, f); - }); - - let value; - try { - element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject); - } catch (e) { - element.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); - } - - if (value instanceof HTMLElement) { - while (element.firstChild) { - element.removeChild(element.firstChild); - } - - try { - element.appendChild(value); - } catch (e) { - element.setAttribute( - ATTRIBUTE_ERRORMESSAGE, - `${element.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${ - e.message - }`.trim(), - ); - } - } else { - element.innerHTML = value; - } - } - } + if (!isArray(parts)) return; + if (!(container instanceof HTMLElement)) return; + parts = clone(parts); + + const mem = new WeakSet(); + + while (parts.length > 0) { + const current = parts.join("."); + parts.pop(); + + // Unfortunately, static data is always changed as well, since it is not possible to react to changes here. + const query = `[${ATTRIBUTE_UPDATER_REPLACE}^="path:${current}"], [${ATTRIBUTE_UPDATER_REPLACE}^="static:"], [${ATTRIBUTE_UPDATER_REPLACE}^="i18n:"]`; + const e = container.querySelectorAll(`${query}`); + + const iterator = new Set([...e]); + + if (container.matches(query)) { + iterator.add(container); + } + + /** + * @type {HTMLElement} + */ + for (const [element] of iterator.entries()) { + if (mem.has(element)) return; + mem.add(element); + + const attributes = element.getAttribute(ATTRIBUTE_UPDATER_REPLACE); + const cmd = trimSpaces(attributes); + + const pipe = new Pipe(cmd); + this[internalSymbol].callbacks.forEach((f, n) => { + pipe.setCallback(n, f); + }); + + let value; + try { + element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); + value = pipe.run(subject); + } catch (e) { + element.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); + } + + if (value instanceof HTMLElement) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + + try { + element.appendChild(value); + } catch (e) { + addErrorAttribute(element, e); + } + } else { + element.innerHTML = value; + } + } + } } /** @@ -791,9 +853,9 @@ function runUpdateContent(container, parts, subject) { * @return {void} */ function updateAttributes(change) { - const subject = this[internalSymbol].subject.getRealSubject(); - const p = clone(change?.["path"]); - runUpdateAttributes.call(this, this[internalSymbol].element, p, subject); + const subject = this[internalSymbol].subject.getRealSubject(); + const p = clone(change?.["path"]); + runUpdateAttributes.call(this, this[internalSymbol].element, p, subject); } /** @@ -805,70 +867,70 @@ function updateAttributes(change) { * @this Updater */ function runUpdateAttributes(container, parts, subject) { - if (!isArray(parts)) return; - parts = clone(parts); + if (!isArray(parts)) return; + parts = clone(parts); - const mem = new WeakSet(); + const mem = new WeakSet(); - while (parts.length > 0) { - const current = parts.join("."); - parts.pop(); + while (parts.length > 0) { + const current = parts.join("."); + parts.pop(); - let iterator = new Set(); + let iterator = new Set(); - const query = `[${ATTRIBUTE_UPDATER_SELECT_THIS}][${ATTRIBUTE_UPDATER_ATTRIBUTES}], [${ATTRIBUTE_UPDATER_ATTRIBUTES}*="path:${current}"], [${ATTRIBUTE_UPDATER_ATTRIBUTES}^="static:"], [${ATTRIBUTE_UPDATER_ATTRIBUTES}^="i18n:"]`; + const query = `[${ATTRIBUTE_UPDATER_SELECT_THIS}][${ATTRIBUTE_UPDATER_ATTRIBUTES}], [${ATTRIBUTE_UPDATER_ATTRIBUTES}*="path:${current}"], [${ATTRIBUTE_UPDATER_ATTRIBUTES}^="static:"], [${ATTRIBUTE_UPDATER_ATTRIBUTES}^="i18n:"]`; - const e = container.querySelectorAll(query); + const e = container.querySelectorAll(query); - if (e.length > 0) { - iterator = new Set([...e]); - } + if (e.length > 0) { + iterator = new Set([...e]); + } - if (container.matches(query)) { - iterator.add(container); - } + if (container.matches(query)) { + iterator.add(container); + } - for (const [element] of iterator.entries()) { - if (mem.has(element)) return; - mem.add(element); + for (const [element] of iterator.entries()) { + if (mem.has(element)) return; + mem.add(element); - // this case occurs when the ATTRIBUTE_UPDATER_SELECT_THIS attribute is set - if (!element.hasAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES)) { - continue; - } + // this case occurs when the ATTRIBUTE_UPDATER_SELECT_THIS attribute is set + if (!element.hasAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES)) { + continue; + } - const attributes = element.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES); + const attributes = element.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES); - for (let [, def] of Object.entries(attributes.split(","))) { - def = trimSpaces(def); - const i = def.indexOf(" "); - const name = trimSpaces(def.substr(0, i)); - const cmd = trimSpaces(def.substr(i)); + for (let [, def] of Object.entries(attributes.split(","))) { + def = trimSpaces(def); + const i = def.indexOf(" "); + const name = trimSpaces(def.substr(0, i)); + const cmd = trimSpaces(def.substr(i)); - const pipe = new Pipe(cmd); + const pipe = new Pipe(cmd); - this[internalSymbol].callbacks.forEach((f, n) => { - pipe.setCallback(n, f, element); - }); + this[internalSymbol].callbacks.forEach((f, n) => { + pipe.setCallback(n, f, element); + }); - let value; - try { - element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject); - } catch (e) { - element.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); - } + let value; + try { + element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); + value = pipe.run(subject); + } catch (e) { + addErrorAttribute(element, e); + } - if (value === undefined) { - element.removeAttribute(name); - } else if (element.getAttribute(name) !== value) { - element.setAttribute(name, value); - } + if (value === undefined) { + element.removeAttribute(name); + } else if (element.getAttribute(name) !== value) { + element.setAttribute(name, value); + } - handleInputControlAttributeUpdate.call(this, element, name, value); - } - } - } + handleInputControlAttributeUpdate.call(this, element, name, value); + } + } + } } /** @@ -881,52 +943,52 @@ function runUpdateAttributes(container, parts, subject) { */ function handleInputControlAttributeUpdate(element, name, value) { - if (element instanceof HTMLSelectElement) { - switch (element.type) { - case "select-multiple": - for (const [index, opt] of Object.entries(element.options)) { - opt.selected = value.indexOf(opt.value) !== -1; - } - - break; - case "select-one": - // Only one value may be selected - - for (const [index, opt] of Object.entries(element.options)) { - if (opt.value === value) { - element.selectedIndex = index; - break; - } - } - - break; - } - } else if (element instanceof HTMLInputElement) { - switch (element.type) { - case "radio": - if (name === "checked") { - element.checked = value !== undefined; - } - break; - - case "checkbox": - if (name === "checked") { - element.checked = value !== undefined; - } - break; - - case "text": - default: - if (name === "value") { - element.value = value === undefined ? "" : value; - } - break; - } - } else if (element instanceof HTMLTextAreaElement) { - if (name === "value") { - element.value = value === undefined ? "" : value; - } - } + if (element instanceof HTMLSelectElement) { + switch (element.type) { + case "select-multiple": + for (const [index, opt] of Object.entries(element.options)) { + opt.selected = value.indexOf(opt.value) !== -1; + } + + break; + case "select-one": + // Only one value may be selected + + for (const [index, opt] of Object.entries(element.options)) { + if (opt.value === value) { + element.selectedIndex = index; + break; + } + } + + break; + } + } else if (element instanceof HTMLInputElement) { + switch (element.type) { + case "radio": + if (name === "checked") { + element.checked = value !== undefined; + } + break; + + case "checkbox": + if (name === "checked") { + element.checked = value !== undefined; + } + break; + + case "text": + default: + if (name === "value") { + element.value = value === undefined ? "" : value; + } + break; + } + } else if (element instanceof HTMLTextAreaElement) { + if (name === "value") { + element.value = value === undefined ? "" : value; + } + } } /** @@ -945,83 +1007,78 @@ function handleInputControlAttributeUpdate(element, name, value) { * @throws {TypeError} symbol must be an instance of Symbol */ function addObjectWithUpdaterToElement(elements, symbol, object, config = {}) { - if (!(this instanceof HTMLElement)) { - throw new TypeError( - "the context of this function must be an instance of HTMLElement", - ); - } - - if (!(typeof symbol === "symbol")) { - throw new TypeError("symbol must be an instance of Symbol"); - } - - const updaters = new Set(); - - if (elements instanceof NodeList) { - elements = new Set([...elements]); - } else if (elements instanceof HTMLElement) { - elements = new Set([elements]); - } else if (elements instanceof Set) { - } else { - throw new TypeError( - `elements is not a valid type. (actual: ${typeof elements})`, - ); - } - - const result = []; - - const updaterCallbacks = []; - const cb = this?.[updaterTransformerMethodsSymbol]; - if (this instanceof HTMLElement && typeof cb === "function") { - const callbacks = cb.call(this); - if (typeof callbacks === "object") { - for (const [name, callback] of Object.entries(callbacks)) { - if (typeof callback === "function") { - updaterCallbacks.push([name, callback]); - } else { - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - `onUpdaterPipeCallbacks: ${name} is not a function`, - ); - } - } - } else { - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - `onUpdaterPipeCallbacks do not return an object with functions`, - ); - } - } - - elements.forEach((element) => { - if (!(element instanceof HTMLElement)) return; - if (element instanceof HTMLTemplateElement) return; - - const u = new Updater(element, object); - updaters.add(u); - - if (updaterCallbacks.length > 0) { - for (const [name, callback] of updaterCallbacks) { - u.setCallback(name, callback); - } - } - - result.push( - u.run().then(() => { - if (config.eventProcessing === true) { - u.enableEventProcessing(); - } - - return u; - }), - ); - }); - - if (updaters.size > 0) { - addToObjectLink(this, symbol, updaters); - } - - return result; + if (!(this instanceof HTMLElement)) { + throw new TypeError( + "the context of this function must be an instance of HTMLElement", + ); + } + + if (!(typeof symbol === "symbol")) { + throw new TypeError("symbol must be an instance of Symbol"); + } + + const updaters = new Set(); + + if (elements instanceof NodeList) { + elements = new Set([...elements]); + } else if (elements instanceof HTMLElement) { + elements = new Set([elements]); + } else if (elements instanceof Set) { + } else { + throw new TypeError( + `elements is not a valid type. (actual: ${typeof elements})`, + ); + } + + const result = []; + + const updaterCallbacks = []; + const cb = this?.[updaterTransformerMethodsSymbol]; + if (this instanceof HTMLElement && typeof cb === "function") { + const callbacks = cb.call(this); + if (typeof callbacks === "object") { + for (const [name, callback] of Object.entries(callbacks)) { + if (typeof callback === "function") { + updaterCallbacks.push([name, callback]); + } else { + addErrorAttribute(this, `onUpdaterPipeCallbacks: ${name} is not a function`); + } + } + } else { + addErrorAttribute( + this, + `onUpdaterPipeCallbacks do not return an object with functions` + ); + } + } + + elements.forEach((element) => { + if (!(element instanceof HTMLElement)) return; + if (element instanceof HTMLTemplateElement) return; + + const u = new Updater(element, object); + updaters.add(u); + + if (updaterCallbacks.length > 0) { + for (const [name, callback] of updaterCallbacks) { + u.setCallback(name, callback); + } + } + + result.push( + u.run().then(() => { + if (config.eventProcessing === true) { + u.enableEventProcessing(); + } + + return u; + }), + ); + }); + + if (updaters.size > 0) { + addToObjectLink(this, symbol, updaters); + } + + return result; }