From b355ac89c1563f0766dd77e0b7b1eac0682393af Mon Sep 17 00:00:00 2001 From: Volker Schukai <volker.schukai@schukai.com> Date: Mon, 30 Dec 2024 14:32:39 +0100 Subject: [PATCH] chore: update doc, small issues, etc #274 --- development/issues/{open => closed}/272.html | 2 +- development/issues/{open => closed}/272.mjs | 0 development/issues/open/274.html | 108 + development/issues/open/274.mjs | 26 + development/mock/issue-274.js | 289 ++ source/components/content/copy.mjs | 2 +- source/components/datatable/dataset.mjs | 14 +- .../components/datatable/datasource/rest.mjs | 6 +- source/components/datatable/pagination.mjs | 2 +- source/components/form/api-bar.mjs | 2 +- source/components/form/api-button.mjs | 2 +- source/components/form/button-bar.mjs | 2 +- source/components/form/button.mjs | 4 +- source/components/form/confirm-button.mjs | 2 +- source/components/form/form.mjs | 12 +- source/components/form/select.mjs | 4020 +++++++++-------- source/components/layout/tabs.mjs | 6 +- source/components/layout/width-toggle.mjs | 2 +- .../navigation/table-of-content.mjs | 2 +- source/components/notify/message.mjs | 2 +- source/components/notify/notify.mjs | 4 +- source/components/state/log.mjs | 2 +- source/components/state/state.mjs | 2 +- source/dom/constants.mjs | 13 +- source/dom/updater.mjs | 9 +- 25 files changed, 2484 insertions(+), 2051 deletions(-) rename development/issues/{open => closed}/272.html (99%) rename development/issues/{open => closed}/272.mjs (100%) create mode 100644 development/issues/open/274.html create mode 100644 development/issues/open/274.mjs create mode 100644 development/mock/issue-274.js diff --git a/development/issues/open/272.html b/development/issues/closed/272.html similarity index 99% rename from development/issues/open/272.html rename to development/issues/closed/272.html index 2fe8e354d..daba14ea0 100644 --- a/development/issues/open/272.html +++ b/development/issues/closed/272.html @@ -4,7 +4,7 @@ <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>check and update data save button #272</title> - <script src="./272.mjs" type="module"></script> + <script src="272.mjs" type="module"></script> </head> <body> <h1>check and update pagination and dataset #272</h1> diff --git a/development/issues/open/272.mjs b/development/issues/closed/272.mjs similarity index 100% rename from development/issues/open/272.mjs rename to development/issues/closed/272.mjs diff --git a/development/issues/open/274.html b/development/issues/open/274.html new file mode 100644 index 000000000..17f20cc85 --- /dev/null +++ b/development/issues/open/274.html @@ -0,0 +1,108 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>update and check form, button and datasources #274</title> + <script src="./274.mjs" type="module"></script> +</head> +<body> + <h1>update and check form, button and datasources #274</h1> + <p></p> + <ul> + <li><a href="https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/274">Issue #274</a></li> + <li><a href="/">Back to overview</a></li> + </ul> + <main> + + <h2>Control with DOM datasource</h2> + <monster-datasource-rest id="ds274-r" + data-monster-option-features-autoInit="true" + data-monster-option-write-url="/issue-274.json" + data-monster-option-read-url="/issue-274.json?limit=1&page=${page}" + ></monster-datasource-rest> + + <monster-pagination + data-monster-option-datasource-selector="#ds274-r" + data-monster-option-objectsperpage="1" + ></monster-pagination> + + <hr> + <monster-form + id="ds-274" + data-monster-option-datasource-selector="#ds274-r"> + + <div style="display: grid; grid-template-columns: 1fr 1fr;gap: 0.1rem;width: 600px"> + <div>ID</div> + <input data-monster-attributes="value path:data.id | tostring" data-monster-bind="path:data.id"> + <div>Username</div> + <input data-monster-attributes="value path:data.username" data-monster-bind="path:data.username"> + <div>Full Name</div> + <input data-monster-attributes="value path:data.full_name" data-monster-bind="path:data.full_name"> + <div>Email</div> + <input data-monster-attributes="value path:data.email" data-monster-bind="path:data.email"> + <div>Age</div> + <input data-monster-attributes="value path:data.age" data-monster-bind="path:data.age"> + <div>Registered Date</div> + <input data-monster-attributes="value path:data.registered_date" data-monster-bind="path:data.registered_date"> + <div>Country</div> + <monster-select data-monster-attributes="value path:data.country" data-monster-bind="path:data.country"> + <div data-monster-value="de">de</div> + <div data-monster-value="en">en</div> + <div data-monster-value="fr">fr</div> + </monster-select> + <div>Status</div> + <monster-toggle-switch data-monster-attributes="value path:data.status" data-monster-bind="path:data.status" + data-monster-option-values-on="active" data-monster-option-values-off="inactive"></monster-toggle-switch> + <!-- monster-toggle-switch data-monster-attributes="value path:data.status" data-monster-bind="path:data.status"></monster-toggle-switch --> + </div> + + </monster-form> + + + <monster-pagination + data-monster-option-datasource-selector="#ds274-r" + data-monster-option-objectsperpage="1" + ></monster-pagination> + + + + <hr> + <hr> + <hr> + <hr> +<h3>Check output</h3> + <monster-dataset + + data-monster-option-datasource-selector="#ds274-r"> + + <div style="display: grid; grid-template-columns: 1fr 1fr;gap: 0.1rem;width: 600px"> + <div>ID</div> + <input data-monster-attributes="value path:data.id"> + <div>Username</div> + <input data-monster-attributes="value path:data.username"> + <div>Full Name</div> + <input data-monster-attributes="value path:data.full_name"> + <div>Email</div> + <input data-monster-attributes="value path:data.email"> + <div>Age</div> + <input data-monster-attributes="value path:data.age"> + <div>Country</div> + <input data-monster-attributes="value path:data.country"> + <div>Registered Date</div> + <input data-monster-attributes="value path:data.registered_date"> + <div>Status</div> + <input data-monster-attributes="value path:data.status"> + + <monster-toggle-switch data-monster-attributes="value path:data.status" + data-monster-option-values-on="active" data-monster-option-values-off="inactive"></monster-toggle-switch> + + </div> + + </monster-dataset> + + + + </main> +</body> +</html> \ No newline at end of file diff --git a/development/issues/open/274.mjs b/development/issues/open/274.mjs new file mode 100644 index 000000000..21eb41223 --- /dev/null +++ b/development/issues/open/274.mjs @@ -0,0 +1,26 @@ +/** + * @file development/issues/open/274.mjs + * @url https://gitlab.schukai.com/oss/libraries/javascript/monster/-/issues/274 + * @description update and check form, button and datasources + * @issue 274 + */ + + +import "../../../source/components/style/property.pcss"; +import "../../../source/components/style/link.pcss"; +import "../../../source/components/style/color.pcss"; +import "../../../source/components/style/theme.pcss"; +import "../../../source/components/style/normalize.pcss"; +import "../../../source/components/style/typography.pcss"; +import "../../../source/components/datatable/datasource/rest.mjs"; +import "../../../source/components/datatable/datasource/dom.mjs"; +import "../../../source/components/datatable/dataset.mjs"; +import "../../../source/components/datatable/pagination.mjs"; +import "../../../source/components/form/button.mjs"; +import "../../../source/components/form/form.mjs"; +import "../../../source/components/form/button-bar.mjs"; +import "../../../source/components/form/toggle-switch.mjs"; + +// DOM-Elemente für die Seiten-Datensätze +const pageData1 = document.getElementById("ds274-d"); +const pageData2 = document.getElementById("ds274-r"); diff --git a/development/mock/issue-274.js b/development/mock/issue-274.js new file mode 100644 index 000000000..6e0a0ca3e --- /dev/null +++ b/development/mock/issue-274.js @@ -0,0 +1,289 @@ +const json = + `[{ + "id": 1, + "username": "wernerjennifer", + "email": "smithchristina@clark.biz", + "full_name": "Joshua Smith", + "age": 28, + "country": "Central African Republic", + "registered_date": "2020-01-17", + "status": "active" + }, + { + "id": 2, + "username": "elizabethmurphy", + "email": "beverlywarren@gmail.com", + "full_name": "Sarah Snyder", + "age": 18, + "country": "Tajikistan", + "registered_date": "2023-05-10", + "status": "banned" + }, + { + "id": 3, + "username": "ftaylor", + "email": "deckercassandra@conrad.com", + "full_name": "Rhonda Carroll", + "age": 34, + "country": "Australia", + "registered_date": "2022-07-31", + "status": "inactive" + }, + { + "id": 4, + "username": "antoniocastillo", + "email": "tevans@hotmail.com", + "full_name": "Brad Brown", + "age": 39, + "country": "Nepal", + "registered_date": "2023-01-09", + "status": "banned" + }, + { + "id": 5, + "username": "dylan46", + "email": "audreywalter@watts-conley.com", + "full_name": "Jacqueline Turner", + "age": 26, + "country": "United States Minor Outlying Islands", + "registered_date": "2024-10-14", + "status": "inactive" + }, + { + "id": 6, + "username": "michael27", + "email": "thompsonsydney@gmail.com", + "full_name": "Stephanie Walls", + "age": 25, + "country": "Switzerland", + "registered_date": "2020-05-20", + "status": "inactive" + }, + { + "id": 7, + "username": "vickie92", + "email": "mary35@jackson.com", + "full_name": "Colin Cohen", + "age": 23, + "country": "Saint Martin", + "registered_date": "2022-12-31", + "status": "active" + }, + { + "id": 8, + "username": "fordomar", + "email": "hernandezbrian@gmail.com", + "full_name": "Christopher Garza", + "age": 65, + "country": "Antigua and Barbuda", + "registered_date": "2022-08-15", + "status": "banned" + }, + { + "id": 9, + "username": "jerry82", + "email": "nwhite@yahoo.com", + "full_name": "Gabrielle Garza", + "age": 46, + "country": "Mauritania", + "registered_date": "2023-03-08", + "status": "inactive" + }, + { + "id": 10, + "username": "alyssa54", + "email": "kevin11@hotmail.com", + "full_name": "Andrea Williams", + "age": 43, + "country": "Western Sahara", + "registered_date": "2023-04-19", + "status": "active" + }, + { + "id": 11, + "username": "jacob30", + "email": "scottmary@yahoo.com", + "full_name": "Nicole Cunningham", + "age": 29, + "country": "French Polynesia", + "registered_date": "2022-02-21", + "status": "banned" + }, + { + "id": 12, + "username": "ftucker", + "email": "simmonsrichard@jones.com", + "full_name": "Daniel Shelton", + "age": 42, + "country": "Cameroon", + "registered_date": "2024-04-20", + "status": "active" + }, + { + "id": 13, + "username": "alvarezpaul", + "email": "ucannon@ortega.biz", + "full_name": "Matthew Poole", + "age": 44, + "country": "Chad", + "registered_date": "2021-09-22", + "status": "inactive" + }, + { + "id": 14, + "username": "sarahunter", + "email": "allisoncharles@phillips-graves.com", + "full_name": "Nathan Fernandez", + "age": 40, + "country": "French Polynesia", + "registered_date": "2023-04-11", + "status": "inactive" + }, + { + "id": 15, + "username": "sierra65", + "email": "hnicholson@gmail.com", + "full_name": "Michael Taylor", + "age": 27, + "country": "Indonesia", + "registered_date": "2021-08-15", + "status": "active" + }, + { + "id": 16, + "username": "benjamin84", + "email": "zgallegos@hale-johnson.com", + "full_name": "Molly Santana", + "age": 32, + "country": "Holy See (Vatican City State)", + "registered_date": "2023-06-09", + "status": "inactive" + }, + { + "id": 17, + "username": "peckpaul", + "email": "james03@hotmail.com", + "full_name": "Kelly Allen", + "age": 42, + "country": "Austria", + "registered_date": "2021-04-26", + "status": "active" + }, + { + "id": 18, + "username": "jill42", + "email": "williamstephenson@hotmail.com", + "full_name": "Samuel Adkins", + "age": 22, + "country": "American Samoa", + "registered_date": "2024-10-04", + "status": "active" + }, + { + "id": 19, + "username": "pottssavannah", + "email": "emily76@mckinney.com", + "full_name": "Jeremy Pearson", + "age": 42, + "country": "Lesotho", + "registered_date": "2020-06-15", + "status": "inactive" + }, + { + "id": 20, + "username": "robertsdaniel", + "email": "robinsontodd@pineda.org", + "full_name": "Francis Castaneda", + "age": 58, + "country": "British Indian Ocean Territory (Chagos Archipelago)", + "registered_date": "2020-03-01", + "status": "inactive" + } + ] +`; + + +// check if JSON is valid +const objects = JSON.parse(json) +if (!Array.isArray(objects)) { + throw new Error('Invalid JSON') +} + +const requestDelay = 10 + +function wrapJsonWithPagination(data, page, limit) { + return JSON.stringify({ + dataset: data, + sys: { + pagination: { + objectsPerPage: limit, + pages: Math.ceil(objects.length / limit), + currentPage: page + } + } + }) +} + +export default [ + { + url: '/issue-274.json', + method: 'get', + rawResponse: async (req, res) => { + res.setHeader('Content-Type', 'application/json') + res.statusCode = 200 + + const url = new URL(req.url, `http://${req.headers.host}`) + const q = Object.fromEntries(url.searchParams) + + let filtered = objects + + if (q) { + + let limit = 20 + + if (q.limit) { + limit = parseInt(q.limit) + } + + if (q.page) { + const page = parseInt(q.page) + const start = (page - 1) * limit + const end = start + limit + filtered = objects.slice(start, end) + } else { + filtered = objects.slice(0, limit) + } + + if (q.q) { + const query = q.q.toLowerCase() + filtered = objects.filter(item => item.name.toLowerCase().includes(query)) + + } + + setTimeout(function () { + res.end(wrapJsonWithPagination(filtered, q.page || 1, limit)) + }, requestDelay); + + return + } + + setTimeout(function () { + res.end(wrapJsonWithPagination(filtered, 1, 20)) + }, requestDelay); + + }, + }, + { + url: '/issue-274.json', + method: 'post', + rawResponse: async (req, res) => { + res.setHeader('Content-Type', 'application/json') + res.statusCode = 200 + + const jsonRespond = JSON.stringify({message: "Data has been successfully saved"}) + + res.end(jsonRespond) + } + } + +]; \ No newline at end of file diff --git a/source/components/content/copy.mjs b/source/components/content/copy.mjs index 439017f5f..6ee6bc632 100644 --- a/source/components/content/copy.mjs +++ b/source/components/content/copy.mjs @@ -84,7 +84,7 @@ const resizeObserverSymbol = Symbol("resizeObserver"); * * @fragments /fragments/components/content/copy/ * - * @example /examples/components/content/copy-simple + * @example /examples/components/content/copy-simple Copy * * @since 3.77.0 * @copyright schukai GmbH diff --git a/source/components/datatable/dataset.mjs b/source/components/datatable/dataset.mjs index 105a02f61..94cac6f9b 100644 --- a/source/components/datatable/dataset.mjs +++ b/source/components/datatable/dataset.mjs @@ -20,7 +20,7 @@ import { attributeObserverSymbol, registerCustomElement, } from "../../dom/customelement.mjs"; -import {findElementWithSelectorUpwards} from "../../dom/util.mjs"; +import {findElementWithSelectorUpwards, getDocument, getWindow} from "../../dom/util.mjs"; import {isString} from "../../types/is.mjs"; import {Observer} from "../../types/observer.mjs"; import { @@ -42,8 +42,8 @@ export {DataSet}; * * @fragments /fragments/components/datatable/dataset * - * @example /examples/components/datatable/dataset-dom - * @example /examples/components/datatable/dataset-rest + * @example /examples/components/datatable/dataset-dom Dom dataset + * @example /examples/components/datatable/dataset-rest Rest dataset * * @issue https://localhost.alvine.dev:8443/development/issues/closed/272.html * @@ -56,7 +56,7 @@ class DataSet extends CustomElement { * @return {symbol} */ static get [instanceSymbol]() { - return Symbol.for("@schukai/monster/components/dataset@@instance"); + return Symbol.for("@schukai/monster/components/datatable/dataset@@instance"); } /** @@ -118,7 +118,7 @@ class DataSet extends CustomElement { * @type {boolean} */ refreshOnMutation: { - selector: "input, select, textarea", + selector: "input, select, textarea, monster-select, monster-toggle-switch", }, data: {}, @@ -139,12 +139,12 @@ class DataSet extends CustomElement { /** * This method is called when the component is created. * @since 3.70.0 - * @return {DataSet} + * @return {Promise} */ refresh() { // makes sure that handleDataSourceChanges is called this.setOption("data", {}); - return this; + return Promise.resolve(this); } /** diff --git a/source/components/datatable/datasource/rest.mjs b/source/components/datatable/datasource/rest.mjs index 3aecdfc81..f477118a6 100644 --- a/source/components/datatable/datasource/rest.mjs +++ b/source/components/datatable/datasource/rest.mjs @@ -68,9 +68,9 @@ const filterObserverSymbol = Symbol("filterObserver"); * * @fragments /fragments/components/datatable/datasource/rest * - * @example /examples/components/datatable/datasource-rest-simple - * @example /examples/components/datatable/datasource-rest-auto-init - * @example /examples/components/datatable/datasource-rest-do-fetch + * @example /examples/components/datatable/datasource-rest-simple Simple Rest datasource + * @example /examples/components/datatable/datasource-rest-auto-init Auto init + * @example /examples/components/datatable/datasource-rest-do-fetch Rest datasource with fetch * * @issue https://localhost.alvine.dev:8443/development/issues/closed/272.html * diff --git a/source/components/datatable/pagination.mjs b/source/components/datatable/pagination.mjs index 89f5a22bf..ce0f23fa1 100644 --- a/source/components/datatable/pagination.mjs +++ b/source/components/datatable/pagination.mjs @@ -75,7 +75,7 @@ const debounceSizeSymbol = Symbol("debounceSize"); * * @fragments /fragments/components/datatable/pagination * - * @example /examples/components/datatable/pagination-simple + * @example /examples/components/datatable/pagination-simple Pagination * * @copyright schukai GmbH * @summary The Pagination component is used to show the current page and the total number of pages. diff --git a/source/components/form/api-bar.mjs b/source/components/form/api-bar.mjs index b37bd0cb1..e0310cbea 100644 --- a/source/components/form/api-bar.mjs +++ b/source/components/form/api-bar.mjs @@ -51,7 +51,7 @@ export { ApiBar }; * * @fragments /fragments/components/form/api-bar/ * - * @example /examples/components/form/api-bar-simple + * @example /examples/components/form/api-bar-simple API Bar * * @since 3.90.0 * @copyright schukai GmbH diff --git a/source/components/form/api-button.mjs b/source/components/form/api-button.mjs index 07a8a44c2..62c48f1c5 100644 --- a/source/components/form/api-button.mjs +++ b/source/components/form/api-button.mjs @@ -56,7 +56,7 @@ const containerElementSymbol = Symbol("containerElement"); * * @fragments /fragments/components/form/api-button/ * - * @example /examples/components/form/api-button-simple + * @example /examples/components/form/api-button-simple API Button * * @since 3.32.0 * @copyright schukai GmbH diff --git a/source/components/form/button-bar.mjs b/source/components/form/button-bar.mjs index 169dc260b..ab2791c9f 100644 --- a/source/components/form/button-bar.mjs +++ b/source/components/form/button-bar.mjs @@ -129,7 +129,7 @@ const ATTRIBUTE_POPPER_POSITION = "data-monster-popper-position"; * * @fragments /fragments/components/form/button-bar/ * - * @example /examples/components/form/button-bar-simple + * @example /examples/components/form/button-bar-simple Button bar * * @copyright schukai GmbH * @summary This is a button bar control that can be used to display a set of buttons. diff --git a/source/components/form/button.mjs b/source/components/form/button.mjs index 93621590c..3fa0957e1 100644 --- a/source/components/form/button.mjs +++ b/source/components/form/button.mjs @@ -44,8 +44,8 @@ export const buttonElementSymbol = Symbol("buttonElement"); * * @fragments /fragments/components/form/button/ * - * @example /examples/components/form/button-simple - * @example /examples/components/form/button-with-click-event + * @example /examples/components/form/button-simple Simple Button + * @example /examples/components/form/button-with-click-event Button with event * * @copyright schukai GmbH * @summary A beautiful button that can make your life easier and also looks good. diff --git a/source/components/form/confirm-button.mjs b/source/components/form/confirm-button.mjs index b4b426e63..174cfd6ae 100644 --- a/source/components/form/confirm-button.mjs +++ b/source/components/form/confirm-button.mjs @@ -93,7 +93,7 @@ const cancelButtonElementSymbol = Symbol("cancelButtonElement"); * * @fragments /fragments/components/form/confirm-button/ * - * @example /examples/components/form/confirm-button-simple + * @example /examples/components/form/confirm-button-simple confirm button * * @since 1.5.0 * @copyright schukai GmbH diff --git a/source/components/form/form.mjs b/source/components/form/form.mjs index 06e80fa53..bfc3fa6f3 100644 --- a/source/components/form/form.mjs +++ b/source/components/form/form.mjs @@ -83,7 +83,7 @@ class Form extends DataSet { }, reportValidity: { - selector: "input,select,textarea", + selector: "input,select,textarea,monster-select,monster-toggle-switch", }, eventProcessing: true, @@ -130,12 +130,13 @@ class Form extends DataSet { /** * This method is called when the component is created. * @since 3.70.0 - * @return {DataSet} + * @return {Promise} */ refresh() { - this.write(); - super.refresh(); - return this; + return this.write().then(() => { + super.refresh(); + return this; + }) } /** @@ -175,6 +176,7 @@ function initEventHandler() { const events = this.getOption("writeBack.events"); for (const event of events) { this.addEventListener(event, (e) => { + if (!this.reportValidity()) { this.classList.add("invalid"); setTimeout(() => { diff --git a/source/components/form/select.mjs b/source/components/form/select.mjs index c9eea5ff5..4c78e9ea9 100644 --- a/source/components/form/select.mjs +++ b/source/components/form/select.mjs @@ -12,61 +12,61 @@ * 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_ERRORMESSAGE, - ATTRIBUTE_PREFIX, - ATTRIBUTE_ROLE, + ATTRIBUTE_ERRORMESSAGE, + ATTRIBUTE_PREFIX, + ATTRIBUTE_ROLE, } from "../../dom/constants.mjs"; -import { CustomControl } from "../../dom/customcontrol.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, getWindow} 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"; export { - Select, - popperElementSymbol, - getSummaryTemplate, - getSelectionTemplate, + Select, + popperElementSymbol, + getSummaryTemplate, + getSelectionTemplate, }; /** @@ -199,7 +199,7 @@ const popperFilterElementSymbol = Symbol("popperFilterElement"); * @type {Symbol} */ const popperFilterContainerElementSymbol = Symbol( - "popperFilterContainerElement", + "popperFilterContainerElement", ); /** @@ -281,6 +281,7 @@ const FILTER_POSITION_INLINE = "inline"; * @fragments /fragments/components/form/select/ * * @example /examples/components/form/select-with-options Select with options + * @example /examples/components/form/select-with-html-options Select with HTML options * @example /examples/components/form/select-multiple Multiple selection * @example /examples/components/form/select-filter Filter * @example /examples/components/form/select-fetch Fetch options @@ -293,611 +294,613 @@ 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) { - const result = convertValueToSelection.call(this, value); - setSelection - .call(this, result.selection) - .then(() => {}) - .catch((e) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - } - - /** - * 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=click,touch List of event types to be observed for opening the dropdown - * @property {boolean} delegatesFocus=false 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=10 Maximum number of visible options before a scroll bar should be displayed. - * @property {string} type=radio Multiple (checkbox) or single selection (radio) - * @property {string} name=(random id) 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=null Load options from server per url - * @property {boolean} lookup.grouping=false 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=error - * @property {String} fetch.method=GET - * @property {String} fetch.mode=same-origin - * @property {String} fetch.credentials=same-origin - * @property {Object} fetch.headers={"accept":"application/json"}} - * @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=true Display of a delete button to delete the entire selection - * @property {Boolean} features.clear=true Display of a delete key for deleting the specific selection - * @property {Boolean} features.lazyLoad=false Load options when first opening the dropdown. (Hint; lazylLoad is not supported with remote filter) - * @property {Boolean} features.closeOnSelect=false Close the dropdown when an option is selected (since 3.54.0) - * @property {Boolean} features.emptyValueIfNoOptions=false If no options are available, the selection is set to an empty array - * @property {Boolean} features.storeFetchedData=false Store fetched data in the object - * @property {Boolean} features.useStrictValueComparison=true Use strict value comparison for the selection - * @property {string} filter.defaultValue=null Default filter value, if the filter is empty, if the default value is null, then no request is made - * @property {Boolean} filter.mode=options 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=bottom PopperJS placement - * @property {Object[]} modifiers={name:offset} 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 {Monster.Components.Form~exampleFilterCallback|undefined} mapping.filter Filtering of values via a function - * @property {Object} formatter - * @property {Monster.Components.Form~formatterSelectionCallback|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: { - "cannot-be-loaded": "Cannot be loaded", - "no-options-available": noOptionsAvailableMessage, - "click-to-load-options": clickToLoadOptionsMessage, - "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.", - }, - 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, - }, - 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) { - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - "lazyLoad is not supported with remote filter", - ); - lazyLoadFlag = false; - } - } - - if (self.hasAttribute("value")) { - new Processing(10, () => { - this.value = this.getAttribute("value"); - }) - .run() - .catch((e) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - } - - if (self.getOption("url") !== null) { - if (lazyLoadFlag || remoteFilterFlag) { - lookupSelection.call(self); - } else { - self.fetch().catch((e) => { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${e}`); - }); - } - } - - 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) { - lastValue = n; - setSelection - .call(self, n) - .then(() => {}) - .catch((e) => { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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 === "") { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, "empty label template"); - flag = true; - } - - if (valueTemplate === "") { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, "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, - }); - - 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + } + + /** + * 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=click,touch List of event types to be observed for opening the dropdown + * @property {boolean} delegatesFocus=false 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=10 Maximum number of visible options before a scroll bar should be displayed. + * @property {string} type=radio Multiple (checkbox) or single selection (radio) + * @property {string} name=(random id) 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=null Load options from server per url + * @property {boolean} lookup.grouping=false 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=error + * @property {String} fetch.method=GET + * @property {String} fetch.mode=same-origin + * @property {String} fetch.credentials=same-origin + * @property {Object} fetch.headers={"accept":"application/json"}} + * @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=true Display of a delete button to delete the entire selection + * @property {Boolean} features.clear=true Display of a delete key for deleting the specific selection + * @property {Boolean} features.lazyLoad=false Load options when first opening the dropdown. (Hint; lazylLoad is not supported with remote filter) + * @property {Boolean} features.closeOnSelect=false Close the dropdown when an option is selected (since 3.54.0) + * @property {Boolean} features.emptyValueIfNoOptions=false If no options are available, the selection is set to an empty array + * @property {Boolean} features.storeFetchedData=false Store fetched data in the object + * @property {Boolean} features.useStrictValueComparison=true Use strict value comparison for the selection + * @property {string} filter.defaultValue=null Default filter value, if the filter is empty, if the default value is null, then no request is made + * @property {Boolean} filter.mode=options 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=bottom PopperJS placement + * @property {Object[]} modifiers={name:offset} 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 {Monster.Components.Form~exampleFilterCallback|undefined} mapping.filter Filtering of values via a function + * @property {Object} formatter + * @property {Monster.Components.Form~formatterSelectionCallback|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: { + "cannot-be-loaded": "Cannot be loaded", + "no-options-available": noOptionsAvailableMessage, + "click-to-load-options": clickToLoadOptionsMessage, + "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.", + }, + 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, + }, + 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) { + addAttributeToken( + this, + ATTRIBUTE_ERRORMESSAGE, + "lazyLoad is not supported with remote filter", + ); + lazyLoadFlag = false; + } + } + + if (self.hasAttribute("value")) { + new Processing(10, () => { + this.value = this.getAttribute("value"); + }) + .run() + .catch((e) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + } + + if (self.getOption("url") !== null) { + if (lazyLoadFlag || remoteFilterFlag) { + lookupSelection.call(self); + } else { + self.fetch().catch((e) => { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${e}`); + }); + } + } + + 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) { + lastValue = n; + setSelection + .call(self, n) + .then(() => { + }) + .catch((e) => { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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 === "") { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, "empty label template"); + flag = true; + } + + if (valueTemplate === "") { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, "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, + }); + + return this; + } + + /** + * @private + * @return {Select} + */ + calcAndSetOptionsDimension() { + calcAndSetOptionsDimension.call(this); + return this; + } + + /** + * + * @return {string} + */ + static getTag() { + return "monster-select"; + } + + /** + * + * @return {CSSStyleSheet[]} + */ + static getCSSStyleSheet() { + return [SelectStyleSheet]; + } } /** * @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) => { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${e}`); - }); - return; - } - - for (const s of selection) { - if (s?.["value"]) { - filterFromRemoteByValue.call(self, url, s?.["value"]).catch((e) => { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${e}`); + }); + return; + } + + for (const s of selection) { + if (s?.["value"]) { + filterFromRemoteByValue.call(self, url, s?.["value"]).catch((e) => { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `${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"); - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - 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"); + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + reject(e); + }); + }); } /** @@ -912,64 +915,64 @@ 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: - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - "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: + addAttributeToken( + this, + ATTRIBUTE_ERRORMESSAGE, + "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]; - }); - }); - - this[resizeObserverSymbol].observe(this.parentElement); + // 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]; + }); + }); + + this[resizeObserverSymbol].observe(this.parentElement); } function disconnectResizeObserver() { - if (this[resizeObserverSymbol] instanceof ResizeObserver) { - this[resizeObserverSymbol].disconnect(); - } + if (this[resizeObserverSymbol] instanceof ResizeObserver) { + this[resizeObserverSymbol].disconnect(); + } } 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" @@ -981,7 +984,7 @@ function getSelectionTemplate() { } 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" @@ -997,35 +1000,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"); - } - - if (node.style.display === "none") { - visibility = "hidden"; - } - - const label = node.outerHTML; - - 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); } /** @@ -1035,39 +1038,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, + }); } /** @@ -1076,38 +1079,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; } /** @@ -1117,17 +1120,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); } /** @@ -1135,25 +1138,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; + } } /** @@ -1163,45 +1166,46 @@ function handleToggleKeyboardEvents(event) { * @this CustomElement */ function initOptionObserver() { - const self = this; - - self.attachObserver( - new Observer(function () { - new Processing(() => { - try { - self.updateI18n(); - } catch (e) { - console.error(e); - requestAnimationFrame(() => { - setStatusOrRemoveBadges.call(self, "error"); - }); - } - try { - areOptionsAvailableAndInit.call(self); - } catch (e) { - console.error(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) { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, e.message); + requestAnimationFrame(() => { + setStatusOrRemoveBadges.call(self, "error"); + }); + } + try { + areOptionsAvailableAndInit.call(self); + } catch (e) { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, e.message); + requestAnimationFrame(() => { + setStatusOrRemoveBadges.call(self, "error"); + }); + } + + setSummaryAndControlText.call(self); + }).run(); + }), + ); } 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; } /** @@ -1209,36 +1213,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 === undefined || 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", ""); + } + } } /** @@ -1246,9 +1250,9 @@ function setSummaryAndControlText() { * @return {NodeList} */ function getOptionElements() { - return this[optionsElementSymbol].querySelectorAll( - `[${ATTRIBUTE_ROLE}=option]`, - ); + return this[optionsElementSymbol].querySelectorAll( + `[${ATTRIBUTE_ROLE}=option]`, + ); } /** @@ -1272,75 +1276,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"; } /** @@ -1349,126 +1353,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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); + 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); } /** * @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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - }) - .catch((e) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); + 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + }) + .catch((e) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); } /** @@ -1476,37 +1480,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); + } } /** @@ -1520,90 +1524,90 @@ 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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - } - - 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + } + + 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) { - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - "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) { + addAttributeToken( + this, + ATTRIBUTE_ERRORMESSAGE, + "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); } /** @@ -1613,28 +1617,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; + }); } /** @@ -1642,50 +1646,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; + } } /** @@ -1693,33 +1697,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(); } /** @@ -1727,29 +1731,29 @@ 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)) { - addAttributeToken( - this, - ATTRIBUTE_ERRORMESSAGE, - "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)) { + addAttributeToken( + this, + ATTRIBUTE_ERRORMESSAGE, + "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); } /** @@ -1757,44 +1761,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); } /** @@ -1804,39 +1808,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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${e}`); + }); + + if (this.getOption("features.closeOnSelect") === true) { + toggle.call(this); + } + + return this; } /** @@ -1845,120 +1850,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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, `${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 = ""; - } - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, noOptionsAvailableMessage); - 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); - - removeAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, noOptionsAvailableMessage); - 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 = ""; + } + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, noOptionsAvailableMessage); + 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); + + removeAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, noOptionsAvailableMessage); + return true; } /** @@ -1966,30 +1972,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; + } + } } /** @@ -1998,41 +2004,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, + }; } /** @@ -2041,25 +2047,25 @@ 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(","); } /** @@ -2069,74 +2075,76 @@ function convertSelectionToValue(selection) { * @throws {Error} no shadow-root is defined */ function setSelection(selection) { - if (isString(selection)) { - const result = convertValueToSelection.call(this, selection); - selection = result?.selection; - } else if (selection === undefined) { - selection = []; - } - - validateArray(selection); - - for (let i = 0; i < selection.length; i++) { - var l = getSelectionLabel.call(this, selection[i].value); - if (l === selection[i].value) { - l = selection[i].label; - } - - selection[i] = { - label: l, - value: selection[i].value, - }; - } - - this.setOption("selection", selection); - checkOptionState.call(this); - - try { - this?.setFormValue(this.value); - } catch (e) { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - } - - fireCustomEvent(this, "monster-selected", { - selection, - }); - - fireEvent(this, "change"); - - 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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); + if (isString(selection)) { + const result = convertValueToSelection.call(this, selection); + selection = result?.selection; + } else if (selection === undefined) { + selection = []; + } + + validateArray(selection); + + for (let i = 0; i < selection.length; i++) { + let l = getSelectionLabel.call(this, selection[i].value); + if (l === selection[i].value) { + l = selection[i].label; + } + + selection[i] = { + label: l, + value: selection[i].value, + }; + } + + this.setOption("selection", selection); + checkOptionState.call(this); + setSummaryAndControlText.call(this); + + try { + this?.setFormValue(this.value); + } catch (e) { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + } + + fireCustomEvent(this, "monster-selected", { + selection, + }); + + fireEvent(this, "change"); + + 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); } /** @@ -2147,139 +2155,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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - setStatusOrRemoveBadges.call(this, "error"); - }); - }) - .run() - .catch((e) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - 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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); + 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + setStatusOrRemoveBadges.call(this, "error"); + }); + }) + .run() + .catch((e) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); } /** * @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); + } } /** @@ -2288,188 +2296,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) => { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - } - } - }; - - /** - * @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) => { + addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + } + } + }; + + /** + * @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; } /** @@ -2477,70 +2485,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; + } + }); } /** @@ -2549,68 +2557,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) => { - addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); - }); - - 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) => { + addAttributeToken(this, ATTRIBUTE_ERRORMESSAGE, e.message); + }); + + return this; } /** @@ -2618,8 +2626,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/components/layout/tabs.mjs b/source/components/layout/tabs.mjs index 99bdf30a6..c167c144b 100644 --- a/source/components/layout/tabs.mjs +++ b/source/components/layout/tabs.mjs @@ -145,9 +145,9 @@ const resizeObserverSymbol = Symbol("resizeObserver"); * * @fragments /fragments/components/layout/tabs/ * - * @example /examples/components/layout/tabs-simple - * @example /examples/components/layout/tabs-active - * @example /examples/components/layout/tabs-removable + * @example /examples/components/layout/tabs-simple Simple Tabs + * @example /examples/components/layout/tabs-active Active Tabs + * @example /examples/components/layout/tabs-removable Removable Tabs * * @issue https://localhost.alvine.dev:8443/development/issues/closed/268.html * @issue https://localhost.alvine.dev:8443/development/issues/closed/271.html diff --git a/source/components/layout/width-toggle.mjs b/source/components/layout/width-toggle.mjs index 5dd08a0bf..303691a84 100644 --- a/source/components/layout/width-toggle.mjs +++ b/source/components/layout/width-toggle.mjs @@ -59,7 +59,7 @@ const MODE_WIDE = "wide"; * * @fragments /fragments/components/layout/width-toggle/ * - * @example /examples/components/layout/width-toggle-simple + * @example /examples/components/layout/width-toggle-simple Toggle Width * * @since 3.57.0 * @copyright schukai GmbH diff --git a/source/components/navigation/table-of-content.mjs b/source/components/navigation/table-of-content.mjs index 5f95cc81f..a6f5f4bab 100644 --- a/source/components/navigation/table-of-content.mjs +++ b/source/components/navigation/table-of-content.mjs @@ -73,7 +73,7 @@ const scrollableEventHandlerSymbol = Symbol("scrollableEventHandler"); * * @fragments /fragments/components/form/table-of-content * - * @example /examples/components/form/table-of-content-simple + * @example /examples/components/form/table-of-content-simple Table of content * * @since 3.65.0 * @copyright schukai GmbH diff --git a/source/components/notify/message.mjs b/source/components/notify/message.mjs index 1bfefa13d..ed53a75bd 100644 --- a/source/components/notify/message.mjs +++ b/source/components/notify/message.mjs @@ -70,7 +70,7 @@ const removeEventHandlerSymbol = Symbol("removeEventHandler"); * * @fragments /fragments/components/notify/message * - * @example /examples/components/notify/message-simple + * @example /examples/components/notify/message-simple Message * * @issue https://localhost.alvine.dev:8443/development/issues/closed/269.html * diff --git a/source/components/notify/notify.mjs b/source/components/notify/notify.mjs index 4d0fe8063..8f26859e2 100644 --- a/source/components/notify/notify.mjs +++ b/source/components/notify/notify.mjs @@ -49,8 +49,8 @@ const queueSymbol = Symbol("queue"); * * @fragments /fragments/components/notify/notify * - * @example /examples/components/notify/notify-simple - * @example /examples/components/notify/notify-inline + * @example /examples/components/notify/notify-simple Notify + * @example /examples/components/notify/notify-inline Inline Notify * * @issue https://localhost.alvine.dev:8443/development/issues/closed/269.html * diff --git a/source/components/state/log.mjs b/source/components/state/log.mjs index fed9862f3..f3bf02be4 100644 --- a/source/components/state/log.mjs +++ b/source/components/state/log.mjs @@ -44,7 +44,7 @@ const emptyStateElementSymbol = Symbol("emptyStateElement"); * * @fragments /fragments/components/state/log * - * @example /examples/components/state/log-simple + * @example /examples/components/state/log-simple Log * * @issue https://localhost.alvine.dev:8444/development/issues/closed/270.html * diff --git a/source/components/state/state.mjs b/source/components/state/state.mjs index 657b91f12..3cf37abfd 100644 --- a/source/components/state/state.mjs +++ b/source/components/state/state.mjs @@ -27,7 +27,7 @@ export { State }; * * @fragments /fragments/components/state/state * - * @example /examples/components/state/state-simple + * @example /examples/components/state/state-simple State * * @since 1.5.0 * @copyright schukai GmbH diff --git a/source/dom/constants.mjs b/source/dom/constants.mjs index cd4e96425..6e728a06a 100644 --- a/source/dom/constants.mjs +++ b/source/dom/constants.mjs @@ -196,23 +196,26 @@ const ATTRIBUTE_UPDATER_BIND = `${ATTRIBUTE_PREFIX}bind`; /** * @type {string} * @license AGPLv3 - * @since 3.73.0 + * @since 1.9.0 */ -const ATTRIBUTE_FORM_BIND = `${ATTRIBUTE_PREFIX}form-bind`; +const ATTRIBUTE_UPDATER_BIND_TYPE = `${ATTRIBUTE_UPDATER_BIND}-type`; /** * @type {string} * @license AGPLv3 + * @deprecated since 2024-12-29 * @since 3.73.0 */ -const ATTRIBUTE_FORM_BIND_TYPE = `${ATTRIBUTE_PREFIX}form-bind-type`; +const ATTRIBUTE_FORM_BIND = `${ATTRIBUTE_PREFIX}form-bind`; /** * @type {string} * @license AGPLv3 - * @since 1.9.0 + * @since 3.73.0 + * @deprecated since 2024-12-29 */ -const ATTRIBUTE_UPDATER_BIND_TYPE = `${ATTRIBUTE_UPDATER_BIND}-type`; +const ATTRIBUTE_FORM_BIND_TYPE = `${ATTRIBUTE_PREFIX}form-bind-type`; + /** * @type {string} diff --git a/source/dom/updater.mjs b/source/dom/updater.mjs index 6f402c3bf..2abe5189a 100644 --- a/source/dom/updater.mjs +++ b/source/dom/updater.mjs @@ -74,7 +74,7 @@ class Updater extends Base { * @param {object|ProxyObserver|undefined} subject * @throws {TypeError} value is not a object * @throws {TypeError} value is not an instance of HTMLElement - * @see {@link Monster.DOM.findDocumentTemplate} + * @see {@link findDocumentTemplate} */ constructor(element, subject) { super(); @@ -305,6 +305,7 @@ function getControlEventHandler() { if (element === undefined) { return; } + queueMicrotask(() => { retrieveAndSetValue.call(this, element); }); @@ -850,11 +851,7 @@ function handleInputControlAttributeUpdate(element, name, value) { switch (element.type) { case "select-multiple": for (const [index, opt] of Object.entries(element.options)) { - if (value.indexOf(opt.value) !== -1) { - opt.selected = true; - } else { - opt.selected = false; - } + opt.selected = value.indexOf(opt.value) !== -1; } break; -- GitLab