From 0f105d329bdeb3947f58daa2c61b0f94ad09a5fc Mon Sep 17 00:00:00 2001 From: Volker Schukai <volker.schukai@schukai.com> Date: Thu, 26 Jan 2023 02:07:57 +0100 Subject: [PATCH] chore: code format rome --- application/source/constants.mjs | 13 +- application/source/constraints/abstract.mjs | 10 +- .../source/constraints/abstractoperator.mjs | 18 +- .../source/constraints/andoperator.mjs | 9 +- application/source/constraints/invalid.mjs | 9 +- application/source/constraints/isarray.mjs | 15 +- application/source/constraints/isobject.mjs | 11 +- application/source/constraints/namespace.mjs | 4 +- application/source/constraints/oroperator.mjs | 48 +-- application/source/constraints/valid.mjs | 9 +- application/source/data/buildmap.mjs | 53 +-- application/source/data/buildtree.mjs | 58 ++-- application/source/data/datasource.mjs | 68 ++-- .../source/data/datasource/namespace.mjs | 2 +- application/source/data/datasource/server.mjs | 34 +- .../source/data/datasource/server/restapi.mjs | 116 +++---- .../datasource/server/restapi/writeerror.mjs | 12 +- .../data/datasource/server/webconnect.mjs | 61 ++-- .../source/data/datasource/storage.mjs | 40 +-- .../data/datasource/storage/localstorage.mjs | 19 +- .../datasource/storage/sessionstorage.mjs | 18 +- application/source/data/diff.mjs | 52 ++- application/source/data/extend.mjs | 20 +- application/source/data/namespace.mjs | 4 +- application/source/data/pathfinder.mjs | 101 ++---- application/source/data/pipe.mjs | 16 +- application/source/data/transformer.mjs | 286 ++++++++-------- application/source/dom/assembler.mjs | 15 +- application/source/dom/attributes.mjs | 76 ++--- application/source/dom/constants.mjs | 96 +++--- application/source/dom/customcontrol.mjs | 37 +- application/source/dom/customelement.mjs | 289 +++++++--------- application/source/dom/events.mjs | 41 +-- application/source/dom/focusmanager.mjs | 78 ++--- application/source/dom/locale.mjs | 35 +- application/source/dom/namespace.mjs | 2 +- application/source/dom/ready.mjs | 17 +- application/source/dom/resource.mjs | 105 +++--- application/source/dom/resource/data.mjs | 84 +++-- application/source/dom/resource/link.mjs | 53 ++- .../source/dom/resource/link/namespace.mjs | 4 +- .../source/dom/resource/link/stylesheet.mjs | 18 +- application/source/dom/resource/namespace.mjs | 2 +- application/source/dom/resource/script.mjs | 36 +- application/source/dom/resourcemanager.mjs | 77 ++--- application/source/dom/template.mjs | 37 +- application/source/dom/theme.mjs | 20 +- application/source/dom/updater.mjs | 322 ++++++++---------- application/source/dom/util.mjs | 23 +- application/source/dom/worker/factory.mjs | 46 ++- application/source/dom/worker/namespace.mjs | 2 +- application/source/i18n/formatter.mjs | 40 +-- application/source/i18n/locale.mjs | 46 ++- application/source/i18n/namespace.mjs | 2 +- application/source/i18n/provider.mjs | 11 +- application/source/i18n/providers/embed.mjs | 42 +-- application/source/i18n/providers/fetch.mjs | 66 ++-- application/source/i18n/translations.mjs | 35 +- application/source/logging/handler.mjs | 33 +- .../source/logging/handler/console.mjs | 16 +- application/source/logging/logentry.mjs | 17 +- application/source/logging/logger.mjs | 120 +++---- application/source/logging/namespace.mjs | 2 +- application/source/math/namespace.mjs | 2 +- application/source/math/random.mjs | 27 +- application/source/monster.mjs | 232 +++++++------ application/source/net/namespace.mjs | 4 +- application/source/net/webconnect.mjs | 67 ++-- application/source/net/webconnect/message.mjs | 14 +- .../source/net/webconnect/namespace.mjs | 4 +- application/source/text/formatter.mjs | 98 +++--- application/source/types/base.mjs | 42 +-- application/source/types/basewithoptions.mjs | 22 +- application/source/types/binary.mjs | 9 +- application/source/types/dataurl.mjs | 40 +-- application/source/types/global.mjs | 40 +-- application/source/types/id.mjs | 10 +- application/source/types/is.mjs | 27 +- application/source/types/mediatype.mjs | 71 ++-- application/source/types/namespace.mjs | 1 - application/source/types/node.mjs | 34 +- application/source/types/nodelist.mjs | 23 +- .../source/types/noderecursiveiterator.mjs | 25 +- application/source/types/observablequeue.mjs | 29 +- application/source/types/observer.mjs | 39 +-- application/source/types/observerlist.mjs | 30 +- application/source/types/proxyobserver.mjs | 58 ++-- application/source/types/queue.mjs | 21 +- application/source/types/randomid.mjs | 20 +- application/source/types/regex.mjs | 8 +- application/source/types/stack.mjs | 12 +- application/source/types/tokenlist.mjs | 55 ++- application/source/types/typeof.mjs | 12 +- application/source/types/uniquequeue.mjs | 21 +- application/source/types/uuid.mjs | 43 +-- application/source/types/validate.mjs | 51 ++- application/source/types/version.mjs | 40 +-- application/source/util/clone.mjs | 53 ++- application/source/util/comparator.mjs | 22 +- application/source/util/deadmansswitch.mjs | 39 +-- application/source/util/freeze.mjs | 12 +- application/source/util/namespace.mjs | 2 +- application/source/util/processing.mjs | 70 ++-- application/source/util/trimspaces.mjs | 39 +-- development/rome.json | 6 + 105 files changed, 1986 insertions(+), 2539 deletions(-) diff --git a/application/source/constants.mjs b/application/source/constants.mjs index 8ad5456ee..501769215 100644 --- a/application/source/constants.mjs +++ b/application/source/constants.mjs @@ -8,11 +8,7 @@ * @author schukai GmbH */ -export { - internalSymbol, - internalStateSymbol, - instanceSymbol -} +export { internalSymbol, internalStateSymbol, instanceSymbol }; /** * @private @@ -21,7 +17,7 @@ export { * @license AGPLv3 * @since 1.24.0 */ -const internalSymbol = Symbol.for('@schukai/monster/internal'); +const internalSymbol = Symbol.for("@schukai/monster/internal"); /** * @private @@ -30,11 +26,10 @@ const internalSymbol = Symbol.for('@schukai/monster/internal'); * @license AGPLv3 * @since 1.25.0 */ -const internalStateSymbol = Symbol.for('@schukai/monster/state'); +const internalStateSymbol = Symbol.for("@schukai/monster/state"); /** * @private * @type {symbol} */ -const instanceSymbol = Symbol.for('@schukai/monster/instance'); - +const instanceSymbol = Symbol.for("@schukai/monster/instance"); diff --git a/application/source/constraints/abstract.mjs b/application/source/constraints/abstract.mjs index 7067d9897..e199d9204 100644 --- a/application/source/constraints/abstract.mjs +++ b/application/source/constraints/abstract.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {instanceSymbol} from '../constants.mjs'; +import { Base } from "../types/base.mjs"; +import { instanceSymbol } from "../constants.mjs"; -export {AbstractConstraint} +export { AbstractConstraint }; /** * Constraints are used to define conditions that must be met by the value of a variable. * * The uniform API of the constraints allows chains to be formed. - * + * * The abstract constraint defines the api for all constraints. mainly the method isValid() is defined. * * Derived classes must implement the method isValid(). @@ -26,7 +26,6 @@ export {AbstractConstraint} * @summary The abstract constraint */ class AbstractConstraint extends Base { - /** * */ @@ -52,5 +51,4 @@ class AbstractConstraint extends Base { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/abstract-constraint"); } - } diff --git a/application/source/constraints/abstractoperator.mjs b/application/source/constraints/abstractoperator.mjs index cb6bcd817..b06a531b3 100644 --- a/application/source/constraints/abstractoperator.mjs +++ b/application/source/constraints/abstractoperator.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {AbstractConstraint} from "./abstract.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {AbstractOperator} +import { AbstractConstraint } from "./abstract.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { AbstractOperator }; /** * Constraints are used to define conditions that must be met by the value of a variable. * * The uniform API of the constraints allows chains to be formed. * - * Operators allow you to link constraints together. for example, you can check whether a value is + * Operators allow you to link constraints together. for example, you can check whether a value is * an object or an array. each operator has two operands that are linked together. * * @license AGPLv3 @@ -24,7 +24,6 @@ export {AbstractOperator} * @summary The abstract operator constraint */ class AbstractOperator extends AbstractConstraint { - /** * * @param {AbstractConstraint} operantA @@ -34,13 +33,12 @@ class AbstractOperator extends AbstractConstraint { constructor(operantA, operantB) { super(); - if (!((operantA instanceof AbstractConstraint) && (operantB instanceof AbstractConstraint))) { - throw new TypeError("parameters must be from type AbstractConstraint") + if (!(operantA instanceof AbstractConstraint && operantB instanceof AbstractConstraint)) { + throw new TypeError("parameters must be from type AbstractConstraint"); } this.operantA = operantA; this.operantB = operantB; - } /** @@ -51,8 +49,4 @@ class AbstractOperator extends AbstractConstraint { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/abstract-operator"); } - - - } - diff --git a/application/source/constraints/andoperator.mjs b/application/source/constraints/andoperator.mjs index 6e1a1a118..2b45fbc96 100644 --- a/application/source/constraints/andoperator.mjs +++ b/application/source/constraints/andoperator.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {AbstractOperator} from "./abstractoperator.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {AndOperator} +import { AbstractOperator } from "./abstractoperator.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { AndOperator }; /** * Constraints are used to define conditions that must be met by the value of a variable. @@ -24,7 +24,6 @@ export {AndOperator} * @summary A and operator constraint */ class AndOperator extends AbstractOperator { - /** * this method return a promise containing the result of the check. * @@ -43,6 +42,4 @@ class AndOperator extends AbstractOperator { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/and-operator"); } - - } diff --git a/application/source/constraints/invalid.mjs b/application/source/constraints/invalid.mjs index 6a5d61912..38f3fd357 100644 --- a/application/source/constraints/invalid.mjs +++ b/application/source/constraints/invalid.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {AbstractConstraint} from "./abstract.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {Invalid} +import { AbstractConstraint } from "./abstract.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Invalid }; /** * Constraints are used to define conditions that must be met by the value of a variable. @@ -24,7 +24,6 @@ export {Invalid} * @summary A constraint that always invalid */ class Invalid extends AbstractConstraint { - /** * this method return a rejected promise * @@ -43,6 +42,4 @@ class Invalid extends AbstractConstraint { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/invalid"); } - - } diff --git a/application/source/constraints/isarray.mjs b/application/source/constraints/isarray.mjs index 843d0dd94..12e30efb1 100644 --- a/application/source/constraints/isarray.mjs +++ b/application/source/constraints/isarray.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray} from "../types/is.mjs"; -import {AbstractConstraint} from "./abstract.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {IsArray} +import { isArray } from "../types/is.mjs"; +import { AbstractConstraint } from "./abstract.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { IsArray }; /** * Constraints are used to define conditions that must be met by the value of a variable. - * + * * The uniform API of the constraints allows chains to be formed. - * + * * @externalExample ../../example/constraints/isarray.mjs * @license AGPLv3 * @since 1.3.0 @@ -23,7 +23,6 @@ export {IsArray} * @summary A constraint to check if a value is an array */ class IsArray extends AbstractConstraint { - /** * this method return a promise containing the result of the check. * @@ -46,6 +45,4 @@ class IsArray extends AbstractConstraint { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraint/is-array"); } - - } diff --git a/application/source/constraints/isobject.mjs b/application/source/constraints/isobject.mjs index fa433033b..6d1a37972 100644 --- a/application/source/constraints/isobject.mjs +++ b/application/source/constraints/isobject.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isObject} from "../types/is.mjs"; -import {AbstractConstraint} from "./abstract.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {IsObject} +import { isObject } from "../types/is.mjs"; +import { AbstractConstraint } from "./abstract.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { IsObject }; /** * Constraints are used to define conditions that must be met by the value of a variable. @@ -23,7 +23,6 @@ export {IsObject} * @summary A constraint to check if a value is an object */ class IsObject extends AbstractConstraint { - /** * this method return a promise containing the result of the check. * @@ -46,6 +45,4 @@ class IsObject extends AbstractConstraint { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraint/is-object"); } - - } diff --git a/application/source/constraints/namespace.mjs b/application/source/constraints/namespace.mjs index 6a24393fa..d9abf97e7 100644 --- a/application/source/constraints/namespace.mjs +++ b/application/source/constraints/namespace.mjs @@ -3,8 +3,6 @@ * SPDX-License-Identifier: AGPL-3.0 */ - - /** * Constraints are used to define conditions that must be met by the value of a variable so that the value can be transferred to the system. * @@ -12,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/constraints/oroperator.mjs b/application/source/constraints/oroperator.mjs index d09ffa6eb..c72d7f08a 100644 --- a/application/source/constraints/oroperator.mjs +++ b/application/source/constraints/oroperator.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {AbstractOperator} from "./abstractoperator.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {OrOperator} +import { AbstractOperator } from "./abstractoperator.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { OrOperator }; /** * Constraints are used to define conditions that must be met by the value of a variable. @@ -21,10 +21,9 @@ export {OrOperator} * @since 1.3.0 * @copyright schukai GmbH * @memberOf Monster.Constraints - * @summary A or operator + * @summary A or operator */ class OrOperator extends AbstractOperator { - /** * this method return a promise containing the result of the check. * @@ -38,27 +37,31 @@ class OrOperator extends AbstractOperator { let a; let b; - self.operantA.isValid(value) + self.operantA + .isValid(value) .then(function () { resolve(); - }).catch(function () { - a = false; - /** b has already been evaluated and was not true */ - if (b === false) { - reject(); - } - }); + }) + .catch(function () { + a = false; + /** b has already been evaluated and was not true */ + if (b === false) { + reject(); + } + }); - self.operantB.isValid(value) + self.operantB + .isValid(value) .then(function () { resolve(); - }).catch(function () { - b = false; - /** b has already been evaluated and was not true */ - if (a === false) { - reject(); - } - }); + }) + .catch(function () { + b = false; + /** b has already been evaluated and was not true */ + if (a === false) { + reject(); + } + }); }); } @@ -70,7 +73,4 @@ class OrOperator extends AbstractOperator { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/or-operator"); } - - - } diff --git a/application/source/constraints/valid.mjs b/application/source/constraints/valid.mjs index 6810dd195..cb2b8abab 100644 --- a/application/source/constraints/valid.mjs +++ b/application/source/constraints/valid.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {AbstractConstraint} from "./abstract.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {Valid} +import { AbstractConstraint } from "./abstract.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Valid }; /** * Constraints are used to define conditions that must be met by the value of a variable. @@ -24,7 +24,6 @@ export {Valid} * @summary A constraint that always valid */ class Valid extends AbstractConstraint { - /** * this method return a promise containing the result of the check. * @@ -43,6 +42,4 @@ class Valid extends AbstractConstraint { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/constraints/valid"); } - - } diff --git a/application/source/data/buildmap.mjs b/application/source/data/buildmap.mjs index 94fd01c2f..c235a028d 100644 --- a/application/source/data/buildmap.mjs +++ b/application/source/data/buildmap.mjs @@ -5,19 +5,18 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isFunction, isObject, isString} from "../types/is.mjs"; -import {validateString} from "../types/validate.mjs"; -import {clone} from "../util/clone.mjs"; -import {DELIMITER, Pathfinder, WILDCARD} from "./pathfinder.mjs"; +import { isFunction, isObject, isString } from "../types/is.mjs"; +import { validateString } from "../types/validate.mjs"; +import { clone } from "../util/clone.mjs"; +import { DELIMITER, Pathfinder, WILDCARD } from "./pathfinder.mjs"; -export {buildMap, PARENT, assembleParts} +export { buildMap, PARENT, assembleParts }; /** * @type {string} * @memberOf Monster.Data */ -const PARENT = '^'; - +const PARENT = "^"; /** * With the help of the function `buildMap()`, maps can be easily created from data objects. @@ -47,10 +46,8 @@ function buildMap(subject, selector, valueTemplate, keyTemplate, filter) { v = build(v, valueTemplate); this.set(k, v); }); - } - /** * @private * @param {*} subject @@ -61,20 +58,19 @@ function buildMap(subject, selector, valueTemplate, keyTemplate, filter) { * @throws {TypeError} selector is neither a string nor a function */ function assembleParts(subject, selector, filter, callback) { - const result = new Map(); let map; if (isFunction(selector)) { - map = selector(subject) + map = selector(subject); if (!(map instanceof Map)) { - throw new TypeError('the selector callback must return a map'); + throw new TypeError("the selector callback must return a map"); } } else if (isString(selector)) { - map = new Map; + map = new Map(); buildFlatMap.call(map, subject, selector); } else { - throw new TypeError('selector is neither a string nor a function') + throw new TypeError("selector is neither a string nor a function"); } if (!(map instanceof Map)) { @@ -87,7 +83,6 @@ function assembleParts(subject, selector, filter, callback) { } callback.call(result, v, k, m); - }); return result; @@ -102,9 +97,8 @@ function assembleParts(subject, selector, filter, callback) { * @return {*} */ function buildFlatMap(subject, selector, key, parentMap) { - const result = this; - const currentMap = new Map; + const currentMap = new Map(); const resultLength = result.size; @@ -114,12 +108,10 @@ function buildFlatMap(subject, selector, key, parentMap) { let current = ""; let currentPath = []; do { - current = parts.shift(); currentPath.push(current); if (current === WILDCARD) { - let finder = new Pathfinder(subject); let map; @@ -131,12 +123,11 @@ function buildFlatMap(subject, selector, key, parentMap) { } for (const [k, o] of map) { - let copyKey = clone(key); currentPath.map((a) => { - copyKey.push((a === WILDCARD) ? k : a) - }) + copyKey.push(a === WILDCARD ? k : a); + }); let kk = copyKey.join(DELIMITER); let sub = buildFlatMap.call(result, o, parts.join(DELIMITER), copyKey, o); @@ -147,10 +138,7 @@ function buildFlatMap(subject, selector, key, parentMap) { currentMap.set(kk, sub); } - } - - } while (parts.length > 0); // no set in child run @@ -161,10 +149,8 @@ function buildFlatMap(subject, selector, key, parentMap) { } return subject; - } - /** * With the help of this filter callback, values can be filtered out. Only if the filter function returns true, the value is taken for the map. * @@ -319,7 +305,7 @@ function build(subject, definition, defaultValue) { if (definition === undefined) return defaultValue ? defaultValue : subject; validateString(definition); - const regexp = /(?<placeholder>\${(?<path>[a-z\^A-Z.\-_0-9]*)})/gm + const regexp = /(?<placeholder>\${(?<path>[a-z\^A-Z.\-_0-9]*)})/gm; const array = [...definition.matchAll(regexp)]; let finder = new Pathfinder(subject); @@ -329,20 +315,17 @@ function build(subject, definition, defaultValue) { } array.forEach((a) => { - let groups = a?.['groups']; - let placeholder = groups?.['placeholder'] + let groups = a?.["groups"]; + let placeholder = groups?.["placeholder"]; if (placeholder === undefined) return; - let path = groups?.['path'] + let path = groups?.["path"]; let v = finder.getVia(path); if (v === undefined) v = defaultValue; definition = definition.replaceAll(placeholder, v); - - - }) + }); return definition; - } diff --git a/application/source/data/buildtree.mjs b/application/source/data/buildtree.mjs index ba0501069..6e50e9b2b 100644 --- a/application/source/data/buildtree.mjs +++ b/application/source/data/buildtree.mjs @@ -5,25 +5,25 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray, isObject} from "../types/is.mjs"; -import {Node} from "../types/node.mjs"; -import {NodeList} from "../types/nodelist.mjs"; -import {assembleParts} from "./buildmap.mjs"; -import {extend} from "./extend.mjs"; +import { isArray, isObject } from "../types/is.mjs"; +import { Node } from "../types/node.mjs"; +import { NodeList } from "../types/nodelist.mjs"; +import { assembleParts } from "./buildmap.mjs"; +import { extend } from "./extend.mjs"; -export {buildTree} +export { buildTree }; /** * @private * @type {symbol} */ -const parentSymbol = Symbol('parent'); +const parentSymbol = Symbol("parent"); /** * @private * @type {symbol} */ -const rootSymbol = Symbol('root'); +const rootSymbol = Symbol("root"); /** * @typedef {Object} buildTreeOptions @@ -49,17 +49,20 @@ const rootSymbol = Symbol('root'); * @since 1.26.0 */ function buildTree(subject, selector, idKey, parentIDKey, options) { - - const nodes = new Map; + const nodes = new Map(); if (!isObject(options)) { - options = {} + options = {}; } - options = extend({}, { - rootReferences: [null, undefined], - filter: undefined - }, options) + options = extend( + {}, + { + rootReferences: [null, undefined], + filter: undefined, + }, + options, + ); const filter = options?.filter; let rootReferences = options.rootReferences; @@ -68,13 +71,12 @@ function buildTree(subject, selector, idKey, parentIDKey, options) { } const childMap = assembleParts(subject, selector, filter, function (o, k, m) { - - const key = o?.[idKey] - let ref = o?.[parentIDKey] + const key = o?.[idKey]; + let ref = o?.[parentIDKey]; if (rootReferences.indexOf(ref) !== -1) ref = rootSymbol; if (key === undefined) { - throw new Error('the object has no value for the specified id') + throw new Error("the object has no value for the specified id"); } o[parentSymbol] = ref; @@ -82,28 +84,26 @@ function buildTree(subject, selector, idKey, parentIDKey, options) { const node = new Node(o); this.has(ref) ? this.get(ref).add(node) : this.set(ref, new NodeList().add(node)); nodes.set(key, node); + }); - }) - - nodes.forEach(node => { - - let id = node?.['value']?.[idKey]; + nodes.forEach((node) => { + let id = node?.["value"]?.[idKey]; if (childMap.has(id)) { node.childNodes = childMap.get(id); - childMap.delete(id) + childMap.delete(id); } - }) + }); - const list = new NodeList; + const list = new NodeList(); childMap.forEach((s) => { if (s instanceof Set) { s.forEach((n) => { list.add(n); - }) + }); } - }) + }); return list; } diff --git a/application/source/data/datasource.mjs b/application/source/data/datasource.mjs index 89b743265..f14984284 100644 --- a/application/source/data/datasource.mjs +++ b/application/source/data/datasource.mjs @@ -5,18 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {instanceSymbol} from '../constants.mjs'; -import {Base} from "../types/base.mjs"; -import {parseDataURL} from "../types/dataurl.mjs"; -import {isString} from "../types/is.mjs"; -import {ProxyObserver} from "../types/proxyobserver.mjs"; -import {validateObject} from "../types/validate.mjs"; -import {extend} from "./extend.mjs"; -import {Pathfinder} from "./pathfinder.mjs"; - -export {Datasource} - +import { internalSymbol } from "../constants.mjs"; +import { instanceSymbol } from "../constants.mjs"; +import { Base } from "../types/base.mjs"; +import { parseDataURL } from "../types/dataurl.mjs"; +import { isString } from "../types/is.mjs"; +import { ProxyObserver } from "../types/proxyobserver.mjs"; +import { validateObject } from "../types/validate.mjs"; +import { extend } from "./extend.mjs"; +import { Pathfinder } from "./pathfinder.mjs"; + +export { Datasource }; /** * This callback can be passed to a datasource and is used to adapt data structures. @@ -28,7 +27,6 @@ export {Datasource} * @see Monster.Data.Datasource */ - /** * @private * @type {symbol} @@ -36,7 +34,7 @@ export {Datasource} * @license AGPLv3 * @since 1.24.0 */ -const internalDataSymbol = Symbol.for('@schukai/monster/data/datasource/@@data'); +const internalDataSymbol = Symbol.for("@schukai/monster/data/datasource/@@data"); /** * The datasource class is the basis for dealing with different data sources. @@ -49,22 +47,17 @@ const internalDataSymbol = Symbol.for('@schukai/monster/data/datasource/@@data') * @summary The datasource class encapsulates the access to data objects. */ class Datasource extends Base { - /** * creates a new datasource - * + * */ constructor() { super(); this[internalSymbol] = new ProxyObserver({ - 'options': extend({}, this.defaults) + options: extend({}, this.defaults), }); - - this[internalDataSymbol] = new ProxyObserver({ - }); - - + this[internalDataSymbol] = new ProxyObserver({}); } /** @@ -74,7 +67,7 @@ class Datasource extends Base { * @returns {Datasource} */ attachObserver(observer) { - this[internalDataSymbol].attachObserver(observer) + this[internalDataSymbol].attachObserver(observer); return this; } @@ -85,7 +78,7 @@ class Datasource extends Base { * @returns {Datasource} */ detachObserver(observer) { - this[internalDataSymbol].detachObserver(observer) + this[internalDataSymbol].detachObserver(observer); return this; } @@ -120,7 +113,7 @@ class Datasource extends Base { * @return {Datasource} */ setOption(path, value) { - new Pathfinder(this[internalSymbol].getSubject()['options']).setVia(path, value); + new Pathfinder(this[internalSymbol].getSubject()["options"]).setVia(path, value); return this; } @@ -130,13 +123,12 @@ class Datasource extends Base { * @throws {Error} the options does not contain a valid json definition */ setOptions(options) { - if (isString(options)) { - options = parseOptionsJSON(options) + options = parseOptionsJSON(options); } const self = this; - extend(self[internalSymbol].getSubject()['options'], self.defaults, options); + extend(self[internalSymbol].getSubject()["options"], self.defaults, options); return self; } @@ -152,10 +144,8 @@ class Datasource extends Base { let value; try { - value = new Pathfinder(this[internalSymbol].getRealSubject()['options']).getVia(path); - } catch (e) { - - } + value = new Pathfinder(this[internalSymbol].getRealSubject()["options"]).getVia(path); + } catch (e) {} if (value === undefined) return defaultValue; return value; @@ -166,7 +156,7 @@ class Datasource extends Base { * @return {Promise} */ read() { - throw new Error("this method must be implemented by derived classes") + throw new Error("this method must be implemented by derived classes"); } /** @@ -174,13 +164,12 @@ class Datasource extends Base { * @return {Promise} */ write() { - throw new Error("this method must be implemented by derived classes") + throw new Error("this method must be implemented by derived classes"); } - /** * Returns real object - * + * * @return {Object|Array} */ get() { @@ -206,7 +195,6 @@ class Datasource extends Base { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/data/datasource"); } - } /** @@ -217,15 +205,11 @@ class Datasource extends Base { */ function parseOptionsJSON(data) { if (isString(data)) { - // the configuration can be specified as a data url. try { let dataUrl = parseDataURL(data); data = dataUrl.content; - } catch (e) { - - } - + } catch (e) {} try { let obj = JSON.parse(data); diff --git a/application/source/data/datasource/namespace.mjs b/application/source/data/datasource/namespace.mjs index 7d3c906a0..4c3b4070b 100644 --- a/application/source/data/datasource/namespace.mjs +++ b/application/source/data/datasource/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster.Data * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/data/datasource/server.mjs b/application/source/data/datasource/server.mjs index 53378fc94..9fcdc06ef 100644 --- a/application/source/data/datasource/server.mjs +++ b/application/source/data/datasource/server.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol,instanceSymbol} from "../../constants.mjs"; -import {isObject} from "../../types/is.mjs"; -import {Datasource} from "../datasource.mjs"; -import {Pathfinder} from "../pathfinder.mjs"; -import {Pipe} from "../pipe.mjs"; +import { internalSymbol, instanceSymbol } from "../../constants.mjs"; +import { isObject } from "../../types/is.mjs"; +import { Datasource } from "../datasource.mjs"; +import { Pathfinder } from "../pathfinder.mjs"; +import { Pipe } from "../pipe.mjs"; -export {Server} +export { Server }; /** * Base class for all server datasources @@ -23,7 +23,6 @@ export {Server} * @summary The Server class encapsulates the access to a server datasource */ class Server extends Datasource { - /** * This method is called by the `instanceof` operator. * @returns {symbol} @@ -32,7 +31,6 @@ class Server extends Datasource { return Symbol.for("@schukai/monster/data/datasource/server"); } - /** * This prepares the data that comes from the server. * Should not be called directly. @@ -43,11 +41,11 @@ class Server extends Datasource { */ transformServerPayload(payload) { const self = this; - payload = doTransform.call(self, 'read', payload); + payload = doTransform.call(self, "read", payload); - const dataPath = self.getOption('read.path'); + const dataPath = self.getOption("read.path"); if (dataPath) { - payload = (new Pathfinder(payload)).getVia(dataPath); + payload = new Pathfinder(payload).getVia(dataPath); } return payload; @@ -63,23 +61,21 @@ class Server extends Datasource { prepareServerPayload(payload) { const self = this; - payload = doTransform.call(self, 'write', payload); + payload = doTransform.call(self, "write", payload); - let sheathingObject = self.getOption('write.sheathing.object'); - let sheathingPath = self.getOption('write.sheathing.path'); + let sheathingObject = self.getOption("write.sheathing.object"); + let sheathingPath = self.getOption("write.sheathing.path"); if (sheathingObject && sheathingPath) { const sub = payload; payload = sheathingObject; - (new Pathfinder(payload)).setVia(sheathingPath, sub); + new Pathfinder(payload).setVia(sheathingPath, sub); } return payload; } - } - /** * @private * @param self @@ -91,11 +87,11 @@ function doTransform(type, obj) { let transformation = self.getOption(`${type}.mapping.transformer`); if (transformation !== undefined) { const pipe = new Pipe(transformation); - const callbacks = self.getOption(`${type}.mapping.callbacks`) + const callbacks = self.getOption(`${type}.mapping.callbacks`); if (isObject(callbacks)) { for (const key in callbacks) { - if (callbacks.hasOwnProperty(key) && typeof callbacks[key] === 'function') { + if (callbacks.hasOwnProperty(key) && typeof callbacks[key] === "function") { pipe.setCallback(key, callbacks[key]); } } diff --git a/application/source/data/datasource/server/restapi.mjs b/application/source/data/datasource/server/restapi.mjs index 2264dde58..8ec0b9195 100644 --- a/application/source/data/datasource/server/restapi.mjs +++ b/application/source/data/datasource/server/restapi.mjs @@ -5,14 +5,14 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol, instanceSymbol} from "../../../constants.mjs"; -import {isObject} from "../../../types/is.mjs"; -import {Server} from "../server.mjs"; -import {Pathfinder} from "../../pathfinder.mjs"; -import {Pipe} from "../../pipe.mjs"; -import {WriteError} from "./restapi/writeerror.mjs"; +import { internalSymbol, instanceSymbol } from "../../../constants.mjs"; +import { isObject } from "../../../types/is.mjs"; +import { Server } from "../server.mjs"; +import { Pathfinder } from "../../pathfinder.mjs"; +import { Pipe } from "../../pipe.mjs"; +import { WriteError } from "./restapi/writeerror.mjs"; -export {RestAPI} +export { RestAPI }; /** * The RestAPI is a class that enables a REST API server. @@ -25,7 +25,6 @@ export {RestAPI} * @summary The RestAPI is a class that binds a REST API server. */ class RestAPI extends Server { - /** * * @param {Object} [options] options contains definitions for the datasource. @@ -36,7 +35,6 @@ class RestAPI extends Server { if (isObject(options)) { this.setOptions(options); } - } /** @@ -76,34 +74,33 @@ class RestAPI extends Server { return Object.assign({}, super.defaults, { write: { init: { - method: 'POST', + method: "POST", }, acceptedStatus: [200, 201], url: undefined, mapping: { transformer: undefined, - callbacks: [] + callbacks: [], }, sheathing: { object: undefined, path: undefined, }, report: { - path: undefined - } + path: undefined, + }, }, read: { init: { - method: 'GET' + method: "GET", }, acceptedStatus: [200], url: undefined, mapping: { transformer: undefined, - callbacks: [] + callbacks: [], }, }, - }); } @@ -114,17 +111,15 @@ class RestAPI extends Server { * @throws {Error} the data cannot be read */ read() { - const self = this; - let init = self.getOption('read.init'); + let init = self.getOption("read.init"); if (!isObject(init)) init = {}; - if (!init['method']) init['method'] = 'GET'; + if (!init["method"]) init["method"] = "GET"; - return fetchData.call(this, 'read', (obj) => { + return fetchData.call(this, "read", (obj) => { self.set(self.transformServerPayload.call(self, obj)); }); - } /** @@ -132,76 +127,67 @@ class RestAPI extends Server { * @throws {WriteError} the data cannot be written */ write() { - const self = this; - let init = self.getOption('write.init'); + let init = self.getOption("write.init"); if (!isObject(init)) init = {}; - if (typeof init['headers'] !== 'object') { - init['headers'] = { - 'Content-Type': 'application/json' - } + if (typeof init["headers"] !== "object") { + init["headers"] = { + "Content-Type": "application/json", + }; } - if (!init['method']) init['method'] = 'POST'; + if (!init["method"]) init["method"] = "POST"; let obj = self.prepareServerPayload(self.get()); - init['body'] = JSON.stringify(obj); + init["body"] = JSON.stringify(obj); - return fetchData.call(this, init, 'write'); + return fetchData.call(this, init, "write"); } - /** * @return {RestAPI} */ getClone() { const self = this; - return new RestAPI(self[internalSymbol].getRealSubject()['options'].read, self[internalSymbol].getRealSubject()['options'].write); + return new RestAPI( + self[internalSymbol].getRealSubject()["options"].read, + self[internalSymbol].getRealSubject()["options"].write, + ); } - } - function fetchData(init, key, callback) { - const self = this; let response; + return fetch(self.getOption(`${key}.url`), init) + .then((resp) => { + response = resp; - return fetch(self.getOption(`${key}.url`), init).then(resp => { - response = resp; - - const acceptedStatus = self.getOption(`${key}.acceptedStatus`, [200]); + const acceptedStatus = self.getOption(`${key}.acceptedStatus`, [200]); - if (acceptedStatus.indexOf(resp.status) === -1) { - throw Error(`the data cannot be ${key} (response ${resp.status})`) - } - - return resp.text() - }).then(body => { - - let obj; - - try { - obj = JSON.parse(body); - - } catch (e) { - - if (body.length > 100) { - body = `${body.substring(0, 97)}...`; + if (acceptedStatus.indexOf(resp.status) === -1) { + throw Error(`the data cannot be ${key} (response ${resp.status})`); } - throw new Error(`the response does not contain a valid json (actual: ${body}).`); - } + return resp.text(); + }) + .then((body) => { + let obj; - if (callback && isFunction(callback)) { - callback(obj); - } - return response; - - }); + try { + obj = JSON.parse(body); + } catch (e) { + if (body.length > 100) { + body = `${body.substring(0, 97)}...`; + } + throw new Error(`the response does not contain a valid json (actual: ${body}).`); + } + if (callback && isFunction(callback)) { + callback(obj); + } + return response; + }); } - - diff --git a/application/source/data/datasource/server/restapi/writeerror.mjs b/application/source/data/datasource/server/restapi/writeerror.mjs index 47cdfc50c..6f14245cb 100644 --- a/application/source/data/datasource/server/restapi/writeerror.mjs +++ b/application/source/data/datasource/server/restapi/writeerror.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol,instanceSymbol} from "../../../../constants.mjs"; +import { internalSymbol, instanceSymbol } from "../../../../constants.mjs"; -export {WriteError} +export { WriteError }; /** * Error message for API requests with extension of request and validation. - * + * * @license AGPLv3 * @since 1.24.0 * @copyright schukai GmbH @@ -28,7 +28,7 @@ class WriteError extends Error { super(message); this[internalSymbol] = { response: response, - validation: validation + validation: validation, }; } @@ -45,13 +45,13 @@ class WriteError extends Error { * @return {Response} */ getResponse() { - return this[internalSymbol]['response'] + return this[internalSymbol]["response"]; } /** * @return {Object} */ getValidation() { - return this[internalSymbol]['validation'] + return this[internalSymbol]["validation"]; } } diff --git a/application/source/data/datasource/server/webconnect.mjs b/application/source/data/datasource/server/webconnect.mjs index 07e6c4ec7..2e86c0c83 100644 --- a/application/source/data/datasource/server/webconnect.mjs +++ b/application/source/data/datasource/server/webconnect.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol, instanceSymbol} from "../../../constants.mjs"; -import {isString, isObject} from "../../../types/is.mjs"; -import {WebConnect as NetWebConnect} from "../../../net/webconnect.mjs"; -import {Message} from "../../../net/webconnect/message.mjs"; -import {Server} from "../server.mjs"; +import { internalSymbol, instanceSymbol } from "../../../constants.mjs"; +import { isString, isObject } from "../../../types/is.mjs"; +import { WebConnect as NetWebConnect } from "../../../net/webconnect.mjs"; +import { Message } from "../../../net/webconnect/message.mjs"; +import { Server } from "../server.mjs"; -export {WebConnect} +export { WebConnect }; /** * @private @@ -21,8 +21,6 @@ export {WebConnect} */ const webConnectSymbol = Symbol("connection"); - - /** * The RestAPI is a class that enables a REST API server. * @@ -34,32 +32,31 @@ const webConnectSymbol = Symbol("connection"); * @summary The LocalStorage class encapsulates the access to data objects. */ class WebConnect extends Server { - /** * * @param {Object} [options] options contains definitions for the datasource. */ constructor(options) { super(); - + const self = this; if (isString(options)) { - options = {url: options}; + options = { url: options }; } if (!isObject(options)) options = {}; this.setOptions(options); this[webConnectSymbol] = new NetWebConnect({ - url: self.getOption('url'), + url: self.getOption("url"), connection: { - timeout: self.getOption('connection.timeout'), + timeout: self.getOption("connection.timeout"), reconnect: { - timeout: self.getOption('connection.reconnect.timeout'), - attempts: self.getOption('connection.reconnect.attempts'), - enabled: self.getOption('connection.reconnect.enabled') - } - } + timeout: self.getOption("connection.reconnect.timeout"), + attempts: self.getOption("connection.reconnect.attempts"), + enabled: self.getOption("connection.reconnect.enabled"), + }, + }, }); } @@ -112,7 +109,7 @@ class WebConnect extends Server { write: { mapping: { transformer: undefined, - callbacks: {} + callbacks: {}, }, sheathing: { object: undefined, @@ -122,7 +119,7 @@ class WebConnect extends Server { read: { mapping: { transformer: undefined, - callbacks: {} + callbacks: {}, }, path: undefined, }, @@ -132,8 +129,8 @@ class WebConnect extends Server { timeout: 1000, attempts: 1, enabled: false, - } - } + }, + }, }); } @@ -153,30 +150,26 @@ class WebConnect extends Server { const self = this; return new Promise((resolve, reject) => { - while (this[webConnectSymbol].dataReceived() === true) { let obj = this[webConnectSymbol].poll(); if (!isObject(obj)) { - reject(new Error('The received data is not an object.')); + reject(new Error("The received data is not an object.")); return; } if (!(obj instanceof Message)) { - reject(new Error('The received data is not a Message.')); + reject(new Error("The received data is not a Message.")); return; } obj = obj.getData(); obj = self.transformServerPayload.call(self, obj); - self.set( obj); + self.set(obj); } resolve(self.get()); - - }) - - }; - + }); + } /** * @return {Promise} @@ -184,7 +177,7 @@ class WebConnect extends Server { write() { const self = this; let obj = self.prepareServerPayload(self.get()); - return self[webConnectSymbol].send(obj) + return self[webConnectSymbol].send(obj); } /** @@ -192,8 +185,6 @@ class WebConnect extends Server { */ getClone() { const self = this; - return new WebConnect(self[internalSymbol].getRealSubject()['options']); + return new WebConnect(self[internalSymbol].getRealSubject()["options"]); } - } - diff --git a/application/source/data/datasource/storage.mjs b/application/source/data/datasource/storage.mjs index bf6bdcb52..548555f3d 100644 --- a/application/source/data/datasource/storage.mjs +++ b/application/source/data/datasource/storage.mjs @@ -5,21 +5,21 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol,instanceSymbol} from "../../constants.mjs"; -import {validateString} from "../../types/validate.mjs"; -import {Datasource} from "../datasource.mjs"; +import { internalSymbol, instanceSymbol } from "../../constants.mjs"; +import { validateString } from "../../types/validate.mjs"; +import { Datasource } from "../datasource.mjs"; -export {Storage, storageObjectSymbol} +export { Storage, storageObjectSymbol }; /** * @private * @type {symbol} */ -const storageObjectSymbol = Symbol.for ('@schukai/monster/data/datasource/storage/@@storageObject') +const storageObjectSymbol = Symbol.for("@schukai/monster/data/datasource/storage/@@storageObject"); /** * The class represents a record. - * + * * @license AGPLv3 * @since 1.22.0 * @copyright schukai GmbH @@ -27,7 +27,6 @@ const storageObjectSymbol = Symbol.for ('@schukai/monster/data/datasource/stora * @summary The Storage class encapsulates the access to data objects over WebStorageAPI. */ class Storage extends Datasource { - /** * * @param {string} key LocalStorage Key @@ -35,7 +34,7 @@ class Storage extends Datasource { */ constructor(key) { super(); - this.setOption('key', validateString(key)); + this.setOption("key", validateString(key)); } /** @@ -45,7 +44,7 @@ class Storage extends Datasource { */ static get [instanceSymbol]() { return Symbol.for("@schukai/monster/data/datasource/storage"); - } + } /** * @property {string} key=undefined LocalStorage Key @@ -62,7 +61,7 @@ class Storage extends Datasource { * @private */ [storageObjectSymbol]() { - throw new Error("this method must be implemented by derived classes") + throw new Error("this method must be implemented by derived classes"); } /** @@ -77,11 +76,10 @@ class Storage extends Datasource { const storage = self[storageObjectSymbol](); return new Promise(function (resolve) { - const data = JSON.parse(storage.getItem(self.getOption('key'))); - self.set(data??{}); + const data = JSON.parse(storage.getItem(self.getOption("key"))); + self.set(data ?? {}); resolve(); - }) - + }); } /** @@ -94,24 +92,22 @@ class Storage extends Datasource { const storage = self[storageObjectSymbol](); return new Promise(function (resolve) { - const data = self.get(); if (data === undefined) { - storage.removeItem(self.getOption('key')); + storage.removeItem(self.getOption("key")); } else { - storage.setItem(self.getOption('key'), JSON.stringify(data)); + storage.setItem(self.getOption("key"), JSON.stringify(data)); } resolve(); - }) + }); } /** * @return {Storage} */ getClone() { - const self=this; - return new Storage(self[internalSymbol].getRealSubject()['options'].key); - } - + const self = this; + return new Storage(self[internalSymbol].getRealSubject()["options"].key); + } } diff --git a/application/source/data/datasource/storage/localstorage.mjs b/application/source/data/datasource/storage/localstorage.mjs index 3cf46c45b..e53df0265 100644 --- a/application/source/data/datasource/storage/localstorage.mjs +++ b/application/source/data/datasource/storage/localstorage.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol,instanceSymbol} from "../../../constants.mjs"; -import {getGlobalObject} from "../../../types/global.mjs"; -import {Datasource} from "../../datasource.mjs"; -import {Storage, storageObjectSymbol} from "../storage.mjs"; +import { internalSymbol, instanceSymbol } from "../../../constants.mjs"; +import { getGlobalObject } from "../../../types/global.mjs"; +import { Datasource } from "../../datasource.mjs"; +import { Storage, storageObjectSymbol } from "../storage.mjs"; -export {LocalStorage} +export { LocalStorage }; /** * The LocalStorage Datasource provides a data store in the browser localStorage. - * + * * @license AGPLv3 * @since 1.22.0 * @copyright schukai GmbH @@ -22,14 +22,13 @@ export {LocalStorage} * @summary The LocalStorage class encapsulates the access to data objects. */ class LocalStorage extends Storage { - /** * @throws {Error} this method must be implemented by derived classes. * @return {external:localStorage} * @private */ [storageObjectSymbol]() { - return getGlobalObject('localStorage'); + return getGlobalObject("localStorage"); } /** @@ -47,8 +46,6 @@ class LocalStorage extends Storage { */ getClone() { const self = this; - return new LocalStorage(self[internalSymbol].getRealSubject()['options'].key); + return new LocalStorage(self[internalSymbol].getRealSubject()["options"].key); } - - } diff --git a/application/source/data/datasource/storage/sessionstorage.mjs b/application/source/data/datasource/storage/sessionstorage.mjs index 69c3f1dea..779b2c318 100644 --- a/application/source/data/datasource/storage/sessionstorage.mjs +++ b/application/source/data/datasource/storage/sessionstorage.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol,instanceSymbol} from "../../../constants.mjs"; -import {getGlobalObject} from "../../../types/global.mjs"; -import {Datasource} from "../../datasource.mjs"; -import {Storage, storageObjectSymbol} from "../storage.mjs"; +import { internalSymbol, instanceSymbol } from "../../../constants.mjs"; +import { getGlobalObject } from "../../../types/global.mjs"; +import { Datasource } from "../../datasource.mjs"; +import { Storage, storageObjectSymbol } from "../storage.mjs"; -export {SessionStorage} +export { SessionStorage }; /** * The SessionStorage class provides a data source that uses the SessionStorage API on the client. @@ -22,14 +22,13 @@ export {SessionStorage} * @summary The LocalStorage class encapsulates the access to data objects. */ class SessionStorage extends Storage { - /** * @throws {Error} this method must be implemented by derived classes. * @return {external:sessionStorage} * @private */ [storageObjectSymbol]() { - return getGlobalObject('sessionStorage'); + return getGlobalObject("sessionStorage"); } /** @@ -43,12 +42,11 @@ class SessionStorage extends Storage { /** * Create Clone - * + * * @return {SessionStorage} */ getClone() { const self = this; - return new SessionStorage(self[internalSymbol].getRealSubject()['options'].key); + return new SessionStorage(self[internalSymbol].getRealSubject()["options"].key); } - } diff --git a/application/source/data/diff.mjs b/application/source/data/diff.mjs index d3761bc0e..efdb26d98 100644 --- a/application/source/data/diff.mjs +++ b/application/source/data/diff.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray, isObject} from "../types/is.mjs"; -import {typeOf} from "../types/typeof.mjs"; +import { isArray, isObject } from "../types/is.mjs"; +import { typeOf } from "../types/typeof.mjs"; -export {diff} +export { diff }; /** * With the diff function you can perform the change of one object to another. The result shows the changes of the second object to the first object. @@ -25,7 +25,7 @@ export {diff} * @memberOf Monster.Data */ function diff(first, second) { - return doDiff(first, second) + return doDiff(first, second); } /** @@ -54,37 +54,30 @@ function getKeys(a, b, type) { * @return {array} */ function doDiff(a, b, path, diff) { - - let typeA = typeOf(a) - let typeB = typeOf(b) + let typeA = typeOf(a); + let typeB = typeOf(b); const currPath = path || []; const currDiff = diff || []; - if (typeA === typeB && (typeA === 'object' || typeA ==='array')) { - + if (typeA === typeB && (typeA === "object" || typeA === "array")) { getKeys(a, b, typeA).forEach((v) => { - - if (!(Object.prototype.hasOwnProperty.call(a, v))) { - currDiff.push(buildResult(a[v], b[v], 'add', currPath.concat(v))); - } else if (!(Object.prototype.hasOwnProperty.call(b, v))) { - currDiff.push(buildResult(a[v], b[v], 'delete', currPath.concat(v))); + if (!Object.prototype.hasOwnProperty.call(a, v)) { + currDiff.push(buildResult(a[v], b[v], "add", currPath.concat(v))); + } else if (!Object.prototype.hasOwnProperty.call(b, v)) { + currDiff.push(buildResult(a[v], b[v], "delete", currPath.concat(v))); } else { doDiff(a[v], b[v], currPath.concat(v), currDiff); } }); - } else { - const o = getOperator(a, b, typeA, typeB); if (o !== undefined) { currDiff.push(buildResult(a, b, o, path)); } - } return currDiff; - } /** @@ -97,16 +90,15 @@ function doDiff(a, b, path, diff) { * @private */ function buildResult(a, b, operator, path) { - const result = { operator, path, }; - if (operator !== 'add') { + if (operator !== "add") { result.first = { value: a, - type: typeof a + type: typeof a, }; if (isObject(a)) { @@ -117,10 +109,10 @@ function buildResult(a, b, operator, path) { } } - if (operator === 'add' || operator === 'update') { + if (operator === "add" || operator === "update") { result.second = { value: b, - type: typeof b + type: typeof b, }; if (isObject(b)) { @@ -129,7 +121,6 @@ function buildResult(a, b, operator, path) { result.second.instance = name; } } - } return result; @@ -142,7 +133,6 @@ function buildResult(a, b, operator, path) { * @return {boolean} */ function isNotEqual(a, b) { - if (typeof a !== typeof b) { return true; } @@ -161,7 +151,6 @@ function isNotEqual(a, b) { * @return {string|undefined} */ function getOperator(a, b) { - /** * @type {string|undefined} */ @@ -177,14 +166,13 @@ function getOperator(a, b) { */ let typeB = typeof b; - if (typeA === 'undefined' && typeB !== 'undefined') { - operator = 'add'; - } else if (typeA !== 'undefined' && typeB === 'undefined') { - operator = 'delete'; + if (typeA === "undefined" && typeB !== "undefined") { + operator = "add"; + } else if (typeA !== "undefined" && typeB === "undefined") { + operator = "delete"; } else if (isNotEqual(a, b)) { - operator = 'update'; + operator = "update"; } return operator; - } diff --git a/application/source/data/extend.mjs b/application/source/data/extend.mjs index 873b0e452..f82f6562d 100644 --- a/application/source/data/extend.mjs +++ b/application/source/data/extend.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray, isObject} from "../types/is.mjs"; -import {typeOf} from "../types/typeof.mjs"; +import { isArray, isObject } from "../types/is.mjs"; +import { typeOf } from "../types/typeof.mjs"; -export {extend} +export { extend }; /** * Extend copies all enumerable own properties from one or @@ -29,7 +29,7 @@ function extend(...args) { let o; let i; - if (typeof args !== 'object' || args[0] === null) { + if (typeof args !== "object" || args[0] === null) { throw new Error(`unsupported argument ${JSON.stringify(args[0])}`); } @@ -46,15 +46,13 @@ function extend(...args) { } for (let k in a) { - let v = a?.[k]; if (v === o?.[k]) { continue; } - if ((isObject(v)&&typeOf(v)==='object') || isArray(v)) { - + if ((isObject(v) && typeOf(v) === "object") || isArray(v)) { if (o[k] === undefined) { if (isArray(v)) { o[k] = []; @@ -63,16 +61,18 @@ function extend(...args) { } } else { if (typeOf(o[k]) !== typeOf(v)) { - throw new Error(`type mismatch: ${JSON.stringify(o[k])}(${typeOf(o[k])}) != ${JSON.stringify(v)}(${typeOf(v)})`); + throw new Error( + `type mismatch: ${JSON.stringify(o[k])}(${typeOf(o[k])}) != ${JSON.stringify(v)}(${typeOf( + v, + )})`, + ); } } o[k] = extend(o[k], v); - } else { o[k] = v; } - } } diff --git a/application/source/data/namespace.mjs b/application/source/data/namespace.mjs index 93c8fccc6..39733b778 100644 --- a/application/source/data/namespace.mjs +++ b/application/source/data/namespace.mjs @@ -3,8 +3,6 @@ * SPDX-License-Identifier: AGPL-3.0 */ - - /** * In this namespace you will find classes and methods for handling data. * @@ -12,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/data/pathfinder.mjs b/application/source/data/pathfinder.mjs index 28a067d43..219c62db0 100644 --- a/application/source/data/pathfinder.mjs +++ b/application/source/data/pathfinder.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {isArray, isInteger, isObject, isPrimitive} from '../types/is.mjs'; -import {Stack} from "../types/stack.mjs"; -import {validateInteger, validateString} from '../types/validate.mjs'; +import { Base } from "../types/base.mjs"; +import { isArray, isInteger, isObject, isPrimitive } from "../types/is.mjs"; +import { Stack } from "../types/stack.mjs"; +import { validateInteger, validateString } from "../types/validate.mjs"; -export {Pathfinder, DELIMITER, WILDCARD} +export { Pathfinder, DELIMITER, WILDCARD }; /** * path separator @@ -18,13 +18,13 @@ export {Pathfinder, DELIMITER, WILDCARD} * @private * @type {string} */ -const DELIMITER = '.'; +const DELIMITER = "."; /** * @private * @type {string} */ -const WILDCARD = '*'; +const WILDCARD = "*"; /** * Pathfinder is a class to find a path to an object. @@ -72,7 +72,6 @@ const WILDCARD = '*'; * @memberOf Monster.Data */ class Pathfinder extends Base { - /** * @param {array|object|Map|Set} value * @since 1.4.0 @@ -82,7 +81,7 @@ class Pathfinder extends Base { super(); if (isPrimitive(object)) { - throw new Error('the parameter must not be a simple type'); + throw new Error("the parameter must not be a simple type"); } this.object = object; @@ -165,16 +164,12 @@ class Pathfinder extends Base { try { getValueViaPath.call(this, this.object, path, true); return true; - } catch (e) { - - } + } catch (e) {} return false; } - } - /** * * @param {*} subject @@ -187,12 +182,11 @@ class Pathfinder extends Base { * @private */ function iterate(subject, path, check) { - - const result = new Map; + const result = new Map(); if (isObject(subject) || isArray(subject)) { for (const [key, value] of Object.entries(subject)) { - result.set(key, getValueViaPath.call(this, value, path, check)) + result.set(key, getValueViaPath.call(this, value, path, check)); } } else { let key = path.split(DELIMITER).shift(); @@ -200,15 +194,13 @@ function iterate(subject, path, check) { } return result; - - } /** * * @param {*} subject * @param [string} path - * @param [boolean} check + * @param [boolean} check * @returns {*} * @throws {TypeError} unsupported type * @throws {Error} the journey is not at its end @@ -216,12 +208,11 @@ function iterate(subject, path, check) { * @private */ function getValueViaPath(subject, path, check) { - if (path === "") { return subject; } - let parts = path.split(DELIMITER) + let parts = path.split(DELIMITER); let current = parts.shift(); if (current === this.wildCard) { @@ -229,51 +220,43 @@ function getValueViaPath(subject, path, check) { } if (isObject(subject) || isArray(subject)) { - let anchor; if (subject instanceof Map || subject instanceof WeakMap) { anchor = subject.get(current); - } else if (subject instanceof Set || subject instanceof WeakSet) { current = parseInt(current); - validateInteger(current) + validateInteger(current); anchor = [...subject]?.[current]; - - } else if (typeof WeakRef === 'function' && subject instanceof WeakRef) { - throw Error('unsupported action for this data type'); - + } else if (typeof WeakRef === "function" && subject instanceof WeakRef) { + throw Error("unsupported action for this data type"); } else if (isArray(subject)) { current = parseInt(current); - validateInteger(current) + validateInteger(current); anchor = subject?.[current]; } else { anchor = subject?.[current]; } if (isObject(anchor) || isArray(anchor)) { - return getValueViaPath.call(this, anchor, parts.join(DELIMITER), check) + return getValueViaPath.call(this, anchor, parts.join(DELIMITER), check); } if (parts.length > 0) { throw Error(`the journey is not at its end (${parts.join(DELIMITER)})`); } - if (check === true) { const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(subject), current); if (!subject.hasOwnProperty(current) && descriptor === undefined) { - throw Error('unknown value'); + throw Error("unknown value"); } - } return anchor; - } - throw TypeError(`unsupported type ${typeof subject}`) - + throw TypeError(`unsupported type ${typeof subject}`); } /** @@ -289,23 +272,19 @@ function getValueViaPath(subject, path, check) { * @private */ function setValueViaPath(object, path, value) { - validateString(path); - let parts = path.split(DELIMITER) + let parts = path.split(DELIMITER); let last = parts.pop(); let subpath = parts.join(DELIMITER); - let stack = new Stack() + let stack = new Stack(); let current = subpath; while (true) { - try { - getValueViaPath.call(this, object, current, true) + getValueViaPath.call(this, object, current, true); break; - } catch (e) { - - } + } catch (e) {} stack.push(current); parts.pop(); @@ -323,7 +302,6 @@ function setValueViaPath(object, path, value) { if (isInteger(parseInt(n))) { obj = []; } - } setValueViaPath.call(this, object, current, obj); @@ -338,20 +316,16 @@ function setValueViaPath(object, path, value) { if (anchor instanceof Map || anchor instanceof WeakMap) { anchor.set(last, value); } else if (anchor instanceof Set || anchor instanceof WeakSet) { - anchor.append(value) - - } else if (typeof WeakRef === 'function' && anchor instanceof WeakRef) { - throw Error('unsupported action for this data type'); - + anchor.append(value); + } else if (typeof WeakRef === "function" && anchor instanceof WeakRef) { + throw Error("unsupported action for this data type"); } else if (isArray(anchor)) { last = parseInt(last); - validateInteger(last) + validateInteger(last); assignProperty(anchor, last, value); } else { assignProperty(anchor, last, value); } - - } /** @@ -361,7 +335,6 @@ function setValueViaPath(object, path, value) { * @param {*} value */ function assignProperty(object, key, value) { - if (!object.hasOwnProperty(key)) { object[key] = value; return; @@ -372,7 +345,6 @@ function assignProperty(object, key, value) { } object[key] = value; - } /** @@ -389,8 +361,7 @@ function assignProperty(object, key, value) { * @private */ function deleteValueViaPath(object, path) { - - const parts = path.split(DELIMITER) + const parts = path.split(DELIMITER); let last = parts.pop(); const subpath = parts.join(DELIMITER); @@ -398,16 +369,18 @@ function deleteValueViaPath(object, path) { if (anchor instanceof Map) { anchor.delete(last); - } else if (anchor instanceof Set || anchor instanceof WeakMap || anchor instanceof WeakSet || (typeof WeakRef === 'function' && anchor instanceof WeakRef)) { - throw Error('unsupported action for this data type'); - + } else if ( + anchor instanceof Set || + anchor instanceof WeakMap || + anchor instanceof WeakSet || + (typeof WeakRef === "function" && anchor instanceof WeakRef) + ) { + throw Error("unsupported action for this data type"); } else if (isArray(anchor)) { last = parseInt(last); - validateInteger(last) + validateInteger(last); delete anchor[last]; } else { delete anchor[last]; } - - } diff --git a/application/source/data/pipe.mjs b/application/source/data/pipe.mjs index ff326d175..fa5f2af62 100644 --- a/application/source/data/pipe.mjs +++ b/application/source/data/pipe.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {validateString} from '../types/validate.mjs'; -import {Transformer} from './transformer.mjs'; +import { Base } from "../types/base.mjs"; +import { validateString } from "../types/validate.mjs"; +import { Transformer } from "./transformer.mjs"; -export {Pipe} +export { Pipe }; /** * @private * @type {string} */ -const DELIMITER = '|'; +const DELIMITER = "|"; /** * The pipe class makes it possible to combine several processing steps. @@ -32,7 +32,6 @@ const DELIMITER = '|'; * @memberOf Monster.Data */ class Pipe extends Base { - /** * @param {string} pipe a pipe consists of commands whose input and output are connected with the pipe symbol `|`. * @throws {TypeError} @@ -40,12 +39,10 @@ class Pipe extends Base { constructor(pipe) { super(); validateString(pipe); - + this.pipe = pipe.split(DELIMITER).map((v) => { return new Transformer(v); }); - - } /** @@ -57,7 +54,6 @@ class Pipe extends Base { * @throws {TypeError} value is not a function */ setCallback(name, callback, context) { - for (const [, t] of Object.entries(this.pipe)) { t.setCallback(name, callback, context); } diff --git a/application/source/data/transformer.mjs b/application/source/data/transformer.mjs index 0ff171ac2..dad571f2c 100644 --- a/application/source/data/transformer.mjs +++ b/application/source/data/transformer.mjs @@ -1,5 +1,3 @@ - - /** * Copyright schukai GmbH and contributors 2022. All Rights Reserved. * Node module: @schukai/monster @@ -7,22 +5,21 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ - -import {Base} from '../types/base.mjs'; -import {getGlobal, getGlobalObject} from "../types/global.mjs"; -import {ID} from '../types/id.mjs'; -import {isArray, isObject, isString} from '../types/is.mjs'; +import { Base } from "../types/base.mjs"; +import { getGlobal, getGlobalObject } from "../types/global.mjs"; +import { ID } from "../types/id.mjs"; +import { isArray, isObject, isString } from "../types/is.mjs"; import { validateFunction, validateInteger, validateObject, validatePrimitive, - validateString -} from '../types/validate.mjs'; -import {clone} from "../util/clone.mjs"; -import {Pathfinder} from "./pathfinder.mjs"; + validateString, +} from "../types/validate.mjs"; +import { clone } from "../util/clone.mjs"; +import { Pathfinder } from "./pathfinder.mjs"; -export {Transformer} +export { Transformer }; /** * The transformer class is a swiss army knife for manipulating values. especially in combination with the pipe, processing chains can be built up. @@ -82,7 +79,7 @@ export {Transformer} * url: 'http://example.com/', * pretendToBeVisual: true * }); - * + * * [ * 'self', * 'document', @@ -120,9 +117,8 @@ class Transformer extends Base { constructor(definition) { super(); this.args = disassemble(definition); - this.command = this.args.shift() + this.command = this.args.shift(); this.callbacks = new Map(); - } /** @@ -135,8 +131,8 @@ class Transformer extends Base { * @throws {TypeError} value is not a function */ setCallback(name, callback, context) { - validateString(name) - validateFunction(callback) + validateString(name); + validateFunction(callback); if (context !== undefined) { validateObject(context); @@ -159,7 +155,7 @@ class Transformer extends Base { * @throws {Error} type not supported */ run(value) { - return transform.apply(this, [value]) + return transform.apply(this, [value]); } } @@ -170,33 +166,31 @@ class Transformer extends Base { * @private */ function disassemble(command) { - validateString(command); - let placeholder = new Map; - const regex = /((?<pattern>\\(?<char>.)){1})/mig; + let placeholder = new Map(); + const regex = /((?<pattern>\\(?<char>.)){1})/gim; // The separator for args must be escaped // undefined string which should not occur normally and is also not a regex - let result = command.matchAll(regex) + let result = command.matchAll(regex); for (let m of result) { - let g = m?.['groups']; + let g = m?.["groups"]; if (!isObject(g)) { continue; } - let p = g?.['pattern']; - let c = g?.['char']; + let p = g?.["pattern"]; + let c = g?.["char"]; if (p && c) { let r = `__${new ID().toString()}__`; placeholder.set(r, c); command = command.replace(p, r); } - } - let parts = command.split(':'); + let parts = command.split(":"); parts = parts.map(function (value) { let v = value.trim(); @@ -204,11 +198,9 @@ function disassemble(command) { v = v.replace(k[0], k[1]); } return v; - - }); - return parts + return parts; } /** @@ -219,12 +211,11 @@ function disassemble(command) { * @private */ function convertToString(value) { - - if (isObject(value) && value.hasOwnProperty('toString')) { + if (isObject(value) && value.hasOwnProperty("toString")) { value = value.toString(); } - validateString(value) + validateString(value); return value; } @@ -239,60 +230,56 @@ function convertToString(value) { * @throws {Error} missing key parameter */ function transform(value) { - - const console = getGlobalObject('console'); + const console = getGlobalObject("console"); let args = clone(this.args); let key; let defaultValue; switch (this.command) { + case "static": + return this.args.join(":"); - case 'static': - return this.args.join(':'); - - case 'tolower': - case 'strtolower': - case 'tolowercase': - validateString(value) + case "tolower": + case "strtolower": + case "tolowercase": + validateString(value); return value.toLowerCase(); - case 'toupper': - case 'strtoupper': - case 'touppercase': - validateString(value) + case "toupper": + case "strtoupper": + case "touppercase": + validateString(value); return value.toUpperCase(); - case 'tostring': + case "tostring": return `${value}`; - case 'tointeger': + case "tointeger": let n = parseInt(value); validateInteger(n); - return n + return n; - case 'tojson': + case "tojson": return JSON.stringify(value); - case 'fromjson': + case "fromjson": return JSON.parse(value); - case 'trim': - validateString(value) + case "trim": + validateString(value); return value.trim(); - case 'rawurlencode': - validateString(value) + case "rawurlencode": + validateString(value); return encodeURIComponent(value) - .replace(/!/g, '%21') - .replace(/'/g, '%27') - .replace(/\(/g, '%28') - .replace(/\)/g, '%29') - .replace(/\*/g, '%2A'); - - - case 'call': + .replace(/!/g, "%21") + .replace(/'/g, "%27") + .replace(/\(/g, "%28") + .replace(/\)/g, "%29") + .replace(/\*/g, "%2A"); + case "call": /** * callback-definition * function callback(value, ...args) { @@ -308,9 +295,9 @@ function transform(value) { callback = value[callbackName]; } else if (this.callbacks.has(callbackName)) { let s = this.callbacks.get(callbackName); - callback = s?.['callback']; - context = s?.['context']; - } else if (typeof window === 'object' && window.hasOwnProperty(callbackName)) { + callback = s?.["callback"]; + context = s?.["context"]; + } else if (typeof window === "object" && window.hasOwnProperty(callbackName)) { callback = window[callbackName]; } validateFunction(callback); @@ -318,119 +305,117 @@ function transform(value) { args.unshift(value); return callback.call(context, ...args); - case 'plain': - case 'plaintext': + case "plain": + case "plaintext": validateString(value); - let doc = new DOMParser().parseFromString(value, 'text/html'); + let doc = new DOMParser().parseFromString(value, "text/html"); return doc.body.textContent || ""; - case 'if': - case '?': - + case "if": + case "?": validatePrimitive(value); - let trueStatement = (args.shift() || undefined); - let falseStatement = (args.shift() || undefined); + let trueStatement = args.shift() || undefined; + let falseStatement = args.shift() || undefined; - if (trueStatement === 'value') { + if (trueStatement === "value") { trueStatement = value; } - if (trueStatement === '\\value') { - trueStatement = 'value'; + if (trueStatement === "\\value") { + trueStatement = "value"; } - if (falseStatement === 'value') { + if (falseStatement === "value") { falseStatement = value; } - if (falseStatement === '\\value') { - falseStatement = 'value'; + if (falseStatement === "\\value") { + falseStatement = "value"; } - let condition = ((value !== undefined && value !== '' && value !== 'off' && value !== 'false' && value !== false) || value === 'on' || value === 'true' || value === true); + let condition = + (value !== undefined && value !== "" && value !== "off" && value !== "false" && value !== false) || + value === "on" || + value === "true" || + value === true; return condition ? trueStatement : falseStatement; - - case 'ucfirst': + case "ucfirst": validateString(value); let firstchar = value.charAt(0).toUpperCase(); return firstchar + value.substr(1); - case 'ucwords': + case "ucwords": validateString(value); return value.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function (v) { return v.toUpperCase(); }); - case 'count': - case 'length': - - if ((isString(value) || isObject(value) || isArray(value)) && value.hasOwnProperty('length')) { + case "count": + case "length": + if ((isString(value) || isObject(value) || isArray(value)) && value.hasOwnProperty("length")) { return value.length; } throw new TypeError(`unsupported type ${typeof value}`); - case 'to-base64': - case 'btoa': - case 'base64': + case "to-base64": + case "btoa": + case "base64": return btoa(convertToString(value)); - case 'atob': - case 'from-base64': + case "atob": + case "from-base64": return atob(convertToString(value)); - case 'empty': - return ''; + case "empty": + return ""; - case 'undefined': + case "undefined": return undefined; - case 'debug': - + case "debug": if (isObject(console)) { console.log(value); } return value; - case 'prefix': + case "prefix": validateString(value); let prefix = args?.[0]; return prefix + value; - case 'suffix': + case "suffix": validateString(value); let suffix = args?.[0]; return value + suffix; - case 'uniqid': - return (new ID()).toString(); - - case 'first-key': - case 'last-key': - case 'nth-last-key': - case 'nth-key': + case "uniqid": + return new ID().toString(); + case "first-key": + case "last-key": + case "nth-last-key": + case "nth-key": if (!isObject(value)) { - throw new Error("type not supported") + throw new Error("type not supported"); } - const keys = Object.keys(value).sort() + const keys = Object.keys(value).sort(); - if (this.command === 'first-key') { + if (this.command === "first-key") { key = 0; - } else if (this.command === 'last-key') { + } else if (this.command === "last-key") { key = keys.length - 1; } else { - key = validateInteger(parseInt(args.shift())); - if (this.command === 'nth-last-key') { + if (this.command === "nth-last-key") { key = keys.length - key - 1; } } - defaultValue = (args.shift() || ''); + defaultValue = args.shift() || ""; let useKey = keys?.[key]; @@ -440,18 +425,16 @@ function transform(value) { return defaultValue; - - case 'key': - case 'property': - case 'index': - + case "key": + case "property": + case "index": key = args.shift() || undefined; if (key === undefined) { - throw new Error("missing key parameter") + throw new Error("missing key parameter"); } - defaultValue = (args.shift() || undefined); + defaultValue = args.shift() || undefined; if (value instanceof Map) { if (!value.has(key)) { @@ -461,7 +444,6 @@ function transform(value) { } if (isObject(value) || isArray(value)) { - if (value?.[key]) { return value?.[key]; } @@ -469,22 +451,20 @@ function transform(value) { return defaultValue; } - throw new Error("type not supported") - - case 'path-exists': + throw new Error("type not supported"); + case "path-exists": key = args.shift(); if (key === undefined) { - throw new Error("missing key parameter") + throw new Error("missing key parameter"); } return new Pathfinder(value).exists(key); - case 'path': - + case "path": key = args.shift(); if (key === undefined) { - throw new Error("missing key parameter") + throw new Error("missing key parameter"); } let pf = new Pathfinder(value); @@ -495,9 +475,7 @@ function transform(value) { return pf.getVia(key); - - case 'substring': - + case "substring": validateString(value); let start = parseInt(args[0]) || 0; @@ -505,11 +483,11 @@ function transform(value) { return value.substring(start, end); - case 'nop': + case "nop": return value; - case '??': - case 'default': + case "??": + case "default": if (value !== undefined && value !== null) { return value; } @@ -517,33 +495,39 @@ function transform(value) { defaultValue = args.shift(); let defaultType = args.shift(); if (defaultType === undefined) { - defaultType = 'string'; + defaultType = "string"; } switch (defaultType) { - case 'int': - case 'integer': + case "int": + case "integer": return parseInt(defaultValue); - case 'float': + case "float": return parseFloat(defaultValue); - case 'undefined': - return undefined - case 'bool': - case 'boolean': - defaultValue = defaultValue.toLowerCase() - return ((defaultValue !== 'undefined' && defaultValue !== '' && defaultValue !== 'off' && defaultValue !== 'false' && defaultValue !== 'false') || defaultValue === 'on' || defaultValue === 'true' || defaultValue === 'true'); - case 'string': + case "undefined": + return undefined; + case "bool": + case "boolean": + defaultValue = defaultValue.toLowerCase(); + return ( + (defaultValue !== "undefined" && + defaultValue !== "" && + defaultValue !== "off" && + defaultValue !== "false" && + defaultValue !== "false") || + defaultValue === "on" || + defaultValue === "true" || + defaultValue === "true" + ); + case "string": return `${defaultValue}`; case "object": return JSON.parse(atob(defaultValue)); } - throw new Error("type not supported") - + throw new Error("type not supported"); default: - throw new Error(`unknown command ${this.command}`) + throw new Error(`unknown command ${this.command}`); } - } - diff --git a/application/source/dom/assembler.mjs b/application/source/dom/assembler.mjs index 38f89532a..cd08b236e 100644 --- a/application/source/dom/assembler.mjs +++ b/application/source/dom/assembler.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {getGlobalFunction} from "../types/global.mjs"; -import {ProxyObserver} from "../types/proxyobserver.mjs"; -import {validateInstance, validateString} from "../types/validate.mjs"; +import { Base } from "../types/base.mjs"; +import { getGlobalFunction } from "../types/global.mjs"; +import { ProxyObserver } from "../types/proxyobserver.mjs"; +import { validateInstance, validateString } from "../types/validate.mjs"; -export {ATTRIBUTEPREFIX,Assembler} +export { ATTRIBUTEPREFIX, Assembler }; /** * attribute prefix @@ -30,7 +30,6 @@ const ATTRIBUTEPREFIX = "data-monster-"; * @summary Allows you to build an html fragment */ class Assembler extends Base { - /** * @param {DocumentFragment} fragment * @throws {TypeError} value is not an instance of @@ -40,7 +39,7 @@ class Assembler extends Base { constructor(fragment) { super(); this.attributePrefix = ATTRIBUTEPREFIX; - validateInstance(fragment, getGlobalFunction('DocumentFragment')); + validateInstance(fragment, getGlobalFunction("DocumentFragment")); this.fragment = fragment; } @@ -71,7 +70,6 @@ class Assembler extends Base { * @throws {TypeError} value is not an instance of */ createDocumentFragment(data) { - if (data === undefined) { data = new ProxyObserver({}); } @@ -80,5 +78,4 @@ class Assembler extends Base { let fragment = this.fragment.cloneNode(true); return fragment; } - } diff --git a/application/source/dom/attributes.mjs b/application/source/dom/attributes.mjs index ac553ac17..d8d9b199f 100644 --- a/application/source/dom/attributes.mjs +++ b/application/source/dom/attributes.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getGlobalFunction} from "../types/global.mjs"; -import {TokenList} from "../types/tokenlist.mjs"; -import {validateInstance, validateString, validateSymbol} from "../types/validate.mjs"; -import {ATTRIBUTE_OBJECTLINK} from "./constants.mjs"; +import { getGlobalFunction } from "../types/global.mjs"; +import { TokenList } from "../types/tokenlist.mjs"; +import { validateInstance, validateString, validateSymbol } from "../types/validate.mjs"; +import { ATTRIBUTE_OBJECTLINK } from "./constants.mjs"; export { findClosestObjectLink, @@ -23,8 +23,8 @@ export { replaceAttributeToken, clearAttributeTokens, findClosestByAttribute, - findClosestByClass -} + findClosestByClass, +}; /** * Get the closest object link of a node @@ -57,18 +57,16 @@ function findClosestObjectLink(element) { * @return {boolean} */ function addToObjectLink(element, symbol, object) { - validateInstance(element, HTMLElement); - validateSymbol(symbol) + validateSymbol(symbol); if (element?.[symbol] === undefined) { - element[symbol] = new Set; + element[symbol] = new Set(); } addAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); element[symbol].add(object); return element; - } /** @@ -83,21 +81,18 @@ function addToObjectLink(element, symbol, object) { * @return {boolean} */ function removeObjectLink(element, symbol) { - validateInstance(element, HTMLElement); - validateSymbol(symbol) + validateSymbol(symbol); if (element?.[symbol] === undefined) { - return element + return element; } removeAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); delete element[symbol]; return element; - } - /** * Checks if an element has an object link * @@ -110,16 +105,14 @@ function removeObjectLink(element, symbol) { * @return {boolean} */ function hasObjectLink(element, symbol) { - validateInstance(element, HTMLElement); - validateSymbol(symbol) + validateSymbol(symbol); if (element?.[symbol] === undefined) { - return false + return false; } return containsAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); - } /** @@ -140,19 +133,16 @@ function hasObjectLink(element, symbol) { * @throws {Error} there is no object link for symbol */ function getLinkedObjects(element, symbol) { - validateInstance(element, HTMLElement); - validateSymbol(symbol) + validateSymbol(symbol); if (element?.[symbol] === undefined) { throw new Error(`there is no object link for ${symbol.toString()}`); } return element?.[symbol][Symbol.iterator](); - } - /** * With this method tokens in an attribute can be switched on or off. For example, classes can be switched on and off in the elements class attribute. * @@ -169,8 +159,8 @@ function getLinkedObjects(element, symbol) { */ function toggleAttributeToken(element, key, token) { validateInstance(element, HTMLElement); - validateString(token) - validateString(key) + validateString(token); + validateString(key); if (!element.hasAttribute(key)) { element.setAttribute(key, token); @@ -179,7 +169,7 @@ function toggleAttributeToken(element, key, token) { element.setAttribute(key, new TokenList(element.getAttribute(key)).toggle(token).toString()); - return element + return element; } /** @@ -196,8 +186,8 @@ function toggleAttributeToken(element, key, token) { */ function addAttributeToken(element, key, token) { validateInstance(element, HTMLElement); - validateString(token) - validateString(key) + validateString(token); + validateString(key); if (!element.hasAttribute(key)) { element.setAttribute(key, token); @@ -206,7 +196,7 @@ function addAttributeToken(element, key, token) { element.setAttribute(key, new TokenList(element.getAttribute(key)).add(token).toString()); - return element + return element; } /** @@ -225,8 +215,8 @@ function addAttributeToken(element, key, token) { */ function removeAttributeToken(element, key, token) { validateInstance(element, HTMLElement); - validateString(token) - validateString(key) + validateString(token); + validateString(key); if (!element.hasAttribute(key)) { return element; @@ -234,7 +224,7 @@ function removeAttributeToken(element, key, token) { element.setAttribute(key, new TokenList(element.getAttribute(key)).remove(token).toString()); - return element + return element; } /** @@ -253,15 +243,14 @@ function removeAttributeToken(element, key, token) { */ function containsAttributeToken(element, key, token) { validateInstance(element, HTMLElement); - validateString(token) - validateString(key) + validateString(token); + validateString(key); if (!element.hasAttribute(key)) { return false; } return new TokenList(element.getAttribute(key)).contains(token); - } /** @@ -279,9 +268,9 @@ function containsAttributeToken(element, key, token) { */ function replaceAttributeToken(element, key, from, to) { validateInstance(element, HTMLElement); - validateString(from) - validateString(to) - validateString(key) + validateString(from); + validateString(to); + validateString(key); if (!element.hasAttribute(key)) { return element; @@ -289,7 +278,7 @@ function replaceAttributeToken(element, key, from, to) { element.setAttribute(key, new TokenList(element.getAttribute(key)).replace(from, to).toString()); - return element + return element; } /** @@ -305,7 +294,7 @@ function replaceAttributeToken(element, key, from, to) { */ function clearAttributeTokens(element, key) { validateInstance(element, HTMLElement); - validateString(key) + validateString(key); if (!element.hasAttribute(key)) { return element; @@ -313,7 +302,7 @@ function clearAttributeTokens(element, key) { element.setAttribute(key, ""); - return element + return element; } /** @@ -346,7 +335,7 @@ function clearAttributeTokens(element, key) { * @summary find closest node */ function findClosestByAttribute(element, key, value) { - validateInstance(element, getGlobalFunction('HTMLElement')); + validateInstance(element, getGlobalFunction("HTMLElement")); if (element.hasAttribute(key)) { if (value === undefined) { @@ -356,7 +345,6 @@ function findClosestByAttribute(element, key, value) { if (element.getAttribute(key) === value) { return element; } - } let selector = validateString(key); @@ -400,7 +388,7 @@ function findClosestByAttribute(element, key, value) { * @summary find closest node */ function findClosestByClass(element, className) { - validateInstance(element, getGlobalFunction('HTMLElement')); + validateInstance(element, getGlobalFunction("HTMLElement")); if (element?.classList?.contains(validateString(className))) { return element; diff --git a/application/source/dom/constants.mjs b/application/source/dom/constants.mjs index ff5557be7..016984cc8 100644 --- a/application/source/dom/constants.mjs +++ b/application/source/dom/constants.mjs @@ -5,7 +5,6 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ - export { DEFAULT_THEME, ATTRIBUTE_PREFIX, @@ -59,16 +58,15 @@ export { ATTRIBUTE_EXPORTPARTS, ATTRIBUTE_HIDDEN, objectUpdaterLinkSymbol, - customElementUpdaterLinkSymbol - -} + customElementUpdaterLinkSymbol, +}; /** * default theme * @memberOf Monster.DOM * @type {string} */ -const DEFAULT_THEME = 'monster'; +const DEFAULT_THEME = "monster"; /** * @memberOf Monster.DOM @@ -76,7 +74,7 @@ const DEFAULT_THEME = 'monster'; * @since 1.8.0 * @type {string} */ -const ATTRIBUTE_PREFIX = 'data-monster-'; +const ATTRIBUTE_PREFIX = "data-monster-"; /** * This is the name of the attribute to pass options to a control @@ -190,7 +188,7 @@ const ATTRIBUTE_ROLE = `${ATTRIBUTE_PREFIX}role`; * @license AGPLv3 * @since 1.24.0 */ -const ATTRIBUTE_DISABLED = 'disabled'; +const ATTRIBUTE_DISABLED = "disabled"; /** * @memberOf Monster.DOM @@ -198,7 +196,7 @@ const ATTRIBUTE_DISABLED = 'disabled'; * @license AGPLv3 * @since 1.24.0 */ -const ATTRIBUTE_VALUE = 'value'; +const ATTRIBUTE_VALUE = "value"; /** * @memberOf Monster.DOM @@ -222,7 +220,7 @@ const ATTRIBUTE_ERRORMESSAGE = `${ATTRIBUTE_PREFIX}error`; * @license AGPLv3 * @since 1.24.0 */ -const objectUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/@@object-updater-link'); +const objectUpdaterLinkSymbol = Symbol.for("@schukai/monster/dom/@@object-updater-link"); /** * @memberOf Monster.DOM @@ -230,7 +228,7 @@ const objectUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/@@object-update * @license AGPLv3 * @since 1.24.0 */ -const customElementUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/custom-element@@options-updater-link'); +const customElementUpdaterLinkSymbol = Symbol.for("@schukai/monster/dom/custom-element@@options-updater-link"); /** * @memberOf Monster.DOM @@ -238,7 +236,7 @@ const customElementUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/custom-e * @license AGPLv3 * @since 1.25.0 */ -const TAG_SCRIPT = 'script'; +const TAG_SCRIPT = "script"; /** * @memberOf Monster.DOM @@ -246,7 +244,7 @@ const TAG_SCRIPT = 'script'; * @license AGPLv3 * @since 1.25.0 */ -const TAG_STYLE = 'style'; +const TAG_STYLE = "style"; /** * @memberOf Monster.DOM @@ -254,7 +252,7 @@ const TAG_STYLE = 'style'; * @license AGPLv3 * @since 1.25.0 */ -const TAG_LINK = 'link'; +const TAG_LINK = "link"; /** * @memberOf Monster.DOM @@ -263,7 +261,7 @@ const TAG_LINK = 'link'; * @since 1.25.0 */ -const ATTRIBUTE_ID = 'id'; +const ATTRIBUTE_ID = "id"; /** * @memberOf Monster.DOM @@ -272,7 +270,7 @@ const ATTRIBUTE_ID = 'id'; * @since 1.25.0 */ -const ATTRIBUTE_CLASS = 'class'; +const ATTRIBUTE_CLASS = "class"; /** * @memberOf Monster.DOM @@ -280,7 +278,7 @@ const ATTRIBUTE_CLASS = 'class'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_TITLE = 'title'; +const ATTRIBUTE_TITLE = "title"; /** * @memberOf Monster.DOM @@ -288,14 +286,14 @@ const ATTRIBUTE_TITLE = 'title'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_SRC = 'src'; +const ATTRIBUTE_SRC = "src"; /** * @memberOf Monster.DOM * @type {string} * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_HREF = 'href'; +const ATTRIBUTE_HREF = "href"; /** * @memberOf Monster.DOM @@ -303,7 +301,7 @@ const ATTRIBUTE_HREF = 'href'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_TYPE = 'type'; +const ATTRIBUTE_TYPE = "type"; /** * @memberOf Monster.DOM @@ -311,7 +309,7 @@ const ATTRIBUTE_TYPE = 'type'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_NONCE = 'nonce'; +const ATTRIBUTE_NONCE = "nonce"; /** * @memberOf Monster.DOM @@ -319,8 +317,7 @@ const ATTRIBUTE_NONCE = 'nonce'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_TRANSLATE = 'translate'; - +const ATTRIBUTE_TRANSLATE = "translate"; /** * @memberOf Monster.DOM @@ -328,8 +325,7 @@ const ATTRIBUTE_TRANSLATE = 'translate'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_TABINDEX = 'tabindex'; - +const ATTRIBUTE_TABINDEX = "tabindex"; /** * @memberOf Monster.DOM @@ -337,8 +333,7 @@ const ATTRIBUTE_TABINDEX = 'tabindex'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_SPELLCHECK = 'spellcheck'; - +const ATTRIBUTE_SPELLCHECK = "spellcheck"; /** * @memberOf Monster.DOM @@ -346,8 +341,7 @@ const ATTRIBUTE_SPELLCHECK = 'spellcheck'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_SLOT = 'slot'; - +const ATTRIBUTE_SLOT = "slot"; /** * @memberOf Monster.DOM @@ -355,8 +349,7 @@ const ATTRIBUTE_SLOT = 'slot'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_PART = 'part'; - +const ATTRIBUTE_PART = "part"; /** * @memberOf Monster.DOM @@ -364,8 +357,7 @@ const ATTRIBUTE_PART = 'part'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_LANG = 'lang'; - +const ATTRIBUTE_LANG = "lang"; /** * @memberOf Monster.DOM @@ -373,8 +365,7 @@ const ATTRIBUTE_LANG = 'lang'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ITEMTYPE = 'itemtype'; - +const ATTRIBUTE_ITEMTYPE = "itemtype"; /** * @memberOf Monster.DOM @@ -382,8 +373,7 @@ const ATTRIBUTE_ITEMTYPE = 'itemtype'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ITEMSCOPE = 'itemscope'; - +const ATTRIBUTE_ITEMSCOPE = "itemscope"; /** * @memberOf Monster.DOM @@ -391,8 +381,7 @@ const ATTRIBUTE_ITEMSCOPE = 'itemscope'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ITEMREF = 'itemref'; - +const ATTRIBUTE_ITEMREF = "itemref"; /** * @memberOf Monster.DOM @@ -400,8 +389,7 @@ const ATTRIBUTE_ITEMREF = 'itemref'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ITEMID = 'itemid'; - +const ATTRIBUTE_ITEMID = "itemid"; /** * @memberOf Monster.DOM @@ -409,8 +397,7 @@ const ATTRIBUTE_ITEMID = 'itemid'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ITEMPROP = 'itemprop'; - +const ATTRIBUTE_ITEMPROP = "itemprop"; /** * @memberOf Monster.DOM @@ -418,8 +405,7 @@ const ATTRIBUTE_ITEMPROP = 'itemprop'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_IS = 'is'; - +const ATTRIBUTE_IS = "is"; /** * @memberOf Monster.DOM @@ -427,8 +413,7 @@ const ATTRIBUTE_IS = 'is'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_INPUTMODE = 'inputmode'; - +const ATTRIBUTE_INPUTMODE = "inputmode"; /** * @memberOf Monster.DOM @@ -436,7 +421,7 @@ const ATTRIBUTE_INPUTMODE = 'inputmode'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ACCESSKEY = 'accesskey'; +const ATTRIBUTE_ACCESSKEY = "accesskey"; /** * @memberOf Monster.DOM @@ -444,7 +429,7 @@ const ATTRIBUTE_ACCESSKEY = 'accesskey'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_AUTOCAPITALIZE = 'autocapitalize'; +const ATTRIBUTE_AUTOCAPITALIZE = "autocapitalize"; /** * @memberOf Monster.DOM @@ -452,7 +437,7 @@ const ATTRIBUTE_AUTOCAPITALIZE = 'autocapitalize'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_AUTOFOCUS = 'autofocus'; +const ATTRIBUTE_AUTOFOCUS = "autofocus"; /** * @memberOf Monster.DOM @@ -460,7 +445,7 @@ const ATTRIBUTE_AUTOFOCUS = 'autofocus'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_CONTENTEDITABLE = 'contenteditable'; +const ATTRIBUTE_CONTENTEDITABLE = "contenteditable"; /** * @memberOf Monster.DOM @@ -468,7 +453,7 @@ const ATTRIBUTE_CONTENTEDITABLE = 'contenteditable'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_DIR = 'dir'; +const ATTRIBUTE_DIR = "dir"; /** * @memberOf Monster.DOM @@ -476,8 +461,7 @@ const ATTRIBUTE_DIR = 'dir'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_DRAGGABLE = 'draggable'; - +const ATTRIBUTE_DRAGGABLE = "draggable"; /** * @memberOf Monster.DOM @@ -485,18 +469,18 @@ const ATTRIBUTE_DRAGGABLE = 'draggable'; * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_ENTERKEYHINT = 'enterkeyhint'; +const ATTRIBUTE_ENTERKEYHINT = "enterkeyhint"; /** * @memberOf Monster.DOM * @type {string} * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_EXPORTPARTS = 'exportparts'; +const ATTRIBUTE_EXPORTPARTS = "exportparts"; /** * @memberOf Monster.DOM * @type {string} * @license AGPLv3 * @since 1.25.0 */ -const ATTRIBUTE_HIDDEN = 'hidden'; +const ATTRIBUTE_HIDDEN = "hidden"; diff --git a/application/source/dom/customcontrol.mjs b/application/source/dom/customcontrol.mjs index 52f621d51..48b2053f6 100644 --- a/application/source/dom/customcontrol.mjs +++ b/application/source/dom/customcontrol.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../data/extend.mjs"; -import {ATTRIBUTE_VALUE} from "./constants.mjs"; -import {CustomElement, attributeObserverSymbol} from "./customelement.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {CustomControl} +import { extend } from "../data/extend.mjs"; +import { ATTRIBUTE_VALUE } from "./constants.mjs"; +import { CustomElement, attributeObserverSymbol } from "./customelement.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { CustomControl }; /** * @private * @type {symbol} */ -const attachedInternalSymbol = Symbol('attachedInternal'); +const attachedInternalSymbol = Symbol("attachedInternal"); /** * To define a new HTML control we need the power of CustomElement @@ -47,7 +47,6 @@ const attachedInternalSymbol = Symbol('attachedInternal'); * @memberOf Monster.DOM */ class CustomControl extends CustomElement { - /** * IMPORTANT: CustomControls instances are not created via the constructor, but either via a tag in the HTML or via <code>document.createElement()</code>. * @@ -57,7 +56,7 @@ class CustomControl extends CustomElement { constructor() { super(); - if (typeof this['attachInternals'] === 'function') { + if (typeof this["attachInternals"] === "function") { /** * currently only supported by chrome * @property {Object} @@ -67,7 +66,6 @@ class CustomControl extends CustomElement { } initObserver.call(this); - } /** @@ -79,7 +77,6 @@ class CustomControl extends CustomElement { return Symbol.for("@schukai/monster/dom/custom-control"); } - /** * This method determines which attributes are to be monitored by `attributeChangedCallback()`. * @@ -90,8 +87,8 @@ class CustomControl extends CustomElement { const list = super.observedAttributes; list.push(ATTRIBUTE_VALUE); return list; - } - + } + /** * * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/attachInternals} @@ -131,7 +128,7 @@ class CustomControl extends CustomElement { * @throws {Error} the value getter must be overwritten by the derived class */ get value() { - throw Error('the value getter must be overwritten by the derived class'); + throw Error("the value getter must be overwritten by the derived class"); } /** @@ -144,7 +141,7 @@ class CustomControl extends CustomElement { * @throws {Error} the value setter must be overwritten by the derived class */ set value(value) { - throw Error('the value setter must be overwritten by the derived class'); + throw Error("the value setter must be overwritten by the derived class"); } /** @@ -165,7 +162,7 @@ class CustomControl extends CustomElement { * @return {string|null} */ get name() { - return this.getAttribute('name'); + return this.getAttribute("name"); } /** @@ -301,7 +298,6 @@ class CustomControl extends CustomElement { reportValidity() { return getInternal.call(this)?.reportValidity(); } - } /** @@ -314,7 +310,7 @@ function getInternal() { const self = this; if (!(attachedInternalSymbol in this)) { - throw new Error('ElementInternals is not supported and a polyfill is necessary'); + throw new Error("ElementInternals is not supported and a polyfill is necessary"); } return this[attachedInternalSymbol]; @@ -329,8 +325,7 @@ function initObserver() { const self = this; // value - self[attributeObserverSymbol]['value'] = () => { - self.setOption('value', self.getAttribute('value')); - } - + self[attributeObserverSymbol]["value"] = () => { + self.setOption("value", self.getAttribute("value")); + }; } diff --git a/application/source/dom/customelement.mjs b/application/source/dom/customelement.mjs index ffdffdfe0..7cd9540db 100644 --- a/application/source/dom/customelement.mjs +++ b/application/source/dom/customelement.mjs @@ -5,28 +5,28 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {extend} from "../data/extend.mjs"; -import {Pathfinder} from "../data/pathfinder.mjs"; - -import {parseDataURL} from "../types/dataurl.mjs"; -import {getGlobalObject} from "../types/global.mjs"; -import {isArray, isFunction, isObject, isString} from "../types/is.mjs"; -import {Observer} from "../types/observer.mjs"; -import {ProxyObserver} from "../types/proxyobserver.mjs"; -import {validateFunction, validateInstance, validateObject, validateString} from "../types/validate.mjs"; -import {clone} from "../util/clone.mjs"; -import {addAttributeToken, getLinkedObjects, hasObjectLink} from "./attributes.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { extend } from "../data/extend.mjs"; +import { Pathfinder } from "../data/pathfinder.mjs"; + +import { parseDataURL } from "../types/dataurl.mjs"; +import { getGlobalObject } from "../types/global.mjs"; +import { isArray, isFunction, isObject, isString } from "../types/is.mjs"; +import { Observer } from "../types/observer.mjs"; +import { ProxyObserver } from "../types/proxyobserver.mjs"; +import { validateFunction, validateInstance, validateObject, validateString } from "../types/validate.mjs"; +import { clone } from "../util/clone.mjs"; +import { addAttributeToken, getLinkedObjects, hasObjectLink } from "./attributes.mjs"; import { ATTRIBUTE_DISABLED, ATTRIBUTE_ERRORMESSAGE, ATTRIBUTE_OPTIONS, ATTRIBUTE_OPTIONS_SELECTOR, - customElementUpdaterLinkSymbol + customElementUpdaterLinkSymbol, } from "./constants.mjs"; -import {findDocumentTemplate, Template} from "./template.mjs"; -import {addObjectWithUpdaterToElement} from "./updater.mjs"; -import {instanceSymbol} from '../constants.mjs'; +import { findDocumentTemplate, Template } from "./template.mjs"; +import { addObjectWithUpdaterToElement } from "./updater.mjs"; +import { instanceSymbol } from "../constants.mjs"; export { CustomElement, @@ -34,28 +34,27 @@ export { assembleMethodSymbol, attributeObserverSymbol, registerCustomElement, - getSlottedElements -} + getSlottedElements, +}; /** * @memberOf Monster.DOM * @type {symbol} */ -const initMethodSymbol = Symbol.for('@schukai/monster/dom/@@initMethodSymbol'); +const initMethodSymbol = Symbol.for("@schukai/monster/dom/@@initMethodSymbol"); /** * @memberOf Monster.DOM * @type {symbol} */ -const assembleMethodSymbol = Symbol.for('@schukai/monster/dom/@@assembleMethodSymbol'); +const assembleMethodSymbol = Symbol.for("@schukai/monster/dom/@@assembleMethodSymbol"); /** * this symbol holds the attribute observer callbacks. The key is the attribute name. * @memberOf Monster.DOM * @type {symbol} */ -const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObserver'); - +const attributeObserverSymbol = Symbol.for("@schukai/monster/dom/@@attributeObserver"); /** * HTMLElement @@ -100,7 +99,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse * @enduml */ - /** * To define a new HTML element we need the power of CustomElement * @@ -187,7 +185,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse * @summary A base class for HTML5 customcontrols */ class CustomElement extends HTMLElement { - /** * A new object is created. First the `initOptions` method is called. Here the * options can be defined in derived classes. Subsequently, the shadowRoot is initialized. @@ -197,7 +194,9 @@ class CustomElement extends HTMLElement { */ constructor() { super(); - this[internalSymbol] = new ProxyObserver({'options': extend({}, this.defaults)}); + this[internalSymbol] = new ProxyObserver({ + options: extend({}, this.defaults), + }); this[attributeObserverSymbol] = {}; initOptionObserver.call(this); this[initMethodSymbol](); @@ -212,7 +211,6 @@ class CustomElement extends HTMLElement { return Symbol.for("@schukai/monster/dom/custom-element"); } - /** * This method determines which attributes are to be monitored by `attributeChangedCallback()`. * @@ -275,11 +273,11 @@ class CustomElement extends HTMLElement { get defaults() { return { ATTRIBUTE_DISABLED: this.getAttribute(ATTRIBUTE_DISABLED), - shadowMode: 'open', + shadowMode: "open", delegatesFocus: true, templates: { - main: undefined - } + main: undefined, + }, }; } @@ -329,7 +327,7 @@ class CustomElement extends HTMLElement { * @returns {CustomElement} */ attachObserver(observer) { - this[internalSymbol].attachObserver(observer) + this[internalSymbol].attachObserver(observer); return this; } @@ -340,7 +338,7 @@ class CustomElement extends HTMLElement { * @returns {CustomElement} */ detachObserver(observer) { - this[internalSymbol].detachObserver(observer) + this[internalSymbol].detachObserver(observer); return this; } @@ -349,7 +347,7 @@ class CustomElement extends HTMLElement { * @returns {ProxyObserver} */ containsObserver(observer) { - return this[internalSymbol].containsObserver(observer) + return this[internalSymbol].containsObserver(observer); } /** @@ -364,10 +362,8 @@ class CustomElement extends HTMLElement { let value; try { - value = new Pathfinder(this[internalSymbol].getRealSubject()['options']).getVia(path); - } catch (e) { - - } + value = new Pathfinder(this[internalSymbol].getRealSubject()["options"]).getVia(path); + } catch (e) {} if (value === undefined) return defaultValue; return value; @@ -382,7 +378,7 @@ class CustomElement extends HTMLElement { * @since 1.14.0 */ setOption(path, value) { - new Pathfinder(this[internalSymbol].getSubject()['options']).setVia(path, value); + new Pathfinder(this[internalSymbol].getSubject()["options"]).setVia(path, value); return this; } @@ -392,13 +388,12 @@ class CustomElement extends HTMLElement { * @return {CustomElement} */ setOptions(options) { - if (isString(options)) { - options = parseOptionsJSON.call(this, options) + options = parseOptionsJSON.call(this, options); } const self = this; - extend(self[internalSymbol].getSubject()['options'], self.defaults, options); + extend(self[internalSymbol].getSubject()["options"], self.defaults, options); return self; } @@ -420,7 +415,6 @@ class CustomElement extends HTMLElement { * @since 1.8.0 */ [assembleMethodSymbol]() { - const self = this; let elements; let nodeList; @@ -435,15 +429,11 @@ class CustomElement extends HTMLElement { self.setOptions(ScriptOptions); } - - if (self.getOption('shadowMode', false) !== false) { + if (self.getOption("shadowMode", false) !== false) { try { initShadowRoot.call(self); elements = self.shadowRoot.childNodes; - - } catch (e) { - - } + } catch (e) {} try { initCSSStylesheet.call(this); @@ -460,15 +450,17 @@ class CustomElement extends HTMLElement { } try { - nodeList = new Set([ - ...elements, - ...getSlottedElements.call(self) - ]) + nodeList = new Set([...elements, ...getSlottedElements.call(self)]); } catch (e) { - nodeList = elements + nodeList = elements; } - addObjectWithUpdaterToElement.call(self, nodeList, customElementUpdaterLinkSymbol, clone(self[internalSymbol].getRealSubject()['options'])) + addObjectWithUpdaterToElement.call( + self, + nodeList, + customElementUpdaterLinkSymbol, + clone(self[internalSymbol].getRealSubject()["options"]), + ); return self; } @@ -482,7 +474,7 @@ class CustomElement extends HTMLElement { connectedCallback() { let self = this; if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) { - self[assembleMethodSymbol]() + self[assembleMethodSymbol](); } } @@ -492,9 +484,7 @@ class CustomElement extends HTMLElement { * @return {void} * @since 1.7.0 */ - disconnectedCallback() { - - } + disconnectedCallback() {} /** * The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)). @@ -502,9 +492,7 @@ class CustomElement extends HTMLElement { * @return {void} * @since 1.7.0 */ - adoptedCallback() { - - } + adoptedCallback() {} /** * Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial @@ -525,7 +513,6 @@ class CustomElement extends HTMLElement { if (isFunction(callback)) { callback.call(self, newVal, oldVal); } - } /** @@ -547,9 +534,7 @@ class CustomElement extends HTMLElement { } return containChildNode.call(self.shadowRoot, node); - } - } /** @@ -564,27 +549,25 @@ class CustomElement extends HTMLElement { */ function getSlottedElements(query, name) { const self = this; - const result = new Set; + const result = new Set(); if (!(self.shadowRoot instanceof ShadowRoot)) { return result; } - let selector = 'slot'; + let selector = "slot"; if (name !== undefined) { if (name === null) { - selector += ':not([name])'; + selector += ":not([name])"; } else { selector += `[name=${validateString(name)}]`; } - } const slots = self.shadowRoot.querySelectorAll(selector); for (const [, slot] of Object.entries(slots)) { slot.assignedElements().forEach(function (node) { - if (!(node instanceof HTMLElement)) return; if (isString(query)) { @@ -595,13 +578,12 @@ function getSlottedElements(query, name) { if (node.matches(query)) { result.add(node); } - } else if (query !== undefined) { - throw new Error('query must be a string') + throw new Error("query must be a string"); } else { result.add(node); } - }) + }); } return result; @@ -628,7 +610,6 @@ function containChildNode(node) { containChildNode.call(e, node); } - return false; } @@ -642,59 +623,58 @@ function initOptionObserver() { const self = this; let lastDisabledValue = undefined; - self.attachObserver(new Observer(function () { - const flag = self.getOption('disabled'); - - if (flag === lastDisabledValue) { - return; - } + self.attachObserver( + new Observer(function () { + const flag = self.getOption("disabled"); - lastDisabledValue = flag; - - if (!(self.shadowRoot instanceof ShadowRoot)) { - return; - } - - const query = 'button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]'; - const elements = self.shadowRoot.querySelectorAll(query); + if (flag === lastDisabledValue) { + return; + } - let nodeList; - try { - nodeList = new Set([ - ...elements, - ...getSlottedElements.call(self, query) - ]) - } catch (e) { - nodeList = elements - } + lastDisabledValue = flag; - for (const element of [...nodeList]) { - if (flag === true) { - element.setAttribute(ATTRIBUTE_DISABLED, ''); - } else { - element.removeAttribute(ATTRIBUTE_DISABLED); + if (!(self.shadowRoot instanceof ShadowRoot)) { + return; } - } - - })); - self.attachObserver(new Observer(function () { + const query = + "button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]"; + const elements = self.shadowRoot.querySelectorAll(query); - // not initialised - if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) { - return; - } - // inform every element - const updaters = getLinkedObjects(self, customElementUpdaterLinkSymbol); + let nodeList; + try { + nodeList = new Set([...elements, ...getSlottedElements.call(self, query)]); + } catch (e) { + nodeList = elements; + } - for (const list of updaters) { - for (const updater of list) { - let d = clone(self[internalSymbol].getRealSubject()['options']); - Object.assign(updater.getSubject(), d); + for (const element of [...nodeList]) { + if (flag === true) { + element.setAttribute(ATTRIBUTE_DISABLED, ""); + } else { + element.removeAttribute(ATTRIBUTE_DISABLED); + } } - } + }), + ); + + self.attachObserver( + new Observer(function () { + // not initialised + if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) { + return; + } + // inform every element + const updaters = getLinkedObjects(self, customElementUpdaterLinkSymbol); - })); + for (const list of updaters) { + for (const updater of list) { + let d = clone(self[internalSymbol].getRealSubject()["options"]); + Object.assign(updater.getSubject(), d); + } + } + }), + ); // disabled self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => { @@ -703,7 +683,7 @@ function initOptionObserver() { } else { self.setOption(ATTRIBUTE_DISABLED, undefined); } - } + }; // data-monster-options self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => { @@ -711,7 +691,7 @@ function initOptionObserver() { if (isObject(options) && Object.keys(options).length > 0) { self.setOptions(options); } - } + }; // data-monster-options-selector self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => { @@ -719,9 +699,7 @@ function initOptionObserver() { if (isObject(options) && Object.keys(options).length > 0) { self.setOptions(options); } - } - - + }; } /** @@ -738,20 +716,29 @@ function getOptionsFromScriptTag() { const node = document.querySelector(self.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR)); if (!(node instanceof HTMLScriptElement)) { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `the selector ${ATTRIBUTE_OPTIONS_SELECTOR} for options was specified (${self.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR)}) but not found.`); + addAttributeToken( + self, + ATTRIBUTE_ERRORMESSAGE, + `the selector ${ATTRIBUTE_OPTIONS_SELECTOR} for options was specified (${self.getAttribute( + ATTRIBUTE_OPTIONS_SELECTOR, + )}) but not found.`, + ); return {}; } let obj = {}; try { - obj = parseOptionsJSON.call(this, node.textContent.trim()) + obj = parseOptionsJSON.call(this, node.textContent.trim()); } catch (e) { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `when analyzing the configuration from the script tag there was an error. ${e}`); + addAttributeToken( + self, + ATTRIBUTE_ERRORMESSAGE, + `when analyzing the configuration from the script tag there was an error. ${e}`, + ); } return obj; - } /** @@ -763,9 +750,15 @@ function getOptionsFromAttributes() { if (this.hasAttribute(ATTRIBUTE_OPTIONS)) { try { - return parseOptionsJSON.call(self, this.getAttribute(ATTRIBUTE_OPTIONS)) + return parseOptionsJSON.call(self, this.getAttribute(ATTRIBUTE_OPTIONS)); } catch (e) { - addAttributeToken(self, ATTRIBUTE_ERRORMESSAGE, `the options attribute ${ATTRIBUTE_OPTIONS} does not contain a valid json definition (actual: ${this.getAttribute(ATTRIBUTE_OPTIONS)}).${e}`); + addAttributeToken( + self, + ATTRIBUTE_ERRORMESSAGE, + `the options attribute ${ATTRIBUTE_OPTIONS} does not contain a valid json definition (actual: ${this.getAttribute( + ATTRIBUTE_OPTIONS, + )}).${e}`, + ); } } @@ -778,7 +771,6 @@ function getOptionsFromAttributes() { * @return {Object} */ function parseOptionsJSON(data) { - let obj = {}; if (!isString(data)) { @@ -789,9 +781,7 @@ function parseOptionsJSON(data) { try { let dataUrl = parseDataURL(data); data = dataUrl.content; - } catch (e) { - - } + } catch (e) {} try { obj = JSON.parse(data); @@ -799,7 +789,6 @@ function parseOptionsJSON(data) { throw e; } - return validateObject(obj); } @@ -808,21 +797,17 @@ function parseOptionsJSON(data) { * @return {initHtmlContent} */ function initHtmlContent() { - try { let template = findDocumentTemplate(this.constructor.getTag()); this.appendChild(template.createDocumentFragment()); } catch (e) { - - let html = this.getOption('templates.main', ''); + let html = this.getOption("templates.main", ""); if (isString(html) && html.length > 0) { this.innerHTML = html; } - } return this; - } /** @@ -850,11 +835,10 @@ function initCSSStylesheet() { } else if (isArray(styleSheet)) { const assign = []; for (let s of styleSheet) { - if (isString(s)) { - let trimedStyleSheet = s.trim() - if (trimedStyleSheet !== '') { - const style = document.createElement('style') + let trimedStyleSheet = s.trim(); + if (trimedStyleSheet !== "") { + const style = document.createElement("style"); style.innerHTML = trimedStyleSheet; self.shadowRoot.prepend(style); } @@ -866,26 +850,21 @@ function initCSSStylesheet() { if (s.cssRules.length > 0) { assign.push(s); } - } if (assign.length > 0) { this.shadowRoot.adoptedStyleSheets = assign; } - } else if (isString(styleSheet)) { - - let trimedStyleSheet = styleSheet.trim() - if (trimedStyleSheet !== '') { - const style = document.createElement('style') + let trimedStyleSheet = styleSheet.trim(); + if (trimedStyleSheet !== "") { + const style = document.createElement("style"); style.innerHTML = styleSheet; self.shadowRoot.prepend(style); } - } return self; - } /** @@ -898,24 +877,21 @@ function initCSSStylesheet() { * @since 1.8.0 */ function initShadowRoot() { - let template; let html; try { template = findDocumentTemplate(this.constructor.getTag()); } catch (e) { - - html = this.getOption('templates.main', ''); + html = this.getOption("templates.main", ""); if (!isString(html) || html === undefined || html === "") { throw new Error("html is not set."); } - } this.attachShadow({ - mode: this.getOption('shadowMode', 'open'), - delegatesFocus: this.getOption('delegatesFocus', true) + mode: this.getOption("shadowMode", "open"), + delegatesFocus: this.getOption("delegatesFocus", true), }); if (template instanceof Template) { @@ -940,6 +916,5 @@ function initShadowRoot() { */ function registerCustomElement(element) { validateFunction(element); - getGlobalObject('customElements').define(element.getTag(), element); + getGlobalObject("customElements").define(element.getTag(), element); } - diff --git a/application/source/dom/events.mjs b/application/source/dom/events.mjs index b906f5441..8ec36d03b 100644 --- a/application/source/dom/events.mjs +++ b/application/source/dom/events.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray, isObject} from "../types/is.mjs"; -import {validateInstance, validateString} from "../types/validate.mjs"; -import {getDocument} from "./util.mjs"; +import { isArray, isObject } from "../types/is.mjs"; +import { validateInstance, validateString } from "../types/validate.mjs"; +import { getDocument } from "./util.mjs"; -export {fireEvent, fireCustomEvent, findTargetElementFromEvent} +export { fireEvent, fireCustomEvent, findTargetElementFromEvent }; /** * The function sends an event @@ -25,12 +25,10 @@ export {fireEvent, fireCustomEvent, findTargetElementFromEvent} * @summary Construct and send and event */ function fireEvent(element, type) { - const document = getDocument(); if (element instanceof HTMLElement) { - - if (type === 'click') { + if (type === "click") { element.click(); return; } @@ -41,15 +39,13 @@ function fireEvent(element, type) { }); element.dispatchEvent(event); - } else if (element instanceof HTMLCollection || element instanceof NodeList) { for (let e of element) { fireEvent(e, type); } } else { - throw new TypeError('value is not an instance of HTMLElement or HTMLCollection') + throw new TypeError("value is not an instance of HTMLElement or HTMLCollection"); } - } /** @@ -66,38 +62,34 @@ function fireEvent(element, type) { * @summary Construct and send and event */ function fireCustomEvent(element, type, detail) { - const document = getDocument(); if (element instanceof HTMLElement) { - if (!isObject(detail)) { - detail = {detail}; + detail = { detail }; } let event = new CustomEvent(validateString(type), { bubbles: true, cancelable: true, - detail + detail, }); element.dispatchEvent(event); - } else if (element instanceof HTMLCollection || element instanceof NodeList) { for (let e of element) { fireCustomEvent(e, type, detail); } } else { - throw new TypeError('value is not an instance of HTMLElement or HTMLCollection') + throw new TypeError("value is not an instance of HTMLElement or HTMLCollection"); } - } /** * This function gets the path `Event.composedPath()` from an event and tries to find the next element * up the tree `element.closest()` with the attribute and value. If no value, or a value that is undefined or null, * is specified, only the attribute is searched. - * + * * @license AGPLv3 * @since 1.14.0 * @param {Event} event @@ -112,8 +104,8 @@ function fireCustomEvent(element, type, detail) { function findTargetElementFromEvent(event, attributeName, attributeValue) { validateInstance(event, Event); - if (typeof event.composedPath !== 'function') { - throw new Error('unsupported event'); + if (typeof event.composedPath !== "function") { + throw new Error("unsupported event"); } const path = event.composedPath(); @@ -123,14 +115,15 @@ function findTargetElementFromEvent(event, attributeName, attributeValue) { for (let i = 0; i < path.length; i++) { const o = path[i]; - if (o instanceof HTMLElement && - o.hasAttribute(attributeName) - && (attributeValue === undefined || o.getAttribute(attributeName) === attributeValue)) { + if ( + o instanceof HTMLElement && + o.hasAttribute(attributeName) && + (attributeValue === undefined || o.getAttribute(attributeName) === attributeValue) + ) { return o; } } } return undefined; - } diff --git a/application/source/dom/focusmanager.mjs b/application/source/dom/focusmanager.mjs index 0f438bde7..821150506 100644 --- a/application/source/dom/focusmanager.mjs +++ b/application/source/dom/focusmanager.mjs @@ -5,34 +5,32 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../data/extend.mjs"; -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {getGlobalObject} from "../types/global.mjs"; -import {isArray} from "../types/is.mjs"; -import {Stack} from "../types/stack.mjs"; -import {validateInstance, validateString} from "../types/validate.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {FocusManager} +import { extend } from "../data/extend.mjs"; +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { getGlobalObject } from "../types/global.mjs"; +import { isArray } from "../types/is.mjs"; +import { Stack } from "../types/stack.mjs"; +import { validateInstance, validateString } from "../types/validate.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { FocusManager }; /** * @private * @type {string} */ -const KEY_DOCUMENT = 'document'; +const KEY_DOCUMENT = "document"; /** * @private * @type {string} */ -const KEY_CONTEXT = 'context'; - +const KEY_CONTEXT = "context"; /** * @private * @type {Symbol} */ -const stackSymbol = Symbol('stack'); - +const stackSymbol = Symbol("stack"); /** * With the focusmanager the focus can be stored in a document, recalled and moved. @@ -44,8 +42,7 @@ const stackSymbol = Symbol('stack'); * @throws {Error} unsupported locale * @summary Handle the focus */ - class FocusManager extends BaseWithOptions { - +class FocusManager extends BaseWithOptions { /** * * @param {Object|undefined} options @@ -66,15 +63,14 @@ const stackSymbol = Symbol('stack'); return Symbol.for("@schukai/monster/dom/focusmanager"); } - /** * @property {HTMLDocument} document the document object into which the node is to be appended */ get defaults() { return extend({}, super.defaults, { - [KEY_DOCUMENT]: getGlobalObject('document'), + [KEY_DOCUMENT]: getGlobalObject("document"), [KEY_CONTEXT]: undefined, - }) + }); } /** @@ -84,10 +80,9 @@ const stackSymbol = Symbol('stack'); * @return {Monster.DOM.FocusManager} */ storeFocus() { - const active = this.getActive(); if (active instanceof Node) { - this[stackSymbol].push(active) + this[stackSymbol].push(active); } return this; } @@ -98,7 +93,6 @@ const stackSymbol = Symbol('stack'); * @return {Monster.DOM.FocusManager} */ restoreFocus() { - const last = this[stackSymbol].pop(); if (last instanceof Node) { this.focus(last); @@ -115,12 +109,11 @@ const stackSymbol = Symbol('stack'); * @return {Monster.DOM.FocusManager} */ focus(element, preventScroll) { - - validateInstance(element, Node) + validateInstance(element, Node); element.focus({ - preventScroll: preventScroll ?? false - }) + preventScroll: preventScroll ?? false, + }); return this; } @@ -141,32 +134,32 @@ const stackSymbol = Symbol('stack'); * @throws {TypeError} value is not an instance of */ getFocusable(query) { - let contextElement = this.getOption(KEY_CONTEXT); if (contextElement === undefined) { contextElement = this.getOption(KEY_DOCUMENT); } - validateInstance(contextElement, Node) + validateInstance(contextElement, Node); if (query !== undefined) { validateString(query); } - return [...contextElement.querySelectorAll( - 'details, button, input, [tabindex]:not([tabindex="-1"]), select, textarea, a[href], body' - )].filter((element) => { - + return [ + ...contextElement.querySelectorAll( + 'details, button, input, [tabindex]:not([tabindex="-1"]), select, textarea, a[href], body', + ), + ].filter((element) => { if (query !== undefined && !element.matches(query)) { return false; } - if (element.hasAttribute('disabled')) return false; - if (element.getAttribute("aria-hidden") === 'true') return false; + if (element.hasAttribute("disabled")) return false; + if (element.getAttribute("aria-hidden") === "true") return false; const rect = element.getBoundingClientRect(); - if(rect.width===0) return false; - if(rect.height===0) return false; + if (rect.width === 0) return false; + if (rect.height === 0) return false; return true; }); @@ -177,7 +170,6 @@ const stackSymbol = Symbol('stack'); * @return {Monster.DOM.FocusManager} */ focusNext(query) { - const current = this.getActive(); const focusable = this.getFocusable(query); @@ -194,7 +186,7 @@ const stackSymbol = Symbol('stack'); this.focus(focusable[0]); } } else { - this.focus(focusable[0]) + this.focus(focusable[0]); } return this; @@ -205,7 +197,6 @@ const stackSymbol = Symbol('stack'); * @return {Monster.DOM.FocusManager} */ focusPrev(query) { - const current = this.getActive(); const focusable = this.getFocusable(query); @@ -222,18 +213,9 @@ const stackSymbol = Symbol('stack'); this.focus(focusable[focusable.length - 1]); } } else { - this.focus(focusable[focusable.length - 1]) + this.focus(focusable[focusable.length - 1]); } return this; } - - } - - - - - - - diff --git a/application/source/dom/locale.mjs b/application/source/dom/locale.mjs index 27ab797d5..4ae3a856f 100644 --- a/application/source/dom/locale.mjs +++ b/application/source/dom/locale.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {parseLocale} from "../i18n/locale.mjs"; -import {getDocument} from "./util.mjs"; -import {getGlobalObject} from "../types/global.mjs"; +import { parseLocale } from "../i18n/locale.mjs"; +import { getDocument } from "./util.mjs"; +import { getGlobalObject } from "../types/global.mjs"; -export {getLocaleOfDocument} +export { getLocaleOfDocument }; /** * @private * @type {string} */ -const DEFAULT_LANGUAGE = 'en'; +const DEFAULT_LANGUAGE = "en"; /** * With this function you can read the language version set by the document. @@ -36,17 +36,16 @@ const DEFAULT_LANGUAGE = 'en'; * @summary Tries to determine the locale used */ function getLocaleOfDocument() { - const document = getDocument(); - let html = document.querySelector('html') - if (html instanceof HTMLElement && html.hasAttribute('lang')) { - let locale = html.getAttribute('lang'); + let html = document.querySelector("html"); + if (html instanceof HTMLElement && html.hasAttribute("lang")) { + let locale = html.getAttribute("lang"); if (locale) { - return new parseLocale(locale) + return new parseLocale(locale); } } - + let navigatorLanguage = getNavigatorLanguage(); if (navigatorLanguage) { return parseLocale(navigatorLanguage); @@ -62,24 +61,22 @@ function getLocaleOfDocument() { * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages */ const getNavigatorLanguage = () => { - const navigator = getGlobalObject('navigator'); + const navigator = getGlobalObject("navigator"); if (navigator === undefined) { return undefined; } - if (navigator.hasOwnProperty('language')) { + if (navigator.hasOwnProperty("language")) { const language = navigator.language; - if (typeof language === 'string' && language.length > 0) { + if (typeof language === "string" && language.length > 0) { return language; } - } const languages = navigator?.languages; - if (Array.isArray(languages) && languages.length>0) { + if (Array.isArray(languages) && languages.length > 0) { return languages[0]; } - - return undefined; -} + return undefined; +}; diff --git a/application/source/dom/namespace.mjs b/application/source/dom/namespace.mjs index d80cd0fb1..898b81f5b 100644 --- a/application/source/dom/namespace.mjs +++ b/application/source/dom/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/dom/ready.mjs b/application/source/dom/ready.mjs index 8e2680513..0591e3edd 100644 --- a/application/source/dom/ready.mjs +++ b/application/source/dom/ready.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getDocument, getWindow} from "./util.mjs"; +import { getDocument, getWindow } from "./util.mjs"; -export {domReady, windowReady} +export { domReady, windowReady }; /** * This variable is a promise that is fulfilled as soon as the dom is available. @@ -28,18 +28,16 @@ export {domReady, windowReady} * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState */ -const domReady = new Promise(resolve => { - +const domReady = new Promise((resolve) => { const document = getDocument(); if (document.readyState === "loading") { - document.addEventListener('DOMContentLoaded', resolve); + document.addEventListener("DOMContentLoaded", resolve); } else { resolve(); } }); - /** * This variable is a promise that is fulfilled as soon as the windows is available. * @@ -55,14 +53,13 @@ const domReady = new Promise(resolve => { * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState */ -const windowReady = new Promise(resolve => { - +const windowReady = new Promise((resolve) => { const document = getDocument(); const window = getWindow(); - if (document.readyState === 'complete') { + if (document.readyState === "complete") { resolve(); } else { - window.addEventListener('load', resolve); + window.addEventListener("load", resolve); } }); diff --git a/application/source/dom/resource.mjs b/application/source/dom/resource.mjs index de77c8318..60729dfe8 100644 --- a/application/source/dom/resource.mjs +++ b/application/source/dom/resource.mjs @@ -5,42 +5,42 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalStateSymbol, internalSymbol,} from "../constants.mjs"; -import {extend} from "../data/extend.mjs"; -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {getGlobalObject} from "../types/global.mjs"; -import {ID} from "../types/id.mjs"; -import {isString} from "../types/is.mjs"; -import {Observer} from "../types/observer.mjs"; -import {ProxyObserver} from "../types/proxyobserver.mjs"; -import {ATTRIBUTE_CLASS, ATTRIBUTE_ID, ATTRIBUTE_TITLE} from "./constants.mjs"; -import {instanceSymbol} from "../constants.mjs"; - -export {Resource, KEY_DOCUMENT, KEY_QUERY, referenceSymbol} +import { internalStateSymbol, internalSymbol } from "../constants.mjs"; +import { extend } from "../data/extend.mjs"; +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { getGlobalObject } from "../types/global.mjs"; +import { ID } from "../types/id.mjs"; +import { isString } from "../types/is.mjs"; +import { Observer } from "../types/observer.mjs"; +import { ProxyObserver } from "../types/proxyobserver.mjs"; +import { ATTRIBUTE_CLASS, ATTRIBUTE_ID, ATTRIBUTE_TITLE } from "./constants.mjs"; +import { instanceSymbol } from "../constants.mjs"; + +export { Resource, KEY_DOCUMENT, KEY_QUERY, referenceSymbol }; /** * @private * @type {string} */ -const KEY_DOCUMENT = 'document'; +const KEY_DOCUMENT = "document"; /** * @private * @type {string} */ -const KEY_QUERY = 'query'; +const KEY_QUERY = "query"; /** * @private * @type {string} */ -const KEY_TIMEOUT = 'timeout'; +const KEY_TIMEOUT = "timeout"; /** * @private * @type {symbol} */ -const referenceSymbol = Symbol('reference'); +const referenceSymbol = Symbol("reference"); /** * This class is the base class for all resources to be loaded. @@ -52,7 +52,6 @@ const referenceSymbol = Symbol('reference'); * @summary A Resource class */ class Resource extends BaseWithOptions { - /** * * @param {Object|undefined} options @@ -63,28 +62,26 @@ class Resource extends BaseWithOptions { let uri = this.getOption(this.constructor.getURLAttribute()); if (uri === undefined) { - throw new Error('missing source') + throw new Error("missing source"); } else if (uri instanceof URL) { uri = uri.toString(); } else if (!isString(uri)) { - throw new Error('unsupported url type') + throw new Error("unsupported url type"); } this[internalSymbol][this.constructor.getURLAttribute()] = uri; this[internalStateSymbol] = new ProxyObserver({ loaded: false, error: undefined, - }) + }); this[referenceSymbol] = undefined; - } /** * @return {boolean} */ isConnected() { - if (this[referenceSymbol] instanceof HTMLElement) { return this[referenceSymbol].isConnected; } @@ -111,7 +108,6 @@ class Resource extends BaseWithOptions { * @return {Monster.DOM.Resource} */ connect() { - if (!(this[referenceSymbol] instanceof HTMLElement)) { this.create(); } @@ -132,13 +128,13 @@ class Resource extends BaseWithOptions { get defaults() { return extend({}, super.defaults, { [this.constructor.getURLAttribute()]: undefined, - [KEY_DOCUMENT]: getGlobalObject('document'), - [KEY_QUERY]: 'head', + [KEY_DOCUMENT]: getGlobalObject("document"), + [KEY_QUERY]: "head", [KEY_TIMEOUT]: 10000, - [ATTRIBUTE_ID]: (new ID('resource')).toString(), + [ATTRIBUTE_ID]: new ID("resource").toString(), [ATTRIBUTE_CLASS]: undefined, - [ATTRIBUTE_TITLE]: undefined - }) + [ATTRIBUTE_TITLE]: undefined, + }); } /** @@ -150,40 +146,35 @@ class Resource extends BaseWithOptions { available() { const self = this; if (!(self[referenceSymbol] instanceof HTMLElement)) { - return Promise.reject('no element') + return Promise.reject("no element"); } if (!self.isConnected()) { - return Promise.reject('element not connected') + return Promise.reject("element not connected"); } - if (self[internalStateSymbol].getSubject()['loaded'] === true) { - - if (self[internalStateSymbol].getSubject()['error'] !== undefined) { - return Promise.reject(self[internalStateSymbol].getSubject()['error']); + if (self[internalStateSymbol].getSubject()["loaded"] === true) { + if (self[internalStateSymbol].getSubject()["error"] !== undefined) { + return Promise.reject(self[internalStateSymbol].getSubject()["error"]); } return Promise.resolve(); - } return new Promise(function (resolve, reject) { - const timeout = setTimeout(() => { - reject('timeout'); - }, self.getOption('timeout')) + reject("timeout"); + }, self.getOption("timeout")); const observer = new Observer(() => { clearTimeout(timeout); self[internalStateSymbol].detachObserver(observer); resolve(); - }) + }); self[internalStateSymbol].attachObserver(observer); - }); - - }; + } /** * @return {string} @@ -191,17 +182,15 @@ class Resource extends BaseWithOptions { static getURLAttribute() { throw new Error("this method must be implemented by derived classes"); } - + /** * @return {symbol} */ static get [instanceSymbol]() { return Symbol.for("@schukai/monster/dom/resource"); } - } - /** * @private * @return {Promise} @@ -210,9 +199,9 @@ class Resource extends BaseWithOptions { function appendToDocument() { const self = this; - const targetNode = document.querySelector(self.getOption(KEY_QUERY, 'head')) + const targetNode = document.querySelector(self.getOption(KEY_QUERY, "head")); if (!(targetNode instanceof HTMLElement)) { - throw new Error('target not found') + throw new Error("target not found"); } addEvents.call(self); @@ -229,28 +218,26 @@ function addEvents() { const self = this; const onError = () => { - - self[referenceSymbol].removeEventListener('error', onError); - self[referenceSymbol].removeEventListener('load', onLoad); + self[referenceSymbol].removeEventListener("error", onError); + self[referenceSymbol].removeEventListener("load", onLoad); self[internalStateSymbol].setSubject({ loaded: true, error: `${self[referenceSymbol][self.constructor.getURLAttribute()]} is not available`, - }) + }); return; - } + }; const onLoad = () => { - self[referenceSymbol].removeEventListener('error', onError); - self[referenceSymbol].removeEventListener('load', onLoad); - self[internalStateSymbol].getSubject()['loaded'] = true; + self[referenceSymbol].removeEventListener("error", onError); + self[referenceSymbol].removeEventListener("load", onLoad); + self[internalStateSymbol].getSubject()["loaded"] = true; return; - } + }; - self[referenceSymbol].addEventListener('load', onLoad, false); - self[referenceSymbol].addEventListener('error', onError, false); + self[referenceSymbol].addEventListener("load", onLoad, false); + self[referenceSymbol].addEventListener("error", onError, false); return self; - } diff --git a/application/source/dom/resource/data.mjs b/application/source/dom/resource/data.mjs index f814ce8d9..eec34947d 100644 --- a/application/source/dom/resource/data.mjs +++ b/application/source/dom/resource/data.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalStateSymbol} from "../../constants.mjs"; -import {extend} from "../../data/extend.mjs"; -import {getGlobalFunction} from "../../types/global.mjs"; +import { internalStateSymbol } from "../../constants.mjs"; +import { extend } from "../../data/extend.mjs"; +import { getGlobalFunction } from "../../types/global.mjs"; import { ATTRIBUTE_CLASS, ATTRIBUTE_ERRORMESSAGE, @@ -15,11 +15,11 @@ import { ATTRIBUTE_SRC, ATTRIBUTE_TITLE, ATTRIBUTE_TYPE, - TAG_SCRIPT + TAG_SCRIPT, } from "../constants.mjs"; -import {KEY_DOCUMENT, KEY_QUERY, referenceSymbol, Resource} from "../resource.mjs"; -import {instanceSymbol} from '../../constants.mjs'; -export {Data} +import { KEY_DOCUMENT, KEY_QUERY, referenceSymbol, Resource } from "../resource.mjs"; +import { instanceSymbol } from "../../constants.mjs"; +export { Data }; /** * This class is used by the resource manager to embed data. @@ -31,7 +31,6 @@ export {Data} * @summary A Data Resource class */ class Data extends Resource { - /** * @property {string} mode=cors https://developer.mozilla.org/en-US/docs/Web/API/fetch * @property {string} credentials=same-origin https://developer.mozilla.org/en-US/docs/Web/API/fetch @@ -39,10 +38,10 @@ class Data extends Resource { */ get defaults() { return extend({}, super.defaults, { - mode: 'cors', - credentials: 'same-origin', - type: 'application/json', - }) + mode: "cors", + credentials: "same-origin", + type: "application/json", + }); } /** @@ -61,7 +60,6 @@ class Data extends Resource { * @return {Monster.DOM.Resource} */ connect() { - if (!(this[referenceSymbol] instanceof HTMLElement)) { this.create(); } @@ -79,14 +77,12 @@ class Data extends Resource { return Symbol.for("@schukai/monster/dom/resource/data"); } - /** * @return {string} */ static getURLAttribute() { - return ATTRIBUTE_SRC + return ATTRIBUTE_SRC; } - } /** @@ -108,7 +104,6 @@ function createElement() { return self; } - /** * @private * @return {Promise} @@ -117,44 +112,41 @@ function createElement() { function appendToDocument() { const self = this; - const targetNode = document.querySelector(self.getOption(KEY_QUERY, 'head')) + const targetNode = document.querySelector(self.getOption(KEY_QUERY, "head")); if (!(targetNode instanceof HTMLElement)) { - throw new Error('target not found') + throw new Error("target not found"); } targetNode.appendChild(self[referenceSymbol]); - getGlobalFunction('fetch')(self.getOption(ATTRIBUTE_SRC), { - method: 'GET', // *GET, POST, PUT, DELETE, etc. - mode: self.getOption('mode', 'cors'), // no-cors, *cors, same-origin - cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached - credentials: self.getOption('credentials', 'same-origin'), // include, *same-origin, omit + getGlobalFunction("fetch")(self.getOption(ATTRIBUTE_SRC), { + method: "GET", // *GET, POST, PUT, DELETE, etc. + mode: self.getOption("mode", "cors"), // no-cors, *cors, same-origin + cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached + credentials: self.getOption("credentials", "same-origin"), // include, *same-origin, omit headers: { - 'Accept': self.getOption('type', 'application/json') + Accept: self.getOption("type", "application/json"), }, - redirect: 'follow', // manual, *follow, error - referrerPolicy: 'no-referrer', // no-referrer, - }).then(response => { - - return response.text() - - - }).then(text => { - - const textNode = document.createTextNode(text); - self[referenceSymbol].appendChild(textNode); - - self[internalStateSymbol].getSubject()['loaded'] = true; - - - }).catch(e => { - self[internalStateSymbol].setSubject({ - loaded: true, - error: e.toString(), + redirect: "follow", // manual, *follow, error + referrerPolicy: "no-referrer", // no-referrer, + }) + .then((response) => { + return response.text(); }) + .then((text) => { + const textNode = document.createTextNode(text); + self[referenceSymbol].appendChild(textNode); - targetNode.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.toString()); - }) + self[internalStateSymbol].getSubject()["loaded"] = true; + }) + .catch((e) => { + self[internalStateSymbol].setSubject({ + loaded: true, + error: e.toString(), + }); + + targetNode.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.toString()); + }); return self; } diff --git a/application/source/dom/resource/link.mjs b/application/source/dom/resource/link.mjs index 590503e13..3cdb6c9b7 100644 --- a/application/source/dom/resource/link.mjs +++ b/application/source/dom/resource/link.mjs @@ -5,18 +5,20 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../../data/extend.mjs"; +import { extend } from "../../data/extend.mjs"; import { ATTRIBUTE_CLASS, ATTRIBUTE_HREF, ATTRIBUTE_ID, - ATTRIBUTE_NONCE, ATTRIBUTE_SRC, - ATTRIBUTE_TITLE, ATTRIBUTE_TYPE, - TAG_LINK + ATTRIBUTE_NONCE, + ATTRIBUTE_SRC, + ATTRIBUTE_TITLE, + ATTRIBUTE_TYPE, + TAG_LINK, } from "../constants.mjs"; -import {KEY_DOCUMENT, referenceSymbol, Resource} from "../resource.mjs"; -import {instanceSymbol} from '../../constants.mjs'; -export {Link} +import { KEY_DOCUMENT, referenceSymbol, Resource } from "../resource.mjs"; +import { instanceSymbol } from "../../constants.mjs"; +export { Link }; /** * This class is used by the resource manager to embed external resources. @@ -29,7 +31,6 @@ export {Link} * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link */ class Link extends Resource { - /** * @property {string} as {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-as} * @property {string} crossOrigin=anonymous {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin} @@ -50,7 +51,7 @@ class Link extends Resource { get defaults() { return extend({}, super.defaults, { as: undefined, - crossOrigin: 'anonymous', + crossOrigin: "anonymous", disabled: undefined, href: undefined, hreflang: undefined, @@ -63,8 +64,8 @@ class Link extends Resource { rel: undefined, sizes: undefined, type: undefined, - nonce: undefined - }) + nonce: undefined, + }); } /** @@ -76,7 +77,6 @@ class Link extends Resource { return Symbol.for("@schukai/monster/dom/resource/link"); } - /** * * @return {Monster.DOM.Resource.Link} @@ -90,9 +90,8 @@ class Link extends Resource { * @return {string} */ static getURLAttribute() { - return ATTRIBUTE_HREF + return ATTRIBUTE_HREF; } - } /** @@ -105,11 +104,31 @@ function createElement() { const document = self.getOption(KEY_DOCUMENT); self[referenceSymbol] = document.createElement(TAG_LINK); - for (let key of ['as','crossOrigin','disabled','href','hreflang','imagesizes','imagesrcset','integrity','media','prefetch','referrerpolicy','sizes','rel','type',ATTRIBUTE_HREF,ATTRIBUTE_ID,ATTRIBUTE_CLASS,ATTRIBUTE_TITLE,ATTRIBUTE_NONCE]) { + for (let key of [ + "as", + "crossOrigin", + "disabled", + "href", + "hreflang", + "imagesizes", + "imagesrcset", + "integrity", + "media", + "prefetch", + "referrerpolicy", + "sizes", + "rel", + "type", + ATTRIBUTE_HREF, + ATTRIBUTE_ID, + ATTRIBUTE_CLASS, + ATTRIBUTE_TITLE, + ATTRIBUTE_NONCE, + ]) { if (self.getOption(key) !== undefined) { self[referenceSymbol][key] = self.getOption(key); } - } - + } + return self; } diff --git a/application/source/dom/resource/link/namespace.mjs b/application/source/dom/resource/link/namespace.mjs index 5905af06f..22e6dedd0 100644 --- a/application/source/dom/resource/link/namespace.mjs +++ b/application/source/dom/resource/link/namespace.mjs @@ -3,8 +3,6 @@ * SPDX-License-Identifier: AGPL-3.0 */ - - /** * In this namespace you will find classes and methods for links * @@ -12,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/dom/resource/link/stylesheet.mjs b/application/source/dom/resource/link/stylesheet.mjs index 46487d4e5..54a239378 100644 --- a/application/source/dom/resource/link/stylesheet.mjs +++ b/application/source/dom/resource/link/stylesheet.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../../../data/extend.mjs"; -import {Link} from "../link.mjs"; -import {instanceSymbol} from '../../../constants.mjs'; -export {Stylesheet} +import { extend } from "../../../data/extend.mjs"; +import { Link } from "../link.mjs"; +import { instanceSymbol } from "../../../constants.mjs"; +export { Stylesheet }; /** * This class is used by the resource manager to embed external resources. @@ -21,14 +21,13 @@ export {Stylesheet} * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link */ class Stylesheet extends Link { - /** * @property {string} rel {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link#attr-rel} */ get defaults() { return extend({}, super.defaults, { - rel: 'stylesheet' - }) + rel: "stylesheet", + }); } /** @@ -37,9 +36,6 @@ class Stylesheet extends Link { * @since 2.1.0 */ static get [instanceSymbol]() { - return Symbol.for("@schukai/monster/dom/resource/link/stylesheet") + return Symbol.for("@schukai/monster/dom/resource/link/stylesheet"); } - - } - diff --git a/application/source/dom/resource/namespace.mjs b/application/source/dom/resource/namespace.mjs index ff1964231..6cd37991f 100644 --- a/application/source/dom/resource/namespace.mjs +++ b/application/source/dom/resource/namespace.mjs @@ -4,7 +4,7 @@ */ /** - * In this namespace you will find classes and methods for handling resources. + * In this namespace you will find classes and methods for handling resources. * * @namespace Monster.DOM.Resource * @memberOf Monster diff --git a/application/source/dom/resource/script.mjs b/application/source/dom/resource/script.mjs index 79443d890..6310341b7 100644 --- a/application/source/dom/resource/script.mjs +++ b/application/source/dom/resource/script.mjs @@ -5,7 +5,7 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../../data/extend.mjs"; +import { extend } from "../../data/extend.mjs"; import { ATTRIBUTE_CLASS, ATTRIBUTE_ID, @@ -13,11 +13,11 @@ import { ATTRIBUTE_SRC, ATTRIBUTE_TITLE, ATTRIBUTE_TYPE, - TAG_SCRIPT + TAG_SCRIPT, } from "../constants.mjs"; -import {KEY_DOCUMENT, referenceSymbol, Resource} from "../resource.mjs"; -import {instanceSymbol} from '../../constants.mjs'; -export {Script} +import { KEY_DOCUMENT, referenceSymbol, Resource } from "../resource.mjs"; +import { instanceSymbol } from "../../constants.mjs"; +export { Script }; /** * This class is used by the resource manager to embed scripts. @@ -29,7 +29,6 @@ export {Script} * @summary A Resource class */ class Script extends Resource { - /** * @property {boolean} async=true {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-async} * @property {string} crossOrigin=anonymous {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-crossorigin} @@ -43,14 +42,14 @@ class Script extends Resource { get defaults() { return extend({}, super.defaults, { async: true, - crossOrigin: 'anonymous', + crossOrigin: "anonymous", defer: false, integrity: undefined, nomodule: false, nonce: undefined, referrerpolicy: undefined, - type: 'text/javascript', - }) + type: "text/javascript", + }); } /** @@ -75,9 +74,8 @@ class Script extends Resource { * @return {string} */ static getURLAttribute() { - return ATTRIBUTE_SRC + return ATTRIBUTE_SRC; } - } /** @@ -90,12 +88,24 @@ function createElement() { const document = self.getOption(KEY_DOCUMENT); self[referenceSymbol] = document.createElement(TAG_SCRIPT); - for (let key of ['crossOrigin', 'defer', 'async', 'integrity', 'nomodule', ATTRIBUTE_NONCE, 'referrerpolicy', ATTRIBUTE_TYPE, ATTRIBUTE_SRC, ATTRIBUTE_ID, ATTRIBUTE_CLASS, ATTRIBUTE_TITLE]) { + for (let key of [ + "crossOrigin", + "defer", + "async", + "integrity", + "nomodule", + ATTRIBUTE_NONCE, + "referrerpolicy", + ATTRIBUTE_TYPE, + ATTRIBUTE_SRC, + ATTRIBUTE_ID, + ATTRIBUTE_CLASS, + ATTRIBUTE_TITLE, + ]) { if (self.getOption(key) !== undefined) { self[referenceSymbol][key] = self.getOption(key); } } - return self; } diff --git a/application/source/dom/resourcemanager.mjs b/application/source/dom/resourcemanager.mjs index cb05a63c5..cc4d9d15c 100644 --- a/application/source/dom/resourcemanager.mjs +++ b/application/source/dom/resourcemanager.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {extend} from "../data/extend.mjs"; -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {getGlobalObject} from "../types/global.mjs"; -import {isArray} from "../types/is.mjs"; -import {ATTRIBUTE_HREF, ATTRIBUTE_SRC} from "./constants.mjs"; -import {Resource} from "./resource.mjs"; -import {Data} from "./resource/data.mjs"; -import {Stylesheet} from "./resource/link/stylesheet.mjs"; -import {Script} from "./resource/script.mjs"; - -export {ResourceManager} +import { extend } from "../data/extend.mjs"; +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { getGlobalObject } from "../types/global.mjs"; +import { isArray } from "../types/is.mjs"; +import { ATTRIBUTE_HREF, ATTRIBUTE_SRC } from "./constants.mjs"; +import { Resource } from "./resource.mjs"; +import { Data } from "./resource/data.mjs"; +import { Stylesheet } from "./resource/link/stylesheet.mjs"; +import { Script } from "./resource/script.mjs"; + +export { ResourceManager }; /** * The ResourceManager is a singleton that manages all resources. @@ -26,8 +26,7 @@ export {ResourceManager} * @memberOf Monster.DOM * @summary A Resource class */ - class ResourceManager extends BaseWithOptions { - +class ResourceManager extends BaseWithOptions { /** * * @param {Object} options @@ -36,18 +35,16 @@ export {ResourceManager} constructor(options) { super(options); - if (!(this.getOption('document') instanceof Document)) { - throw new Error('unsupported document type') + if (!(this.getOption("document") instanceof Document)) { + throw new Error("unsupported document type"); } - - } /** * @property {string} baseurl */ getBaseURL() { - this.getOption('document')?.baseURL; + this.getOption("document")?.baseURL; } /** @@ -60,13 +57,13 @@ export {ResourceManager} */ get defaults() { return Object.assign({}, super.defaults, { - document: getGlobalObject('document'), + document: getGlobalObject("document"), resources: { scripts: [], stylesheets: [], - data: [] - } - }) + data: [], + }, + }); } /** @@ -76,7 +73,7 @@ export {ResourceManager} * @throws {Error} unsupported resource definition */ connect() { - runResourceMethod.call(this, 'connect'); + runResourceMethod.call(this, "connect"); return this; } @@ -87,7 +84,7 @@ export {ResourceManager} * @throws {Error} unsupported resource definition */ available() { - return Promise.all(runResourceMethod.call(this, 'available')); + return Promise.all(runResourceMethod.call(this, "available")); } /** @@ -99,10 +96,9 @@ export {ResourceManager} * @see Monster.DOM.Resource.Script */ addScript(url, options) { - return addResource.call(this, 'scripts', url, options); + return addResource.call(this, "scripts", url, options); } - /** * Add Stylesheet * @@ -112,7 +108,7 @@ export {ResourceManager} * @see Monster.DOM.Resource.Link.Stylesheet */ addStylesheet(url, options) { - return addResource.call(this, 'stylesheets', url, options); + return addResource.call(this, "stylesheets", url, options); } /** @@ -124,10 +120,8 @@ export {ResourceManager} * @see Monster.DOM.Resource.Data */ addData(url, options) { - return addResource.call(this, 'data', url, options); + return addResource.call(this, "data", url, options); } - - } /** @@ -140,7 +134,7 @@ function runResourceMethod(method) { const result = []; - for (const type of ['scripts', 'stylesheets', 'data']) { + for (const type of ["scripts", "stylesheets", "data"]) { const resources = self.getOption(`resources.${type}`); if (!isArray(resources)) { continue; @@ -148,12 +142,11 @@ function runResourceMethod(method) { for (const resource of resources) { if (!(resource instanceof Resource)) { - throw new Error('unsupported resource definition') + throw new Error("unsupported resource definition"); } result.push(resource[method]()); } - } return result; @@ -174,23 +167,23 @@ function addResource(type, url, options) { url = url.toString(); } - options = options || {} + options = options || {}; let resource; switch (type) { - case 'scripts': - resource = new Script(extend({}, options, {[ATTRIBUTE_SRC]: url})) + case "scripts": + resource = new Script(extend({}, options, { [ATTRIBUTE_SRC]: url })); break; - case 'stylesheets': - resource = new Stylesheet(extend({}, options, {[ATTRIBUTE_HREF]: url})) + case "stylesheets": + resource = new Stylesheet(extend({}, options, { [ATTRIBUTE_HREF]: url })); break; - case 'data': - resource = new Data(extend({}, options, {[ATTRIBUTE_SRC]: url})) + case "data": + resource = new Data(extend({}, options, { [ATTRIBUTE_SRC]: url })); break; default: - throw new Error(`unsupported type ${type}`) + throw new Error(`unsupported type ${type}`); } - (self.getOption('resources')?.[type]).push(resource); + self.getOption("resources")?.[type].push(resource); return self; } diff --git a/application/source/dom/template.mjs b/application/source/dom/template.mjs index a5c482755..7db963dd5 100644 --- a/application/source/dom/template.mjs +++ b/application/source/dom/template.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {getGlobalFunction, getGlobalObject} from '../types/global.mjs'; -import {validateInstance, validateString} from "../types/validate.mjs"; -import {ATTRIBUTE_TEMPLATE_PREFIX} from "./constants.mjs"; -import {getDocumentTheme} from "./theme.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {Template} +import { Base } from "../types/base.mjs"; +import { getGlobalFunction, getGlobalObject } from "../types/global.mjs"; +import { validateInstance, validateString } from "../types/validate.mjs"; +import { ATTRIBUTE_TEMPLATE_PREFIX } from "./constants.mjs"; +import { getDocumentTheme } from "./theme.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Template }; /** * The template class provides methods for creating templates. @@ -32,7 +32,7 @@ class Template extends Base { */ constructor(template) { super(); - const HTMLTemplateElement = getGlobalFunction('HTMLTemplateElement'); + const HTMLTemplateElement = getGlobalFunction("HTMLTemplateElement"); validateInstance(template, HTMLTemplateElement); this.template = template; } @@ -46,7 +46,6 @@ class Template extends Base { return Symbol.for("@schukai/monster/dom/resource/template"); } - /** * * @returns {HTMLTemplateElement} @@ -63,7 +62,6 @@ class Template extends Base { createDocumentFragment() { return this.template.content.cloneNode(true); } - } /** @@ -132,20 +130,17 @@ class Template extends Base { export function findDocumentTemplate(id, currentNode) { validateString(id); - const document = getGlobalObject('document'); - const HTMLTemplateElement = getGlobalFunction('HTMLTemplateElement'); - const DocumentFragment = getGlobalFunction('DocumentFragment'); - const Document = getGlobalFunction('Document'); - + const document = getGlobalObject("document"); + const HTMLTemplateElement = getGlobalFunction("HTMLTemplateElement"); + const DocumentFragment = getGlobalFunction("DocumentFragment"); + const Document = getGlobalFunction("Document"); let prefixID; if (!(currentNode instanceof Document || currentNode instanceof DocumentFragment)) { - if (currentNode instanceof Node) { - if (currentNode.hasAttribute(ATTRIBUTE_TEMPLATE_PREFIX)) { - prefixID = currentNode.getAttribute(ATTRIBUTE_TEMPLATE_PREFIX) + prefixID = currentNode.getAttribute(ATTRIBUTE_TEMPLATE_PREFIX); } currentNode = currentNode.getRootNode(); @@ -153,7 +148,6 @@ export function findDocumentTemplate(id, currentNode) { if (!(currentNode instanceof Document || currentNode instanceof DocumentFragment)) { currentNode = currentNode.ownerDocument; } - } if (!(currentNode instanceof Document || currentNode instanceof DocumentFragment)) { @@ -162,7 +156,7 @@ export function findDocumentTemplate(id, currentNode) { } let template; - let theme = getDocumentTheme() + let theme = getDocumentTheme(); if (prefixID) { let themedPrefixID = `${prefixID}-${id}-${theme.getName()}`; @@ -206,6 +200,5 @@ export function findDocumentTemplate(id, currentNode) { return new Template(template); } - throw new Error(`template ${id} not found.`) + throw new Error(`template ${id} not found.`); } - diff --git a/application/source/dom/theme.mjs b/application/source/dom/theme.mjs index 8fc71ba87..c166f383f 100644 --- a/application/source/dom/theme.mjs +++ b/application/source/dom/theme.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {getGlobalObject} from '../types/global.mjs'; -import {validateString} from "../types/validate.mjs"; -import {ATTRIBUTE_THEME_NAME, DEFAULT_THEME} from "./constants.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {Theme, getDocumentTheme} +import { Base } from "../types/base.mjs"; +import { getGlobalObject } from "../types/global.mjs"; +import { validateString } from "../types/validate.mjs"; +import { ATTRIBUTE_THEME_NAME, DEFAULT_THEME } from "./constants.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Theme, getDocumentTheme }; /** * The Theme class provides the functionality for the theme. @@ -23,7 +23,6 @@ export {Theme, getDocumentTheme} * @summary A theme class */ class Theme extends Base { - /** * * @param name @@ -44,7 +43,6 @@ class Theme extends Base { return Symbol.for("@schukai/monster/dom/theme"); } - /** * * @returns {string} @@ -52,7 +50,6 @@ class Theme extends Base { getName() { return this.name; } - } /** @@ -73,10 +70,10 @@ class Theme extends Base { * @since 1.7.0 */ function getDocumentTheme() { - let document = getGlobalObject('document'); + let document = getGlobalObject("document"); let name = DEFAULT_THEME; - let element = document.querySelector('html'); + let element = document.querySelector("html"); if (element instanceof HTMLElement) { let theme = element.getAttribute(ATTRIBUTE_THEME_NAME); if (theme) { @@ -85,5 +82,4 @@ function getDocumentTheme() { } return new Theme(name); - } diff --git a/application/source/dom/updater.mjs b/application/source/dom/updater.mjs index 364c8eea5..0b50ee5e4 100644 --- a/application/source/dom/updater.mjs +++ b/application/source/dom/updater.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {diff} from "../data/diff.mjs"; -import {Pathfinder} from "../data/pathfinder.mjs"; -import {Pipe} from "../data/pipe.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { diff } from "../data/diff.mjs"; +import { Pathfinder } from "../data/pathfinder.mjs"; +import { Pipe } from "../data/pipe.mjs"; import { ATTRIBUTE_ERRORMESSAGE, ATTRIBUTE_UPDATER_ATTRIBUTES, @@ -17,22 +17,23 @@ import { ATTRIBUTE_UPDATER_INSERT_REFERENCE, ATTRIBUTE_UPDATER_REMOVE, ATTRIBUTE_UPDATER_REPLACE, - ATTRIBUTE_UPDATER_SELECT_THIS, customElementUpdaterLinkSymbol + ATTRIBUTE_UPDATER_SELECT_THIS, + customElementUpdaterLinkSymbol, } from "../dom/constants.mjs"; -import {Base} from "../types/base.mjs"; -import {isArray, isInstance, isIterable} from "../types/is.mjs"; -import {Observer} from "../types/observer.mjs"; -import {ProxyObserver} from "../types/proxyobserver.mjs"; -import {validateArray, validateInstance} from "../types/validate.mjs"; -import {clone} from "../util/clone.mjs"; -import {trimSpaces} from "../util/trimspaces.mjs"; -import {addToObjectLink} from "./attributes.mjs"; -import {findTargetElementFromEvent} from "./events.mjs"; -import {findDocumentTemplate} from "./template.mjs"; -import {getDocument} from "./util.mjs"; +import { Base } from "../types/base.mjs"; +import { isArray, isInstance, isIterable } from "../types/is.mjs"; +import { Observer } from "../types/observer.mjs"; +import { ProxyObserver } from "../types/proxyobserver.mjs"; +import { validateArray, validateInstance } from "../types/validate.mjs"; +import { clone } from "../util/clone.mjs"; +import { trimSpaces } from "../util/trimspaces.mjs"; +import { addToObjectLink } from "./attributes.mjs"; +import { findTargetElementFromEvent } from "./events.mjs"; +import { findDocumentTemplate } from "./template.mjs"; +import { getDocument } from "./util.mjs"; -export {Updater, addObjectWithUpdaterToElement} +export { Updater, addObjectWithUpdaterToElement }; /** * The updater class connects an object with the dom. In this way, structures and contents in the DOM can be programmatically adapted via attributes. @@ -57,7 +58,6 @@ export {Updater, addObjectWithUpdaterToElement} * @summary The updater class connects an object with the dom */ class Updater extends Base { - /** * @since 1.8.0 * @param {HTMLElement} element @@ -72,7 +72,7 @@ class Updater extends Base { /** * @type {HTMLElement} */ - if (subject === undefined) subject = {} + if (subject === undefined) subject = {}; if (!isInstance(subject, ProxyObserver)) { subject = new ProxyObserver(subject); } @@ -81,27 +81,27 @@ class Updater extends Base { element: validateInstance(element, HTMLElement), last: {}, callbacks: new Map(), - eventTypes: ['keyup', 'click', 'change', 'drop', 'touchend', 'input'], - subject: subject - } - - this[internalSymbol].callbacks.set('checkstate', getCheckStateCallback.call(this)); - - this[internalSymbol].subject.attachObserver(new Observer(() => { + eventTypes: ["keyup", "click", "change", "drop", "touchend", "input"], + subject: subject, + }; - const s = this[internalSymbol].subject.getRealSubject(); + this[internalSymbol].callbacks.set("checkstate", getCheckStateCallback.call(this)); - const diffResult = diff(this[internalSymbol].last, s) - this[internalSymbol].last = clone(s); + this[internalSymbol].subject.attachObserver( + new Observer(() => { + const s = this[internalSymbol].subject.getRealSubject(); - for (const [, change] of Object.entries(diffResult)) { - removeElement.call(this, change); - insertElement.call(this, change); - updateContent.call(this, change); - updateAttributes.call(this, change); - } - })); + const diffResult = diff(this[internalSymbol].last, s); + this[internalSymbol].last = clone(s); + for (const [, change] of Object.entries(diffResult)) { + removeElement.call(this, change); + insertElement.call(this, change); + updateContent.call(this, change); + updateAttributes.call(this, change); + } + }), + ); } /** @@ -137,12 +137,11 @@ class Updater extends Base { // @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener this[internalSymbol].element.addEventListener(type, getControlEventHandler.call(this), { capture: true, - passive: true + passive: true, }); } return this; - } /** @@ -152,13 +151,11 @@ class Updater extends Base { * @return {Updater} */ disableEventProcessing() { - for (const type of this[internalSymbol].eventTypes) { this[internalSymbol].element.removeEventListener(type, getControlEventHandler.call(this)); } return this; - } /** @@ -175,9 +172,9 @@ class Updater extends Base { * @return {Promise} */ run() { - // the key __init__has no further meaning and is only + // the key __init__has no further meaning and is only // used to create the diff for empty objects. - this[internalSymbol].last = {'__init__': true}; + this[internalSymbol].last = { __init__: true }; return this[internalSymbol].subject.notifyObservers(); } @@ -219,7 +216,6 @@ class Updater extends Base { this[internalSymbol].callbacks.set(name, callback); return this; } - } /** @@ -233,27 +229,25 @@ function getCheckStateCallback() { const self = this; return function (current) { - // this is a reference to the current object (therefore no array function here) if (this instanceof HTMLInputElement) { - if (['radio', 'checkbox'].indexOf(this.type) !== -1) { - return (`${this.value}` === `${current}`) ? 'true' : undefined + if (["radio", "checkbox"].indexOf(this.type) !== -1) { + return `${this.value}` === `${current}` ? "true" : undefined; } } else if (this instanceof HTMLOptionElement) { - if (isArray(current) && current.indexOf(this.value) !== -1) { - return 'true' + return "true"; } return undefined; } - } + }; } /** * @private */ -const symbol = Symbol('@schukai/monster/updater@@EventHandler'); +const symbol = Symbol("@schukai/monster/updater@@EventHandler"); /** * @private @@ -262,7 +256,6 @@ const symbol = Symbol('@schukai/monster/updater@@EventHandler'); * @throws {Error} the bind argument must start as a value with a path */ function getControlEventHandler() { - const self = this; if (self[symbol]) { @@ -282,12 +275,9 @@ function getControlEventHandler() { } retrieveAndSetValue.call(self, element); - - } + }; return self[symbol]; - - } /** @@ -298,15 +288,14 @@ function getControlEventHandler() { * @private */ function retrieveAndSetValue(element) { - const self = this; const pathfinder = new Pathfinder(self[internalSymbol].subject.getSubject()); let path = element.getAttribute(ATTRIBUTE_UPDATER_BIND); - if (path.indexOf('path:') !== 0) { - throw new Error('the bind argument must start as a value with a path'); + if (path.indexOf("path:") !== 0) { + throw new Error("the bind argument must start as a value with a path"); } path = path.substring(5); @@ -315,39 +304,37 @@ function retrieveAndSetValue(element) { if (element instanceof HTMLInputElement) { switch (element.type) { - - case 'checkbox': + case "checkbox": value = element.checked ? element.value : undefined; break; default: value = element.value; break; - - } } else if (element instanceof HTMLTextAreaElement) { value = element.value; - } else if (element instanceof HTMLSelectElement) { - switch (element.type) { - case 'select-one': + case "select-one": value = element.value; break; - case 'select-multiple': + case "select-multiple": value = element.value; let options = element?.selectedOptions; if (options === undefined) options = element.querySelectorAll(":scope option:checked"); - value = Array.from(options).map(({value}) => value); + value = Array.from(options).map(({ value }) => value); break; } - - // values from customelements - } else if ((element?.constructor?.prototype && !!Object.getOwnPropertyDescriptor(element.constructor.prototype, 'value')?.['get']) || element.hasOwnProperty('value')) { - value = element?.['value']; + // values from customelements + } else if ( + (element?.constructor?.prototype && + !!Object.getOwnPropertyDescriptor(element.constructor.prototype, "value")?.["get"]) || + element.hasOwnProperty("value") + ) { + value = element?.["value"]; } else { throw new Error("unsupported object"); } @@ -373,13 +360,12 @@ function retrieveFromBindings() { const self = this; if (self[internalSymbol].element.matches(`[${ATTRIBUTE_UPDATER_BIND}]`)) { - retrieveAndSetValue.call(self, self[internalSymbol].element) + retrieveAndSetValue.call(self, self[internalSymbol].element); } for (const [, element] of self[internalSymbol].element.querySelectorAll(`[${ATTRIBUTE_UPDATER_BIND}]`).entries()) { - retrieveAndSetValue.call(self, element) + retrieveAndSetValue.call(self, element); } - } /** @@ -392,7 +378,9 @@ function retrieveFromBindings() { function removeElement(change) { const self = this; - for (const [, element] of self[internalSymbol].element.querySelectorAll(`:scope [${ATTRIBUTE_UPDATER_REMOVE}]`).entries()) { + for (const [, element] of self[internalSymbol].element + .querySelectorAll(`:scope [${ATTRIBUTE_UPDATER_REMOVE}]`) + .entries()) { element.parentNode.removeChild(element); } } @@ -414,7 +402,7 @@ function insertElement(change) { const subject = self[internalSymbol].subject.getRealSubject(); const document = getDocument(); - let mem = new WeakSet; + let mem = new WeakSet(); let wd = 0; const container = self[internalSymbol].element; @@ -423,21 +411,19 @@ function insertElement(change) { let found = false; wd++; - let p = clone(change?.['path']); + let p = clone(change?.["path"]); if (!isArray(p)) return self; while (p.length > 0) { - const current = p.join('.'); + const current = p.join("."); - let iterator = new Set; + let iterator = new Set(); const query = `[${ATTRIBUTE_UPDATER_INSERT}*="path:${current}"]`; const e = container.querySelectorAll(query); if (e.length > 0) { - iterator = new Set( - [...e] - ) + iterator = new Set([...e]); } if (container.matches(query)) { @@ -445,38 +431,37 @@ function insertElement(change) { } for (const [, containerElement] of iterator.entries()) { - if (mem.has(containerElement)) continue; - mem.add(containerElement) + mem.add(containerElement); found = true; const attributes = containerElement.getAttribute(ATTRIBUTE_UPDATER_INSERT); let def = trimSpaces(attributes); - let i = def.indexOf(' '); + let i = def.indexOf(" "); let key = trimSpaces(def.substr(0, i)); let refPrefix = `${key}-`; let cmd = trimSpaces(def.substr(i)); // this case is actually excluded by the query but is nevertheless checked again here - if (cmd.indexOf('|') > 0) { + if (cmd.indexOf("|") > 0) { throw new Error("pipes are not allowed when cloning a node."); } let pipe = new Pipe(cmd); self[internalSymbol].callbacks.forEach((f, n) => { pipe.setCallback(n, f); - }) + }); - let value + let value; try { containerElement.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject) + value = pipe.run(subject); } catch (e) { containerElement.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); } - let dataPath = cmd.split(':').pop(); + let dataPath = cmd.split(":").pop(); let insertPoint; if (containerElement.hasChildNodes()) { @@ -484,10 +469,10 @@ function insertElement(change) { } if (!isIterable(value)) { - throw new Error('the value is not iterable'); + throw new Error("the value is not iterable"); } - let available = new Set; + let available = new Set(); for (const [i, obj] of Object.entries(value)) { let ref = refPrefix + i; @@ -504,15 +489,19 @@ function insertElement(change) { appendNewDocumentFragment(containerElement, key, ref, currentPath); } - let nodes = containerElement.querySelectorAll(`[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}*="${refPrefix}"]`); + let nodes = containerElement.querySelectorAll( + `[${ATTRIBUTE_UPDATER_INSERT_REFERENCE}*="${refPrefix}"]`, + ); for (const [, node] of Object.entries(nodes)) { if (!available.has(node.getAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE))) { try { containerElement.removeChild(node); } catch (e) { - containerElement.setAttribute(ATTRIBUTE_ERRORMESSAGE, (`${containerElement.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${e.message}`).trim()); + containerElement.setAttribute( + ATTRIBUTE_ERRORMESSAGE, + `${containerElement.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${e.message}`.trim(), + ); } - } } } @@ -522,9 +511,8 @@ function insertElement(change) { if (found === false) break; if (wd++ > 200) { - throw new Error('the maximum depth for the recursion is reached.'); + throw new Error("the maximum depth for the recursion is reached."); } - } } @@ -540,13 +528,11 @@ function insertElement(change) { * @throws {Error} no template was found with the specified key. */ function appendNewDocumentFragment(container, key, ref, path) { - let template = findDocumentTemplate(key, container); let nodes = template.createDocumentFragment(); for (const [, node] of Object.entries(nodes.childNodes)) { if (node instanceof HTMLElement) { - applyRecursive(node, key, path); node.setAttribute(ATTRIBUTE_UPDATER_INSERT_REFERENCE, ref); } @@ -565,9 +551,7 @@ function appendNewDocumentFragment(container, key, ref, path) { * @return {void} */ function applyRecursive(node, key, path) { - if (node instanceof HTMLElement) { - if (node.hasAttribute(ATTRIBUTE_UPDATER_REPLACE)) { let value = node.getAttribute(ATTRIBUTE_UPDATER_REPLACE); node.setAttribute(ATTRIBUTE_UPDATER_REPLACE, value.replaceAll(`path:${key}`, `path:${path}`)); @@ -596,10 +580,10 @@ function updateContent(change) { const self = this; const subject = self[internalSymbol].subject.getRealSubject(); - let p = clone(change?.['path']); + let p = clone(change?.["path"]); runUpdateContent.call(this, this[internalSymbol].element, p, subject); - const slots = this[internalSymbol].element.querySelectorAll('slot'); + const slots = this[internalSymbol].element.querySelectorAll("slot"); if (slots.length > 0) { for (const [, slot] of Object.entries(slots)) { for (const [, element] of Object.entries(slot.assignedNodes())) { @@ -623,19 +607,17 @@ function runUpdateContent(container, parts, subject) { if (!(container instanceof HTMLElement)) return; parts = clone(parts); - let mem = new WeakSet; + let mem = new WeakSet(); while (parts.length > 0) { - const current = parts.join('.'); + const current = parts.join("."); parts.pop(); // Unfortunately, static data is always changed as well, since it is not possible to react to changes here. const query = `[${ATTRIBUTE_UPDATER_REPLACE}^="path:${current}"], [${ATTRIBUTE_UPDATER_REPLACE}^="static:"]`; const e = container.querySelectorAll(`${query}`); - const iterator = new Set([ - ...e - ]) + const iterator = new Set([...e]); if (container.matches(query)) { iterator.add(container); @@ -645,22 +627,21 @@ function runUpdateContent(container, parts, subject) { * @type {HTMLElement} */ for (const [element] of iterator.entries()) { - if (mem.has(element)) return; - mem.add(element) + mem.add(element); - const attributes = element.getAttribute(ATTRIBUTE_UPDATER_REPLACE) + const attributes = element.getAttribute(ATTRIBUTE_UPDATER_REPLACE); let cmd = trimSpaces(attributes); let pipe = new Pipe(cmd); this[internalSymbol].callbacks.forEach((f, n) => { pipe.setCallback(n, f); - }) + }); - let value + let value; try { element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject) + value = pipe.run(subject); } catch (e) { element.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); } @@ -673,18 +654,16 @@ function runUpdateContent(container, parts, subject) { try { element.appendChild(value); } catch (e) { - element.setAttribute(ATTRIBUTE_ERRORMESSAGE, (`${element.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${e.message}`).trim()); + element.setAttribute( + ATTRIBUTE_ERRORMESSAGE, + `${element.getAttribute(ATTRIBUTE_ERRORMESSAGE)}, ${e.message}`.trim(), + ); } - } else { element.innerHTML = value; } - } - - } - } /** @@ -697,7 +676,7 @@ function runUpdateContent(container, parts, subject) { */ function updateAttributes(change) { const subject = this[internalSymbol].subject.getRealSubject(); - let p = clone(change?.['path']); + let p = clone(change?.["path"]); runUpdateAttributes.call(this, this[internalSymbol].element, p, subject); } @@ -710,28 +689,25 @@ function updateAttributes(change) { * @this Updater */ function runUpdateAttributes(container, parts, subject) { - const self = this; if (!isArray(parts)) return; parts = clone(parts); - let mem = new WeakSet; + let mem = new WeakSet(); while (parts.length > 0) { - const current = parts.join('.'); + const current = parts.join("."); parts.pop(); - let iterator = new Set; + let iterator = new Set(); const query = `[${ATTRIBUTE_UPDATER_SELECT_THIS}], [${ATTRIBUTE_UPDATER_ATTRIBUTES}*="path:${current}"], [${ATTRIBUTE_UPDATER_ATTRIBUTES}^="static:"]`; const e = container.querySelectorAll(query); if (e.length > 0) { - iterator = new Set( - [...e] - ) + iterator = new Set([...e]); } if (container.matches(query)) { @@ -739,15 +715,14 @@ function runUpdateAttributes(container, parts, subject) { } for (const [element] of iterator.entries()) { - if (mem.has(element)) return; - mem.add(element) + mem.add(element); - const attributes = element.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES) + const attributes = element.getAttribute(ATTRIBUTE_UPDATER_ATTRIBUTES); - for (let [, def] of Object.entries(attributes.split(','))) { + for (let [, def] of Object.entries(attributes.split(","))) { def = trimSpaces(def); - let i = def.indexOf(' '); + let i = def.indexOf(" "); let name = trimSpaces(def.substr(0, i)); let cmd = trimSpaces(def.substr(i)); @@ -755,30 +730,26 @@ function runUpdateAttributes(container, parts, subject) { self[internalSymbol].callbacks.forEach((f, n) => { pipe.setCallback(n, f, element); - }) + }); - let value + let value; try { element.removeAttribute(ATTRIBUTE_ERRORMESSAGE); - value = pipe.run(subject) + value = pipe.run(subject); } catch (e) { element.setAttribute(ATTRIBUTE_ERRORMESSAGE, e.message); } - if (value === undefined) { - element.removeAttribute(name) - + element.removeAttribute(name); } else if (element.getAttribute(name) !== value) { element.setAttribute(name, value); } handleInputControlAttributeUpdate.call(this, element, name, value); - } } } - } /** @@ -794,11 +765,8 @@ function handleInputControlAttributeUpdate(element, name, value) { const self = this; if (element instanceof HTMLSelectElement) { - - switch (element.type) { - case 'select-multiple': - + case "select-multiple": for (const [index, opt] of Object.entries(element.options)) { if (value.indexOf(opt.value) !== -1) { opt.selected = true; @@ -808,7 +776,7 @@ function handleInputControlAttributeUpdate(element, name, value) { } break; - case 'select-one': + case "select-one": // Only one value may be selected for (const [index, opt] of Object.entries(element.options)) { @@ -820,14 +788,10 @@ function handleInputControlAttributeUpdate(element, name, value) { break; } - - } else if (element instanceof HTMLInputElement) { switch (element.type) { - - case 'radio': - if (name === 'checked') { - + case "radio": + if (name === "checked") { if (value !== undefined) { element.checked = true; } else { @@ -837,10 +801,8 @@ function handleInputControlAttributeUpdate(element, name, value) { break; - case 'checkbox': - - if (name === 'checked') { - + case "checkbox": + if (name === "checked") { if (value !== undefined) { element.checked = true; } else { @@ -849,26 +811,21 @@ function handleInputControlAttributeUpdate(element, name, value) { } break; - case 'text': + case "text": default: - if (name === 'value') { - element.value = (value === undefined ? "" : value); + if (name === "value") { + element.value = value === undefined ? "" : value; } break; - - } } else if (element instanceof HTMLTextAreaElement) { - if (name === 'value') { - element.value = (value === undefined ? "" : value); + if (name === "value") { + element.value = value === undefined ? "" : value; } } - } - - /** * @param {NodeList|HTMLElement|Set<HTMLElement>} elements * @param {Symbol} symbol @@ -881,26 +838,22 @@ function handleInputControlAttributeUpdate(element, name, value) { * @throws {TypeError} the context of the function is not an instance of HTMLElement * @throws {TypeError} symbol must be an instance of Symbol */ -function addObjectWithUpdaterToElement (elements,symbol, object) { +function addObjectWithUpdaterToElement(elements, symbol, object) { const self = this; if (!(self instanceof HTMLElement)) { - throw new TypeError('the context of this function must be an instance of HTMLElement'); + throw new TypeError("the context of this function must be an instance of HTMLElement"); } - - if (!(typeof symbol === 'symbol')) { - throw new TypeError('symbol must be an instance of Symbol'); + + if (!(typeof symbol === "symbol")) { + throw new TypeError("symbol must be an instance of Symbol"); } - const updaters = new Set; + const updaters = new Set(); if (elements instanceof NodeList) { - elements = new Set([ - ...elements - ]) + elements = new Set([...elements]); } else if (elements instanceof HTMLElement) { - elements = new Set([ - elements - ]) + elements = new Set([elements]); } else if (elements instanceof Set) { } else { throw new TypeError(`elements is not a valid type. (actual: ${typeof elements})`); @@ -910,15 +863,16 @@ function addObjectWithUpdaterToElement (elements,symbol, object) { elements.forEach((element) => { if (!(element instanceof HTMLElement)) return; - if ((element instanceof HTMLTemplateElement)) return; + if (element instanceof HTMLTemplateElement) return; - const u = new Updater(element, object) + const u = new Updater(element, object); updaters.add(u); - result.push(u.run().then(() => { - return u.enableEventProcessing(); - })); - + result.push( + u.run().then(() => { + return u.enableEventProcessing(); + }), + ); }); if (updaters.size > 0) { diff --git a/application/source/dom/util.mjs b/application/source/dom/util.mjs index ee3e40590..aa7360a43 100644 --- a/application/source/dom/util.mjs +++ b/application/source/dom/util.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getGlobal} from "../types/global.mjs"; -import {validateString} from "../types/validate.mjs"; +import { getGlobal } from "../types/global.mjs"; +import { validateString } from "../types/validate.mjs"; -export {getDocument, getWindow, getDocumentFragmentFromString} +export { getDocument, getWindow, getDocumentFragmentFromString }; /** * This method fetches the document object @@ -48,9 +48,9 @@ export {getDocument, getWindow, getDocumentFragmentFromString} * @throws {Error} not supported environment */ function getDocument() { - let document = getGlobal()?.['document']; - if (typeof document !== 'object') { - throw new Error("not supported environment") + let document = getGlobal()?.["document"]; + if (typeof document !== "object") { + throw new Error("not supported environment"); } return document; @@ -70,7 +70,7 @@ function getDocument() { * }); * * getGlobal()['window']=window; - * + * * [ * 'self', * 'document', @@ -96,15 +96,14 @@ function getDocument() { * @throws {Error} not supported environment */ function getWindow() { - let window = getGlobal()?.['window']; - if (typeof window !== 'object') { - throw new Error("not supported environment") + let window = getGlobal()?.["window"]; + if (typeof window !== "object") { + throw new Error("not supported environment"); } return window; } - /** * This method fetches the document object * @@ -147,7 +146,7 @@ function getDocumentFragmentFromString(html) { validateString(html); const document = getDocument(); - const template = document.createElement('template'); + const template = document.createElement("template"); template.innerHTML = html; return template.content; diff --git a/application/source/dom/worker/factory.mjs b/application/source/dom/worker/factory.mjs index c96d71891..183355651 100644 --- a/application/source/dom/worker/factory.mjs +++ b/application/source/dom/worker/factory.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../../constants.mjs"; -import {Base} from "../../types/base.mjs"; -import {getGlobal, getGlobalFunction} from "../../types/global.mjs"; -import {isFunction} from "../../types/is.mjs"; -import {validateInstance, validateString} from "../../types/validate.mjs"; +import { internalSymbol } from "../../constants.mjs"; +import { Base } from "../../types/base.mjs"; +import { getGlobal, getGlobalFunction } from "../../types/global.mjs"; +import { isFunction } from "../../types/is.mjs"; +import { validateInstance, validateString } from "../../types/validate.mjs"; -export {Factory} +export { Factory }; /** * A factory for creating worker instances. - * + * * @license AGPLv3 * @since 1.25.0 * @copyright schukai GmbH @@ -23,15 +23,14 @@ export {Factory} * @summary A small factory to create worker */ class Factory extends Base { - /** * */ constructor() { super(); this[internalSymbol] = { - worker: new WeakMap - } + worker: new WeakMap(), + }; } /** @@ -43,24 +42,23 @@ class Factory extends Base { * @return {Worker} */ createFromURL = function (url, messageHandler, errorHandler) { - if (url instanceof URL) { url = url.toString(); } - const workerClass = getGlobalFunction('Worker'); + const workerClass = getGlobalFunction("Worker"); var worker = new workerClass(validateString(url)); if (isFunction(messageHandler)) { worker.onmessage = (event) => { messageHandler.call(worker, event); - } + }; } if (isFunction(errorHandler)) { worker.onerror = (event) => { errorHandler.call(worker, event); - } + }; } return worker; @@ -76,16 +74,17 @@ class Factory extends Base { * @see https://developer.mozilla.org/de/docs/Web/API/URL/createObjectURL */ createFromScript = function (content, messageHandler, errorHandler) { - const blobFunction = new getGlobalFunction('Blob') - const blob = new blobFunction([validateString(content)], {type: 'script/javascript'}); + const blobFunction = new getGlobalFunction("Blob"); + const blob = new blobFunction([validateString(content)], { + type: "script/javascript", + }); - const url = getGlobalFunction('URL').createObjectURL(blob); + const url = getGlobalFunction("URL").createObjectURL(blob); const worker = this.createFromURL(url, messageHandler, errorHandler); - this[internalSymbol]['worker'].set(worker, url); + this[internalSymbol]["worker"].set(worker, url); return worker; - }; /** @@ -95,19 +94,16 @@ class Factory extends Base { * @return {Monster.DOM.Worker.Factory} */ terminate(worker) { - - const workerClass = getGlobalFunction('Worker'); + const workerClass = getGlobalFunction("Worker"); validateInstance(worker, workerClass); worker.terminate(); - if (this[internalSymbol]['worker'].has(worker)) { - const url = this[internalSymbol]['worker'].get(worker); + if (this[internalSymbol]["worker"].has(worker)) { + const url = this[internalSymbol]["worker"].get(worker); URL.revokeObjectURL(url); } return this; } - - } diff --git a/application/source/dom/worker/namespace.mjs b/application/source/dom/worker/namespace.mjs index 959ef0a22..512998707 100644 --- a/application/source/dom/worker/namespace.mjs +++ b/application/source/dom/worker/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/i18n/formatter.mjs b/application/source/i18n/formatter.mjs index 281a40806..c58aecb5a 100644 --- a/application/source/i18n/formatter.mjs +++ b/application/source/i18n/formatter.mjs @@ -5,20 +5,20 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {extend} from "../data/extend.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { extend } from "../data/extend.mjs"; -import {Formatter as TextFormatter} from "../text/formatter.mjs"; -import {validateInstance, validateString} from "../types/validate.mjs"; -import {Translations} from "./translations.mjs"; +import { Formatter as TextFormatter } from "../text/formatter.mjs"; +import { validateInstance, validateString } from "../types/validate.mjs"; +import { Translations } from "./translations.mjs"; -export {Formatter} +export { Formatter }; /** * @private * @type {symbol} */ -const internalTranslationSymbol = Symbol('internalTranslation') +const internalTranslationSymbol = Symbol("internalTranslation"); /** * The Formatter extends the Text.Formatter with the possibility to replace the key by a translation. @@ -30,7 +30,6 @@ const internalTranslationSymbol = Symbol('internalTranslation') * @memberOf Monster.I18n */ class Formatter extends TextFormatter { - /** * Default values for the markers are `${` and `}` * @@ -58,13 +57,13 @@ class Formatter extends TextFormatter { callbacks: { i18n: (value) => { return self[internalTranslationSymbol].getText(validateString(value)); - } + }, }, marker: { - open: ['i18n{', '${'], - close: ['}'], + open: ["i18n{", "${"], + close: ["}"], }, - }) + }); } /** @@ -77,10 +76,10 @@ class Formatter extends TextFormatter { * @throws {Error} the closing marker is missing */ format(text) { - validateString(text) + validateString(text); - const openMarker = this[internalSymbol]['marker']['open']?.[0]; - const closeMarker = this[internalSymbol]['marker']['close']?.[0]; + const openMarker = this[internalSymbol]["marker"]["open"]?.[0]; + const closeMarker = this[internalSymbol]["marker"]["close"]?.[0]; if (text.indexOf(openMarker) === 0) { text = text.substring(openMarker.length); @@ -88,14 +87,13 @@ class Formatter extends TextFormatter { if (text.indexOf(closeMarker) === text.length - closeMarker.length) { text = text.substring(0, text.length - closeMarker.length); } else { - throw new Error("the closing marker is missing") + throw new Error("the closing marker is missing"); } } - - const parts = validateString(text).split('::') - const translationKey = parts.shift().trim(); // key value delimiter - const parameter = parts.join('::').trim(); + const parts = validateString(text).split("::"); + const translationKey = parts.shift().trim(); // key value delimiter + const parameter = parts.join("::").trim(); let assembledText = `${openMarker}static:${translationKey} | call:i18n`; if (parameter.length > 0) { @@ -104,6 +102,4 @@ class Formatter extends TextFormatter { assembledText += closeMarker; return super.format(assembledText); } - - } diff --git a/application/source/i18n/locale.mjs b/application/source/i18n/locale.mjs index f93009465..26622acb7 100644 --- a/application/source/i18n/locale.mjs +++ b/application/source/i18n/locale.mjs @@ -5,23 +5,23 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from "../types/base.mjs"; -import {validateString} from "../types/validate.mjs"; -import {clone} from "../util/clone.mjs"; +import { Base } from "../types/base.mjs"; +import { validateString } from "../types/validate.mjs"; +import { clone } from "../util/clone.mjs"; -export {Locale, parseLocale} +export { Locale, parseLocale }; /** * @memberOf Monster.I18n * @type {symbol} */ -const propertiesSymbol = Symbol('properties'); +const propertiesSymbol = Symbol("properties"); /** * @type {symbol} * @memberOf Monster.I18n */ -const localeStringSymbol = Symbol('localeString'); +const localeStringSymbol = Symbol("localeString"); /** * The Locale class is a base class for the language classes. @@ -64,7 +64,6 @@ const localeStringSymbol = Symbol('localeString'); * @see https://datatracker.ietf.org/doc/html/rfc3066 */ class Locale extends Base { - /** * @param {string} language * @param {string} [region] @@ -78,12 +77,12 @@ class Locale extends Base { super(); this[propertiesSymbol] = { - language: (language === undefined) ? undefined : validateString(language), - script: (script === undefined) ? undefined : validateString(script), - region: (region === undefined) ? undefined : validateString(region), - variants: (variants === undefined) ? undefined : validateString(variants), - extlang: (extlang === undefined) ? undefined : validateString(extlang), - privateUse: (privateUse === undefined) ? undefined : validateString(privateUse), + language: language === undefined ? undefined : validateString(language), + script: script === undefined ? undefined : validateString(script), + region: region === undefined ? undefined : validateString(region), + variants: variants === undefined ? undefined : validateString(variants), + extlang: extlang === undefined ? undefined : validateString(extlang), + privateUse: privateUse === undefined ? undefined : validateString(privateUse), }; let s = []; @@ -95,11 +94,10 @@ class Locale extends Base { if (privateUse !== undefined) s.push(privateUse); if (s.length === 0) { - throw new Error('unsupported locale'); + throw new Error("unsupported locale"); } - this[localeStringSymbol] = s.join('-'); - + this[localeStringSymbol] = s.join("-"); } /** @@ -151,7 +149,6 @@ class Locale extends Base { return this[propertiesSymbol].privateValue; } - /** * @return {string} */ @@ -165,10 +162,8 @@ class Locale extends Base { * @return {Monster.I18n.LocaleMap} */ getMap() { - return clone(this[propertiesSymbol]) + return clone(this[propertiesSymbol]); } - - } /** @@ -263,7 +258,6 @@ class Locale extends Base { * @throws {Error} unsupported locale */ function parseLocale(locale) { - locale = validateString(locale).replace(/_/g, "-"); let language; @@ -273,7 +267,8 @@ function parseLocale(locale) { let script; let extlang; let regexRegular = "(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang)"; - let regexIrregular = "(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)"; + let regexIrregular = + "(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)"; let regexGrandfathered = `(${regexIrregular}|${regexRegular})`; let regexPrivateUse = "(x(-[A-Za-z0-9]{1,8})+)"; let regexSingleton = "[0-9A-WY-Za-wy-z]"; @@ -288,7 +283,6 @@ function parseLocale(locale) { let regex = new RegExp(regexLanguageTag); let match; - if ((match = regex.exec(locale)) !== null) { if (match.index === regex.lastIndex) { regex.lastIndex++; @@ -296,18 +290,17 @@ function parseLocale(locale) { } if (match === undefined || match === null) { - throw new Error('unsupported locale'); + throw new Error("unsupported locale"); } if (match[6] !== undefined) { language = match[6]; - parts = language.split('-'); + parts = language.split("-"); if (parts.length > 1) { language = parts[0]; extlang = parts[1]; } - } if (match[14] !== undefined) { @@ -323,5 +316,4 @@ function parseLocale(locale) { } return new Locale(language, region, script, variants, extlang); - } diff --git a/application/source/i18n/namespace.mjs b/application/source/i18n/namespace.mjs index f39b342ba..a123745ae 100644 --- a/application/source/i18n/namespace.mjs +++ b/application/source/i18n/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/i18n/provider.mjs b/application/source/i18n/provider.mjs index 12337549f..8e0fab5ea 100644 --- a/application/source/i18n/provider.mjs +++ b/application/source/i18n/provider.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {Locale} from "./locale.mjs" -import {Translations} from "./translations.mjs" +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { Locale } from "./locale.mjs"; +import { Translations } from "./translations.mjs"; -export {Provider} +export { Provider }; /** * A provider makes a translation object available. @@ -21,7 +21,6 @@ export {Provider} * @see {@link https://datatracker.ietf.org/doc/html/rfc3066} */ class Provider extends BaseWithOptions { - /** * @param {Locale|string} locale * @return {Promise} @@ -33,8 +32,6 @@ class Provider extends BaseWithOptions { } catch (e) { reject(e); } - }); } - } diff --git a/application/source/i18n/providers/embed.mjs b/application/source/i18n/providers/embed.mjs index d4d1f0b7f..1aa8c9acd 100644 --- a/application/source/i18n/providers/embed.mjs +++ b/application/source/i18n/providers/embed.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../../constants.mjs"; -import {extend} from "../../data/extend.mjs"; -import { getGlobalObject} from "../../types/global.mjs"; -import {isString} from "../../types/is.mjs"; -import {validateObject, validateString} from "../../types/validate.mjs"; -import {parseLocale} from "../locale.mjs"; -import {Provider} from "../provider.mjs"; -import {Translations} from "../translations.mjs"; +import { internalSymbol } from "../../constants.mjs"; +import { extend } from "../../data/extend.mjs"; +import { getGlobalObject } from "../../types/global.mjs"; +import { isString } from "../../types/is.mjs"; +import { validateObject, validateString } from "../../types/validate.mjs"; +import { parseLocale } from "../locale.mjs"; +import { Provider } from "../provider.mjs"; +import { Translations } from "../translations.mjs"; -export {Embed} +export { Embed }; /** * The Embed provider retrieves a JSON file from the given Script Tag. @@ -28,7 +28,6 @@ export {Embed} * @tutorial i18n-locale-and-formatter */ class Embed extends Provider { - /** * ```html * <script id="translations" type="application/json"> @@ -37,8 +36,8 @@ class Embed extends Provider { * } * </script> * ``` - * - * + * + * * ```javascript * new Embed('translations') * ``` @@ -65,7 +64,6 @@ class Embed extends Provider { * @property {Object} options */ this[internalSymbol] = extend({}, super.defaults, this.defaults, validateObject(options)); - } /** @@ -83,17 +81,15 @@ class Embed extends Provider { * @return {Promise} */ getTranslations(locale) { - if (isString(locale)) { locale = parseLocale(locale); } return new Promise((resolve, reject) => { - - let text = getGlobalObject('document').getElementById(this.textId); + let text = getGlobalObject("document").getElementById(this.textId); if (text === null) { - reject(new Error('Text not found')); + reject(new Error("Text not found")); return; } @@ -105,21 +101,15 @@ class Embed extends Provider { return; } - if (translations === null) { - reject(new Error('Translations not found or invalid')); + reject(new Error("Translations not found or invalid")); return; } - + const t = new Translations(locale); - t.assignTranslations(translations) + t.assignTranslations(translations); resolve(t); - }); - } - - } - diff --git a/application/source/i18n/providers/fetch.mjs b/application/source/i18n/providers/fetch.mjs index 0ce8abe25..061f37c8e 100644 --- a/application/source/i18n/providers/fetch.mjs +++ b/application/source/i18n/providers/fetch.mjs @@ -5,21 +5,21 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../../constants.mjs"; -import {extend} from "../../data/extend.mjs"; -import {Formatter} from "../../text/formatter.mjs"; -import {getGlobalFunction} from "../../types/global.mjs"; -import {isInstance, isString} from "../../types/is.mjs"; -import {validateObject, validateString} from "../../types/validate.mjs"; -import {parseLocale} from "../locale.mjs"; -import {Provider} from "../provider.mjs"; -import {Translations} from "../translations.mjs"; - -export {Fetch} +import { internalSymbol } from "../../constants.mjs"; +import { extend } from "../../data/extend.mjs"; +import { Formatter } from "../../text/formatter.mjs"; +import { getGlobalFunction } from "../../types/global.mjs"; +import { isInstance, isString } from "../../types/is.mjs"; +import { validateObject, validateString } from "../../types/validate.mjs"; +import { parseLocale } from "../locale.mjs"; +import { Provider } from "../provider.mjs"; +import { Translations } from "../translations.mjs"; + +export { Fetch }; /** * The fetch provider retrieves a JSON file from the given URL and returns a translation object. - * + * * @externalExample ../../../example/i18n/providers/fetch.mjs * @license AGPLv3 * @since 1.13.0 @@ -28,17 +28,16 @@ export {Fetch} * @see {@link https://datatracker.ietf.org/doc/html/rfc3066} * @tutorial i18n-locale-and-formatter */ - class Fetch extends Provider { - +class Fetch extends Provider { /** * As options the key `fetch` can be passed. This config object is passed to the fetch method as init. - * + * * The url may contain placeholders (language, script, region, variants, extlang, privateUse), so you can specify one url for all translations. - * + * * ``` * new Fetch('https://www.example.com/assets/${language}.json') * ``` - * + * * @param {string|URL} url * @param {Object} options see {@link Monster.I18n.Providers.Fetch#defaults} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch} @@ -66,7 +65,6 @@ export {Fetch} * @property {Object} options */ this[internalSymbol] = extend({}, super.defaults, this.defaults, validateObject(options)); - } /** @@ -83,19 +81,19 @@ export {Fetch} * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API} */ get defaults() { - return extend( { fetch: { - method: 'GET', // *GET, POST, PUT, DELETE, etc. - mode: 'cors', // no-cors, *cors, same-origin - cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached - credentials: 'omit', // include, *same-origin, omit - redirect: 'follow', // manual, *follow, error - referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url - } - }, super.defaults); - + method: "GET", // *GET, POST, PUT, DELETE, etc. + mode: "cors", // no-cors, *cors, same-origin + cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached + credentials: "omit", // include, *same-origin, omit + redirect: "follow", // manual, *follow, error + referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url + }, + }, + super.defaults, + ); } /** @@ -104,20 +102,16 @@ export {Fetch} * @return {Promise} */ getTranslations(locale) { - if (isString(locale)) { locale = parseLocale(locale); } - let formatter = new Formatter(locale.getMap()) + let formatter = new Formatter(locale.getMap()); - return getGlobalFunction('fetch')(formatter.format(this.url), this.getOption('fetch', {})) - .then((response) => response.json()).then(data => { + return getGlobalFunction("fetch")(formatter.format(this.url), this.getOption("fetch", {})) + .then((response) => response.json()) + .then((data) => { return new Translations(locale).assignTranslations(data); }); - } - - } - diff --git a/application/source/i18n/translations.mjs b/application/source/i18n/translations.mjs index be020dd56..74f9d4c2e 100644 --- a/application/source/i18n/translations.mjs +++ b/application/source/i18n/translations.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from "../types/base.mjs"; -import {isObject, isString} from "../types/is.mjs"; -import {validateInstance, validateInteger, validateObject, validateString} from "../types/validate.mjs"; -import {Locale, parseLocale} from "./locale.mjs"; +import { Base } from "../types/base.mjs"; +import { isObject, isString } from "../types/is.mjs"; +import { validateInstance, validateInteger, validateObject, validateString } from "../types/validate.mjs"; +import { Locale, parseLocale } from "./locale.mjs"; -export {Translations} +export { Translations }; /** * With this class you can manage translations and access the keys. @@ -23,7 +23,6 @@ export {Translations} * @see https://datatracker.ietf.org/doc/html/rfc3066 */ class Translations extends Base { - /** * * @param {Locale} locale @@ -37,10 +36,8 @@ class Translations extends Base { this.locale = validateInstance(locale, Locale); this.storage = new Map(); - } - /** * Fetches a text using the specified key. * If no suitable key is found, `defaultText` is taken. @@ -61,7 +58,7 @@ class Translations extends Base { let r = this.storage.get(key); if (isObject(r)) { - return this.getPluralRuleText(key, 'other', defaultText); + return this.getPluralRuleText(key, "other", defaultText); } return this.storage.get(key); @@ -92,8 +89,8 @@ class Translations extends Base { count = validateInteger(count); if (count === 0) { // special handlig for zero count - if (r.hasOwnProperty('zero')) { - return validateString(r['zero']); + if (r.hasOwnProperty("zero")) { + return validateString(r["zero"]); } } @@ -131,26 +128,24 @@ class Translations extends Base { * @throws {TypeError} value is not a string or object */ setText(key, text) { - if (isString(text) || isObject(text)) { this.storage.set(validateString(key), text); return this; } - throw new TypeError('value is not a string or object'); - + throw new TypeError("value is not a string or object"); } /** - * This method can be used to transfer overlays from an object. The keys are transferred, and the values are entered + * This method can be used to transfer overlays from an object. The keys are transferred, and the values are entered * as text. - * + * * The values can either be character strings or, in the case of texts with plural forms, objects. The plural forms * must be stored as text via a standard key "zero", "one", "two", "few", "many" and "other". - * + * * Additionally, the key default can be specified, which will be used if no other key fits. - * - * In some languages, like for example in German, there is no own more number at the value 0. In these languages, + * + * In some languages, like for example in German, there is no own more number at the value 0. In these languages, * the function applies additionally zero. * * ``` @@ -176,7 +171,5 @@ class Translations extends Base { } return this; - } - } diff --git a/application/source/logging/handler.mjs b/application/source/logging/handler.mjs index 9971ce6dc..c448a3c54 100644 --- a/application/source/logging/handler.mjs +++ b/application/source/logging/handler.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {validateInstance, validateInteger} from "../types/validate.mjs"; -import {LogEntry} from "./logentry.mjs"; -import {ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN} from "./logger.mjs"; +import { Base } from "../types/base.mjs"; +import { validateInstance, validateInteger } from "../types/validate.mjs"; +import { LogEntry } from "./logentry.mjs"; +import { ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN } from "./logger.mjs"; -export {Handler} +export { Handler }; /** * The log handler is the interface between the log entries and the log listeners. @@ -20,7 +20,7 @@ export {Handler} * @copyright schukai GmbH * @memberOf Monster.Logging */ - class Handler extends Base { +class Handler extends Base { constructor() { super(); @@ -59,7 +59,7 @@ export {Handler} * @since 1.5.0 */ setLogLevel(loglevel) { - validateInteger(loglevel) + validateInteger(loglevel); this.loglevel = loglevel; return this; } @@ -83,7 +83,7 @@ export {Handler} setAll() { this.setLogLevel(ALL); return this; - }; + } /** * Set log level to Trace @@ -94,7 +94,7 @@ export {Handler} setTrace() { this.setLogLevel(TRACE); return this; - }; + } /** * Set log level to Debug @@ -105,7 +105,7 @@ export {Handler} setDebug() { this.setLogLevel(DEBUG); return this; - }; + } /** * Set log level to Info @@ -116,7 +116,7 @@ export {Handler} setInfo() { this.setLogLevel(INFO); return this; - }; + } /** * Set log level to Warn @@ -127,7 +127,7 @@ export {Handler} setWarn() { this.setLogLevel(WARN); return this; - }; + } /** * Set log level to Error @@ -138,7 +138,7 @@ export {Handler} setError() { this.setLogLevel(ERROR); return this; - }; + } /** * Set log level to Fatal @@ -149,8 +149,7 @@ export {Handler} setFatal() { this.setLogLevel(FATAL); return this; - }; - + } /** * Set log level to Off @@ -161,7 +160,5 @@ export {Handler} setOff() { this.setLogLevel(OFF); return this; - }; - - + } } diff --git a/application/source/logging/handler/console.mjs b/application/source/logging/handler/console.mjs index b5cb4b3ad..1ff2096bb 100644 --- a/application/source/logging/handler/console.mjs +++ b/application/source/logging/handler/console.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getGlobalObject} from "../../types/global.mjs"; -import {Handler} from '../handler.mjs'; -import {LogEntry} from "../logentry.mjs"; -import {TRACE, WARN, DEBUG, ERROR, FATAL, INFO} from "../logger.mjs"; +import { getGlobalObject } from "../../types/global.mjs"; +import { Handler } from "../handler.mjs"; +import { LogEntry } from "../logentry.mjs"; +import { TRACE, WARN, DEBUG, ERROR, FATAL, INFO } from "../logger.mjs"; -export {ConsoleHandler} +export { ConsoleHandler }; /** * You can create an object of the class simply by using the namespace `new Monster.Logging.Handler.ConsoleHandler()`. @@ -36,7 +36,7 @@ class ConsoleHandler extends Handler { */ log(entry) { if (super.log(entry)) { - let console = getGlobalObject('console'); + let console = getGlobalObject("console"); if (!console) return false; if (!console.error) console.error = console.log; @@ -58,7 +58,6 @@ class ConsoleHandler extends Handler { default: console.log(entry.toString()); break; - } return true; @@ -66,7 +65,4 @@ class ConsoleHandler extends Handler { return false; } - } - - diff --git a/application/source/logging/logentry.mjs b/application/source/logging/logentry.mjs index e93ab0478..27cc08948 100644 --- a/application/source/logging/logentry.mjs +++ b/application/source/logging/logentry.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {validateInteger} from '../types/validate.mjs'; +import { Base } from "../types/base.mjs"; +import { validateInteger } from "../types/validate.mjs"; -export {LogEntry} +export { LogEntry }; /** * A log entry for the logger @@ -18,7 +18,7 @@ export {LogEntry} * @copyright schukai GmbH * @memberOf Monster.Logging */ - class LogEntry extends Base { +class LogEntry extends Base { /** * * @param {Integer} loglevel @@ -28,8 +28,8 @@ export {LogEntry} super(); validateInteger(loglevel); - this.loglevel = loglevel - this.arguments = args + this.loglevel = loglevel; + this.arguments = args; } /** @@ -37,7 +37,7 @@ export {LogEntry} * @returns {integerr} */ getLogLevel() { - return this.loglevel + return this.loglevel; } /** @@ -45,7 +45,6 @@ export {LogEntry} * @returns {array} */ getArguments() { - return this.arguments + return this.arguments; } - } diff --git a/application/source/logging/logger.mjs b/application/source/logging/logger.mjs index c4e3a6af0..a80b04103 100644 --- a/application/source/logging/logger.mjs +++ b/application/source/logging/logger.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Handler} from '../logging/handler.mjs'; -import {LogEntry} from '../logging/logentry.mjs'; +import { Handler } from "../logging/handler.mjs"; +import { LogEntry } from "../logging/logentry.mjs"; -import {Base} from '../types/base.mjs'; -import {validateInteger, validateObject, validateString} from '../types/validate.mjs'; +import { Base } from "../types/base.mjs"; +import { validateInteger, validateObject, validateString } from "../types/validate.mjs"; -export {Logger, ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF}; +export { Logger, ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF }; /** * ALL > TRACE > DEBUG > INFO > WARN > ERROR > FATAL > OFF @@ -71,13 +71,12 @@ const OFF = 0; * @memberOf Monster.Logging */ class Logger extends Base { - /** * */ constructor() { super(); - this.handler = new Set; + this.handler = new Set(); } /** @@ -87,12 +86,12 @@ class Logger extends Base { * @throws {Error} the handler must be an instance of Handler */ addHandler(handler) { - validateObject(handler) + validateObject(handler); if (!(handler instanceof Handler)) { - throw new Error("the handler must be an instance of Handler") + throw new Error("the handler must be an instance of Handler"); } - this.handler.add(handler) + this.handler.add(handler); return this; } @@ -103,9 +102,9 @@ class Logger extends Base { * @throws {Error} the handler must be an instance of Handler */ removeHandler(handler) { - validateObject(handler) + validateObject(handler); if (!(handler instanceof Handler)) { - throw new Error("the handler must be an instance of Handler") + throw new Error("the handler must be an instance of Handler"); } this.handler.delete(handler); @@ -122,14 +121,13 @@ class Logger extends Base { * @since 1.5.0 */ logTrace(...args) { + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); + } - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') - } - triggerLog.apply(this, [TRACE, ...args]); return this; - }; + } /** * log Debug message @@ -141,14 +139,13 @@ class Logger extends Base { * @since 1.5.0 */ logDebug(...args) { + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); + } - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') - } - triggerLog.apply(this, [DEBUG, ...args]); return this; - }; + } /** * log Info message @@ -161,14 +158,13 @@ class Logger extends Base { * @since 1.5.0 */ logInfo(...args) { + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); + } - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') - } - triggerLog.apply(this, [INFO, ...args]); return this; - }; + } /** * log Warn message @@ -180,14 +176,13 @@ class Logger extends Base { * @since 1.5.0 */ logWarn(...args) { + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); + } - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') - } - triggerLog.apply(this, [WARN, ...args]); return this; - }; + } /** * log Error message @@ -199,14 +194,13 @@ class Logger extends Base { * @since 1.5.0 */ logError(...args) { + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); + } - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') - } - triggerLog.apply(this, [ERROR, ...args]); return this; - }; + } /** * log Fatal message @@ -218,15 +212,13 @@ class Logger extends Base { * @since 1.5.0 */ logFatal(...args) { - - if (typeof args !== 'object' || args[0] === null) { - throw new Error('the first argument must be an object') + if (typeof args !== "object" || args[0] === null) { + throw new Error("the first argument must be an object"); } triggerLog.apply(this, [FATAL, ...args]); return this; - }; - + } /** * Labels @@ -237,17 +229,17 @@ class Logger extends Base { getLabel(level) { validateInteger(level); - if (level === ALL) return 'ALL'; - if (level === TRACE) return 'TRACE'; - if (level === DEBUG) return 'DEBUG'; - if (level === INFO) return 'INFO'; - if (level === WARN) return 'WARN'; - if (level === ERROR) return 'ERROR'; - if (level === FATAL) return 'FATAL'; - if (level === OFF) return 'OFF'; + if (level === ALL) return "ALL"; + if (level === TRACE) return "TRACE"; + if (level === DEBUG) return "DEBUG"; + if (level === INFO) return "INFO"; + if (level === WARN) return "WARN"; + if (level === ERROR) return "ERROR"; + if (level === FATAL) return "FATAL"; + if (level === OFF) return "OFF"; - return 'unknown'; - }; + return "unknown"; + } /** * Level @@ -258,22 +250,19 @@ class Logger extends Base { getLevel(label) { validateString(label); - if (label === 'ALL') return ALL; - if (label === 'TRACE') return TRACE; - if (label === 'DEBUG') return DEBUG; - if (label === 'INFO') return INFO; - if (label === 'WARN') return WARN; - if (label === 'ERROR') return ERROR; - if (label === 'FATAL') return FATAL; - if (label === 'OFF') return OFF; + if (label === "ALL") return ALL; + if (label === "TRACE") return TRACE; + if (label === "DEBUG") return DEBUG; + if (label === "INFO") return INFO; + if (label === "WARN") return WARN; + if (label === "ERROR") return ERROR; + if (label === "FATAL") return FATAL; + if (label === "OFF") return OFF; return 0; - }; - - + } } - /** * Log triggern * @@ -286,9 +275,8 @@ function triggerLog(loglevel, ...args) { var logger = this; for (let handler of logger.handler) { - handler.log(new LogEntry(loglevel, args)) + handler.log(new LogEntry(loglevel, args)); } return logger; - } diff --git a/application/source/logging/namespace.mjs b/application/source/logging/namespace.mjs index 759ad491e..96c1508f6 100644 --- a/application/source/logging/namespace.mjs +++ b/application/source/logging/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/math/namespace.mjs b/application/source/math/namespace.mjs index 126aaa571..131fcf380 100644 --- a/application/source/math/namespace.mjs +++ b/application/source/math/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/math/random.mjs b/application/source/math/random.mjs index c62a88ab3..b1a9a13a3 100644 --- a/application/source/math/random.mjs +++ b/application/source/math/random.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getGlobal} from '../types/global.mjs'; +import { getGlobal } from "../types/global.mjs"; -export {random} +export { random }; /** * this function uses crypt and returns a random number. @@ -24,8 +24,7 @@ export {random} * @since 1.0.0 * @copyright schukai GmbH */ - function random(min, max) { - +function random(min, max) { if (min === undefined) { min = 0; } @@ -38,7 +37,6 @@ export {random} } return Math.round(create(min, max)); - } /** @@ -47,9 +45,11 @@ export {random} */ var MAX = 1000000000; -Math.log2 = Math.log2 || function (n) { - return Math.log(n) / Math.log(2); -}; +Math.log2 = + Math.log2 || + function (n) { + return Math.log(n) / Math.log(2); + }; /** * @@ -65,21 +65,21 @@ function create(min, max) { let crypt; let globalReference = getGlobal(); - crypt = globalReference?.['crypto'] || globalReference?.['msCrypto'] || globalReference?.['crypto'] || undefined; + crypt = globalReference?.["crypto"] || globalReference?.["msCrypto"] || globalReference?.["crypto"] || undefined; if (typeof crypt === "undefined") { - throw new Error("missing crypt") + throw new Error("missing crypt"); } let rval = 0; const range = max - min; if (range < 2) { - throw new Error('the distance is too small to create a random number.') + throw new Error("the distance is too small to create a random number."); } const bitsNeeded = Math.ceil(Math.log2(range)); if (bitsNeeded > 53) { - throw new Error("we cannot generate numbers larger than 53 bits."); + throw new Error("we cannot generate numbers larger than 53 bits."); } const bytesNeeded = Math.ceil(bitsNeeded / 8); const mask = Math.pow(2, bitsNeeded) - 1; @@ -102,7 +102,6 @@ function create(min, max) { if (rval < min) { rval += min; } - - return rval; + return rval; } diff --git a/application/source/monster.mjs b/application/source/monster.mjs index b10bb8e4e..8ad827468 100644 --- a/application/source/monster.mjs +++ b/application/source/monster.mjs @@ -14,30 +14,49 @@ */ // development/script/grep-exports.cjs -export {IsObject} from "./constraints/isobject.mjs" -export {Invalid} from "./constraints/invalid.mjs" -export {AndOperator} from "./constraints/andoperator.mjs" -export {OrOperator} from "./constraints/oroperator.mjs" -export {AbstractConstraint} from "./constraints/abstract.mjs" -export {IsArray} from "./constraints/isarray.mjs" -export {AbstractOperator} from "./constraints/abstractoperator.mjs" -export {Valid} from "./constraints/valid.mjs" -export {Logger, ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF} from "./logging/logger.mjs" -export {LogEntry} from "./logging/logentry.mjs" -export {ConsoleHandler} from "./logging/handler/console.mjs" -export {Handler} from "./logging/handler.mjs" -export {Formatter} from "./text/formatter.mjs" -export {Stylesheet} from "./dom/resource/link/stylesheet.mjs" -export {Data} from "./dom/resource/data.mjs" -export {Link} from "./dom/resource/link.mjs" -export {Script} from "./dom/resource/script.mjs" -export {Updater, addObjectWithUpdaterToElement} from "./dom/updater.mjs" -export {CustomControl} from "./dom/customcontrol.mjs" -export {getLocaleOfDocument} from "./dom/locale.mjs" -export {Theme, getDocumentTheme} from "./dom/theme.mjs" -export {Resource, KEY_DOCUMENT, KEY_QUERY, referenceSymbol} from "./dom/resource.mjs" -export {ResourceManager} from "./dom/resourcemanager.mjs" -export {getDocument, getWindow, getDocumentFragmentFromString} from "./dom/util.mjs" +export { IsObject } from "./constraints/isobject.mjs"; +export { Invalid } from "./constraints/invalid.mjs"; +export { AndOperator } from "./constraints/andoperator.mjs"; +export { OrOperator } from "./constraints/oroperator.mjs"; +export { AbstractConstraint } from "./constraints/abstract.mjs"; +export { IsArray } from "./constraints/isarray.mjs"; +export { AbstractOperator } from "./constraints/abstractoperator.mjs"; +export { Valid } from "./constraints/valid.mjs"; +export { + Logger, + ALL, + TRACE, + DEBUG, + INFO, + WARN, + ERROR, + FATAL, + OFF, +} from "./logging/logger.mjs"; +export { LogEntry } from "./logging/logentry.mjs"; +export { ConsoleHandler } from "./logging/handler/console.mjs"; +export { Handler } from "./logging/handler.mjs"; +export { Formatter } from "./text/formatter.mjs"; +export { Stylesheet } from "./dom/resource/link/stylesheet.mjs"; +export { Data } from "./dom/resource/data.mjs"; +export { Link } from "./dom/resource/link.mjs"; +export { Script } from "./dom/resource/script.mjs"; +export { Updater, addObjectWithUpdaterToElement } from "./dom/updater.mjs"; +export { CustomControl } from "./dom/customcontrol.mjs"; +export { getLocaleOfDocument } from "./dom/locale.mjs"; +export { Theme, getDocumentTheme } from "./dom/theme.mjs"; +export { + Resource, + KEY_DOCUMENT, + KEY_QUERY, + referenceSymbol, +} from "./dom/resource.mjs"; +export { ResourceManager } from "./dom/resourcemanager.mjs"; +export { + getDocument, + getWindow, + getDocumentFragmentFromString, +} from "./dom/util.mjs"; export { DEFAULT_THEME, ATTRIBUTE_PREFIX, @@ -91,17 +110,16 @@ export { ATTRIBUTE_EXPORTPARTS, ATTRIBUTE_HIDDEN, objectUpdaterLinkSymbol, - customElementUpdaterLinkSymbol - -} from "./dom/constants.mjs" + customElementUpdaterLinkSymbol, +} from "./dom/constants.mjs"; export { CustomElement, initMethodSymbol, assembleMethodSymbol, attributeObserverSymbol, registerCustomElement, - getSlottedElements -} from "./dom/customelement.mjs" + getSlottedElements, +} from "./dom/customelement.mjs"; export { findClosestObjectLink, addToObjectLink, @@ -115,46 +133,54 @@ export { replaceAttributeToken, clearAttributeTokens, findClosestByAttribute, - findClosestByClass -} from "./dom/attributes.mjs" -export {fireEvent, fireCustomEvent, findTargetElementFromEvent} from "./dom/events.mjs" -export {Factory} from "./dom/worker/factory.mjs" -export {Template} from "./dom/template.mjs" -export {domReady, windowReady} from "./dom/ready.mjs" -export {FocusManager} from "./dom/focusmanager.mjs" -export {ATTRIBUTEPREFIX, Assembler} from "./dom/assembler.mjs" -export {Translations} from "./i18n/translations.mjs" -export {Locale, parseLocale} from "./i18n/locale.mjs" -export {Formatter as I18nFormatter} from "./i18n/formatter.mjs" -export {Fetch} from "./i18n/providers/fetch.mjs" -export {Provider} from "./i18n/provider.mjs" -export {Message} from "./net/webconnect/message.mjs" -export {WebConnect as NetWebConnect} from "./net/webconnect.mjs" + findClosestByClass, +} from "./dom/attributes.mjs"; +export { + fireEvent, + fireCustomEvent, + findTargetElementFromEvent, +} from "./dom/events.mjs"; +export { Factory } from "./dom/worker/factory.mjs"; +export { Template } from "./dom/template.mjs"; +export { domReady, windowReady } from "./dom/ready.mjs"; +export { FocusManager } from "./dom/focusmanager.mjs"; +export { ATTRIBUTEPREFIX, Assembler } from "./dom/assembler.mjs"; +export { Translations } from "./i18n/translations.mjs"; +export { Locale, parseLocale } from "./i18n/locale.mjs"; +export { Formatter as I18nFormatter } from "./i18n/formatter.mjs"; +export { Fetch } from "./i18n/providers/fetch.mjs"; +export { Provider } from "./i18n/provider.mjs"; +export { Message } from "./net/webconnect/message.mjs"; +export { WebConnect as NetWebConnect } from "./net/webconnect.mjs"; export { internalSymbol, internalStateSymbol, - instanceSymbol -} from "./constants.mjs" -export {MediaType, parseMediaType} from "./types/mediatype.mjs" -export {typeOf} from "./types/typeof.mjs" -export {ObserverList} from "./types/observerlist.mjs" -export {RandomID} from "./types/randomid.mjs" -export {ObservableQueue} from "./types/observablequeue.mjs" -export {UUID} from "./types/uuid.mjs" -export {Observer} from "./types/observer.mjs" -export {TokenList} from "./types/tokenlist.mjs" -export {Queue} from "./types/queue.mjs" -export {Stack} from "./types/stack.mjs" -export {toBinary, fromBinary} from "./types/binary.mjs" -export {BaseWithOptions} from "./types/basewithoptions.mjs" -export {escapeString} from "./types/regex.mjs" -export {ProxyObserver} from "./types/proxyobserver.mjs" -export {NodeList} from "./types/nodelist.mjs" -export {Version, getMonsterVersion} from "./types/version.mjs" -export {Node} from "./types/node.mjs" -export {NodeRecursiveIterator} from "./types/noderecursiveiterator.mjs" -export {getGlobal, getGlobalObject, getGlobalFunction} from "./types/global.mjs" -export {DataUrl, parseDataURL} from "./types/dataurl.mjs" + instanceSymbol, +} from "./constants.mjs"; +export { MediaType, parseMediaType } from "./types/mediatype.mjs"; +export { typeOf } from "./types/typeof.mjs"; +export { ObserverList } from "./types/observerlist.mjs"; +export { RandomID } from "./types/randomid.mjs"; +export { ObservableQueue } from "./types/observablequeue.mjs"; +export { UUID } from "./types/uuid.mjs"; +export { Observer } from "./types/observer.mjs"; +export { TokenList } from "./types/tokenlist.mjs"; +export { Queue } from "./types/queue.mjs"; +export { Stack } from "./types/stack.mjs"; +export { toBinary, fromBinary } from "./types/binary.mjs"; +export { BaseWithOptions } from "./types/basewithoptions.mjs"; +export { escapeString } from "./types/regex.mjs"; +export { ProxyObserver } from "./types/proxyobserver.mjs"; +export { NodeList } from "./types/nodelist.mjs"; +export { Version, getMonsterVersion } from "./types/version.mjs"; +export { Node } from "./types/node.mjs"; +export { NodeRecursiveIterator } from "./types/noderecursiveiterator.mjs"; +export { + getGlobal, + getGlobalObject, + getGlobalFunction, +} from "./types/global.mjs"; +export { DataUrl, parseDataURL } from "./types/dataurl.mjs"; export { validateIterable, validatePrimitive, @@ -165,39 +191,47 @@ export { validateArray, validateSymbol, validateFunction, - validateInteger -} from "./types/validate.mjs" -export {UniqueQueue} from "./types/uniquequeue.mjs" -export {Base} from "./types/base.mjs" + validateInteger, +} from "./types/validate.mjs"; +export { UniqueQueue } from "./types/uniquequeue.mjs"; +export { Base } from "./types/base.mjs"; export { - isIterable, isPrimitive, isSymbol, isBoolean, isString, isObject, isInstance, isArray, isFunction, isInteger -} from "./types/is.mjs" -export {ID} from "./types/id.mjs" -export {trimSpaces} from "./util/trimspaces.mjs" -export {DeadMansSwitch} from "./util/deadmansswitch.mjs" -export {deepFreeze} from "./util/freeze.mjs" -export {Comparator} from "./util/comparator.mjs" -export {clone} from "./util/clone.mjs" -export {Processing} from "./util/processing.mjs" -export {extend} from "./data/extend.mjs" -export {Pipe} from "./data/pipe.mjs" -export {buildMap, PARENT, assembleParts} from "./data/buildmap.mjs" -export {Datasource} from "./data/datasource.mjs" -export {buildTree} from "./data/buildtree.mjs" -export {Transformer} from "./data/transformer.mjs" -export {Pathfinder, DELIMITER, WILDCARD} from "./data/pathfinder.mjs" -export {diff} from "./data/diff.mjs" -export {Server} from "./data/datasource/server.mjs" -export {SessionStorage} from "./data/datasource/storage/sessionstorage.mjs" -export {LocalStorage} from "./data/datasource/storage/localstorage.mjs" -export {RestAPI} from "./data/datasource/server/restapi.mjs" -export {WebConnect} from "./data/datasource/server/webconnect.mjs" -export {WriteError} from "./data/datasource/server/restapi/writeerror.mjs" -export {Storage, storageObjectSymbol} from "./data/datasource/storage.mjs" -export {random} from "./math/random.mjs" + isIterable, + isPrimitive, + isSymbol, + isBoolean, + isString, + isObject, + isInstance, + isArray, + isFunction, + isInteger, +} from "./types/is.mjs"; +export { ID } from "./types/id.mjs"; +export { trimSpaces } from "./util/trimspaces.mjs"; +export { DeadMansSwitch } from "./util/deadmansswitch.mjs"; +export { deepFreeze } from "./util/freeze.mjs"; +export { Comparator } from "./util/comparator.mjs"; +export { clone } from "./util/clone.mjs"; +export { Processing } from "./util/processing.mjs"; +export { extend } from "./data/extend.mjs"; +export { Pipe } from "./data/pipe.mjs"; +export { buildMap, PARENT, assembleParts } from "./data/buildmap.mjs"; +export { Datasource } from "./data/datasource.mjs"; +export { buildTree } from "./data/buildtree.mjs"; +export { Transformer } from "./data/transformer.mjs"; +export { Pathfinder, DELIMITER, WILDCARD } from "./data/pathfinder.mjs"; +export { diff } from "./data/diff.mjs"; +export { Server } from "./data/datasource/server.mjs"; +export { SessionStorage } from "./data/datasource/storage/sessionstorage.mjs"; +export { LocalStorage } from "./data/datasource/storage/localstorage.mjs"; +export { RestAPI } from "./data/datasource/server/restapi.mjs"; +export { WebConnect } from "./data/datasource/server/webconnect.mjs"; +export { WriteError } from "./data/datasource/server/restapi/writeerror.mjs"; +export { Storage, storageObjectSymbol } from "./data/datasource/storage.mjs"; +export { random } from "./math/random.mjs"; - -export {Monster} +export { Monster }; /** * This class has no other purpose than to exist. @@ -207,6 +241,4 @@ export {Monster} * @copyright schukai GmbH * @memberOf Monster */ -class Monster { - -} +class Monster {} diff --git a/application/source/net/namespace.mjs b/application/source/net/namespace.mjs index d1f766470..4a292ce0c 100644 --- a/application/source/net/namespace.mjs +++ b/application/source/net/namespace.mjs @@ -3,8 +3,6 @@ * SPDX-License-Identifier: AGPL-3.0 */ - - /** * In this namespace you will find classes and methods for handling connections. * @@ -12,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/net/webconnect.mjs b/application/source/net/webconnect.mjs index a497ded29..d46b1f4da 100644 --- a/application/source/net/webconnect.mjs +++ b/application/source/net/webconnect.mjs @@ -5,14 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {instanceSymbol} from "../constants.mjs"; -import {isInteger, isString, isObject} from "../types/is.mjs"; -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {ObservableQueue} from "../types/observablequeue.mjs"; -import {Message} from "./webconnect/message.mjs"; +import { instanceSymbol } from "../constants.mjs"; +import { isInteger, isString, isObject } from "../types/is.mjs"; +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { ObservableQueue } from "../types/observablequeue.mjs"; +import { Message } from "./webconnect/message.mjs"; - -export {WebConnect} +export { WebConnect }; /** * @private @@ -57,7 +56,7 @@ const connectionStatusCode = { 1009: "Message too big", 1010: "Mandatory extension", 1011: "Internal server error", - 1015: "TLS handshake" + 1015: "TLS handshake", }; /** @@ -68,15 +67,15 @@ const connectionStatusCode = { function connectServer(resolve, reject) { const self = this; - const url = self.getOption('url'); + const url = self.getOption("url"); if (!url) { - reject('No url defined for webconnect.'); + reject("No url defined for webconnect."); return; } let promiseAllredyResolved = false; - let connectionTimeout = self.getOption('connection.timeout'); + let connectionTimeout = self.getOption("connection.timeout"); if (!isInteger(connectionTimeout) || connectionTimeout < 100) { connectionTimeout = 5000; } @@ -88,11 +87,11 @@ function connectServer(resolve, reject) { reject(new Error("Connection timeout")); }, connectionTimeout); - let reconnectTimeout = self.getOption('connection.reconnect.timeout'); + let reconnectTimeout = self.getOption("connection.reconnect.timeout"); if (!isInteger(reconnectTimeout) || reconnectTimeout < 1000) reconnectTimeout = 1000; - let reconnectAttempts = self.getOption('connection.reconnect.attempts'); + let reconnectAttempts = self.getOption("connection.reconnect.attempts"); if (!isInteger(reconnectAttempts) || reconnectAttempts < 1) reconnectAttempts = 1; - let reconnectEnabled = self.getOption('connection.reconnect.enabled'); + let reconnectEnabled = self.getOption("connection.reconnect.enabled"); if (reconnectEnabled !== true) reconnectEnabled = false; self[manualCloseSymbol] = false; @@ -108,7 +107,7 @@ function connectServer(resolve, reject) { if (event.data instanceof Blob) { const reader = new FileReader(); reader.addEventListener("loadend", function () { - self[receiveQueueSymbol].add(new Message(reader.result)) + self[receiveQueueSymbol].add(new Message(reader.result)); }); reader.readAsText(new Message(event.data)); } else { @@ -118,14 +117,13 @@ function connectServer(resolve, reject) { self[connectionSymbol].socket.onopen = function () { self[connectionSymbol].reconnectCounter = 0; - if (typeof resolve === 'function' && !promiseAllredyResolved) { + if (typeof resolve === "function" && !promiseAllredyResolved) { promiseAllredyResolved = true; resolve(); } }; self[connectionSymbol].socket.close = function (event) { - if (self[manualCloseSymbol]) { self[manualCloseSymbol] = false; return; @@ -136,22 +134,19 @@ function connectServer(resolve, reject) { self.connect(); }, reconnectTimeout * this[connectionSymbol].reconnectCounter); } - }; self[connectionSymbol].socket.onerror = (error) => { - if (reconnectEnabled && self[connectionSymbol].reconnectCounter < reconnectAttempts) { setTimeout(() => { self.connect(); }, reconnectTimeout * this[connectionSymbol].reconnectCounter); } else { - if (typeof reject === 'function' && !promiseAllredyResolved) { + if (typeof reject === "function" && !promiseAllredyResolved) { promiseAllredyResolved = true; reject(error); } } - }; } @@ -166,17 +161,15 @@ function connectServer(resolve, reject) { * @summary The LocalStorage class encapsulates the access to data objects. */ class WebConnect extends BaseWithOptions { - /** * * @param {Object} [options] options contains definitions for the webconnect. */ constructor(options) { - if (isString(options)) { - options = {url: options}; + options = { url: options }; } - + super(options); this[receiveQueueSymbol] = new ObservableQueue(); @@ -232,8 +225,8 @@ class WebConnect extends BaseWithOptions { timeout: 1000, attempts: 1, enabled: false, - } - } + }, + }, }); } @@ -245,12 +238,12 @@ class WebConnect extends BaseWithOptions { * @returns {Promise} * @see https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1 */ - close(statusCode, reason ) { + close(statusCode, reason) { if (!isInteger(statusCode) || statusCode < 1000 || statusCode > 4999) { statusCode = 1000; } if (!isString(reason)) { - reason = ''; + reason = ""; } return new Promise((resolve, reject) => { @@ -264,12 +257,11 @@ class WebConnect extends BaseWithOptions { } resolve(); }); - } /** * Polls the receive queue for new messages. - * + * * @returns {Message} */ poll() { @@ -277,8 +269,8 @@ class WebConnect extends BaseWithOptions { } /** - * Are there any messages in the receive queue? - * + * Are there any messages in the receive queue? + * * @returns {boolean} */ dataReceived() { @@ -287,7 +279,7 @@ class WebConnect extends BaseWithOptions { /** * Get Message from the receive queue, but do not remove it. - * + * * @returns {Object} */ peek() { @@ -332,15 +324,12 @@ class WebConnect extends BaseWithOptions { const self = this; return new Promise((resolve, reject) => { - if (self[connectionSymbol].socket.readyState !== 1) { - reject('the socket is not ready'); + reject("the socket is not ready"); } - self[connectionSymbol].socket.send(JSON.stringify(message)) + self[connectionSymbol].socket.send(JSON.stringify(message)); resolve(); }); } - } - diff --git a/application/source/net/webconnect/message.mjs b/application/source/net/webconnect/message.mjs index e198ed9d8..85ea8535e 100644 --- a/application/source/net/webconnect/message.mjs +++ b/application/source/net/webconnect/message.mjs @@ -5,10 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from "../../types/base.mjs"; -import {validateObject, validateString} from "../../types/validate.mjs"; +import { Base } from "../../types/base.mjs"; +import { validateObject, validateString } from "../../types/validate.mjs"; -export {Message} +export { Message }; const dataSymbol = Symbol("@@data"); @@ -22,7 +22,6 @@ const dataSymbol = Symbol("@@data"); * @summary The Message class encapsulates a WebSocket message. */ class Message extends Base { - /** * @param {Object} data * @throws {TypeError} value is not a object @@ -31,10 +30,10 @@ class Message extends Base { super(); this[dataSymbol] = validateObject(data); } - + /** * Returns the raw message. - * + * * @returns {object} */ getData() { @@ -57,5 +56,4 @@ class Message extends Base { validateString(json); return new Message(JSON.parse(json)); } - -} \ No newline at end of file +} diff --git a/application/source/net/webconnect/namespace.mjs b/application/source/net/webconnect/namespace.mjs index ba98b2c10..da5fc351f 100644 --- a/application/source/net/webconnect/namespace.mjs +++ b/application/source/net/webconnect/namespace.mjs @@ -3,8 +3,6 @@ * SPDX-License-Identifier: AGPL-3.0 */ - - /** * In this namespace you will find classes and methods for handling data. * @@ -12,4 +10,4 @@ * @memberOf Monster.Net * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/text/formatter.mjs b/application/source/text/formatter.mjs index 72ca51782..1f1d797ff 100644 --- a/application/source/text/formatter.mjs +++ b/application/source/text/formatter.mjs @@ -5,46 +5,45 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {extend} from "../data/extend.mjs"; -import {Pipe} from "../data/pipe.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { extend } from "../data/extend.mjs"; +import { Pipe } from "../data/pipe.mjs"; -import {BaseWithOptions} from "../types/basewithoptions.mjs"; -import {isObject, isString} from "../types/is.mjs"; -import {validateArray, validateString} from "../types/validate.mjs"; +import { BaseWithOptions } from "../types/basewithoptions.mjs"; +import { isObject, isString } from "../types/is.mjs"; +import { validateArray, validateString } from "../types/validate.mjs"; -export {Formatter} +export { Formatter }; /** * @private * @type {symbol} */ -const internalObjectSymbol = Symbol('internalObject'); +const internalObjectSymbol = Symbol("internalObject"); /** * @private * @type {symbol} */ -const watchdogSymbol = Symbol('watchdog'); +const watchdogSymbol = Symbol("watchdog"); /** * @private * @type {symbol} */ -const markerOpenIndexSymbol = Symbol('markerOpenIndex'); +const markerOpenIndexSymbol = Symbol("markerOpenIndex"); /** * @private * @type {symbol} */ -const markerCloseIndexSymbol = Symbol('markercloseIndex'); +const markerCloseIndexSymbol = Symbol("markercloseIndex"); /** * @private * @type {symbol} */ -const workingDataSymbol = Symbol('workingData'); - +const workingDataSymbol = Symbol("workingData"); /** * Messages can be formatted with the formatter. To do this, an object with the values must be passed to the formatter. The message can then contain placeholders. @@ -109,8 +108,7 @@ const workingDataSymbol = Symbol('workingData'); * @copyright schukai GmbH * @memberOf Monster.Text */ - class Formatter extends BaseWithOptions { - +class Formatter extends BaseWithOptions { /** * Default values for the markers are `${` and `}` * @@ -119,7 +117,7 @@ const workingDataSymbol = Symbol('workingData'); */ constructor(object, options) { super(options); - this[internalObjectSymbol] = object || {} + this[internalObjectSymbol] = object || {}; this[markerOpenIndexSymbol] = 0; this[markerCloseIndexSymbol] = 0; } @@ -136,18 +134,17 @@ const workingDataSymbol = Symbol('workingData'); get defaults() { return extend({}, super.defaults, { marker: { - open: ['${'], - close: ['}'] + open: ["${"], + close: ["}"], }, parameter: { - delimiter: '::', - assignment: '=' + delimiter: "::", + assignment: "=", }, callbacks: {}, - }) + }); } - /** * Set new Parameter Character * @@ -166,13 +163,12 @@ const workingDataSymbol = Symbol('workingData'); * @throws {TypeError} value is not a string */ setParameterChars(delimiter, assignment) { - if (delimiter !== undefined) { - this[internalSymbol]['parameter']['delimiter'] = validateString(delimiter); + this[internalSymbol]["parameter"]["delimiter"] = validateString(delimiter); } if (assignment !== undefined) { - this[internalSymbol]['parameter']['assignment'] = validateString(assignment); + this[internalSymbol]["parameter"]["assignment"] = validateString(assignment); } return this; @@ -196,7 +192,6 @@ const workingDataSymbol = Symbol('workingData'); * @throws {TypeError} value is not a string */ setMarker(open, close) { - if (close === undefined) { close = open; } @@ -204,8 +199,8 @@ const workingDataSymbol = Symbol('workingData'); if (isString(open)) open = [open]; if (isString(close)) close = [close]; - this[internalSymbol]['marker']['open'] = validateArray(open); - this[internalSymbol]['marker']['close'] = validateArray(close); + this[internalSymbol]["marker"]["open"] = validateArray(open); + this[internalSymbol]["marker"]["close"] = validateArray(close); return this; } @@ -223,7 +218,6 @@ const workingDataSymbol = Symbol('workingData'); this[workingDataSymbol] = {}; return format.call(this, text); } - } /** @@ -235,28 +229,28 @@ function format(text) { self[watchdogSymbol]++; if (this[watchdogSymbol] > 20) { - throw new Error('too deep nesting') + throw new Error("too deep nesting"); } - let openMarker = self[internalSymbol]['marker']['open']?.[this[markerOpenIndexSymbol]]; - let closeMarker = self[internalSymbol]['marker']['close']?.[this[markerCloseIndexSymbol]]; + let openMarker = self[internalSymbol]["marker"]["open"]?.[this[markerOpenIndexSymbol]]; + let closeMarker = self[internalSymbol]["marker"]["close"]?.[this[markerCloseIndexSymbol]]; // contains no placeholders if (text.indexOf(openMarker) === -1 || text.indexOf(closeMarker) === -1) { return text; } - let result = tokenize.call(this, validateString(text), openMarker, closeMarker) + let result = tokenize.call(this, validateString(text), openMarker, closeMarker); - if (self[internalSymbol]['marker']['open']?.[this[markerOpenIndexSymbol] + 1]) { + if (self[internalSymbol]["marker"]["open"]?.[this[markerOpenIndexSymbol] + 1]) { this[markerOpenIndexSymbol]++; } - if (self[internalSymbol]['marker']['close']?.[this[markerCloseIndexSymbol] + 1]) { + if (self[internalSymbol]["marker"]["close"]?.[this[markerCloseIndexSymbol] + 1]) { this[markerCloseIndexSymbol]++; } - result = format.call(self, result) + result = format.call(self, result); return result; } @@ -273,20 +267,19 @@ function tokenize(text, openMarker, closeMarker) { let formatted = []; - const parameterAssignment = self[internalSymbol]['parameter']['assignment'] - const parameterDelimiter = self[internalSymbol]['parameter']['delimiter'] - const callbacks = self[internalSymbol]['callbacks']; + const parameterAssignment = self[internalSymbol]["parameter"]["assignment"]; + const parameterDelimiter = self[internalSymbol]["parameter"]["delimiter"]; + const callbacks = self[internalSymbol]["callbacks"]; while (true) { - let startIndex = text.indexOf(openMarker); - // no marker + // no marker if (startIndex === -1) { formatted.push(text); break; } else if (startIndex > 0) { - formatted.push(text.substring(0, startIndex)) - text = text.substring(startIndex) + formatted.push(text.substring(0, startIndex)); + text = text.substring(startIndex); } let endIndex = text.substring(openMarker.length).indexOf(closeMarker); @@ -296,14 +289,14 @@ function tokenize(text, openMarker, closeMarker) { insideStartIndex += openMarker.length; if (insideStartIndex < endIndex) { let result = tokenize.call(self, text.substring(insideStartIndex), openMarker, closeMarker); - text = text.substring(0, insideStartIndex) + result + text = text.substring(0, insideStartIndex) + result; endIndex = text.substring(openMarker.length).indexOf(closeMarker); if (endIndex !== -1) endIndex += openMarker.length; } } if (endIndex === -1) { - throw new Error("syntax error in formatter template") + throw new Error("syntax error in formatter template"); } let key = text.substring(openMarker.length, endIndex); @@ -317,15 +310,13 @@ function tokenize(text, openMarker, closeMarker) { self[workingDataSymbol][k] = v; } - const t1 = key.split('|').shift().trim(); // pipe symbol - const t2 = t1.split('::').shift().trim(); // key value delimiter - const t3 = t2.split('.').shift().trim(); // path delimiter - let prefix = self[workingDataSymbol]?.[t3] ? 'path:' : 'static:'; + const t1 = key.split("|").shift().trim(); // pipe symbol + const t2 = t1.split("::").shift().trim(); // key value delimiter + const t3 = t2.split(".").shift().trim(); // path delimiter + let prefix = self[workingDataSymbol]?.[t3] ? "path:" : "static:"; let command = ""; - if (prefix && key.indexOf(prefix) !== 0 - && key.indexOf('path:') !== 0 - && key.indexOf('static:') !== 0) { + if (prefix && key.indexOf(prefix) !== 0 && key.indexOf("path:") !== 0 && key.indexOf("static:") !== 0) { command = prefix; } @@ -342,8 +333,7 @@ function tokenize(text, openMarker, closeMarker) { formatted.push(validateString(pipe.run(self[workingDataSymbol]))); text = text.substring(endIndex + closeMarker.length); - } - return formatted.join(''); + return formatted.join(""); } diff --git a/application/source/types/base.mjs b/application/source/types/base.mjs index 3ca5e4279..09d4dcec5 100644 --- a/application/source/types/base.mjs +++ b/application/source/types/base.mjs @@ -5,24 +5,23 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {instanceSymbol} from "../constants.mjs"; - -export {Base} +import { instanceSymbol } from "../constants.mjs"; +export { Base }; /** * This is the base class from which all monster classes are derived. - * + * * This class has besides a `toString` which returns the json representation of the object * also a functionality to check if an object is an instance of a class. - * - * Therefor the class has a static method ` [Symbol.hasInstance](that)` which returns true if the object - * is an instance of the class. + * + * Therefor the class has a static method ` [Symbol.hasInstance](that)` which returns true if the object + * is an instance of the class. * F * @see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance](developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance) * * Derived classes should implement a static getter `instanceSymbol` which returns a unique symbol. - * + * * ```javascript * static get [instanceSymbol]() { * return Symbol.for("@schukai/monster/types/base"); @@ -37,14 +36,13 @@ export {Base} * @memberOf Monster.Types */ class Base extends Object { - /** * * @returns {string} */ toString() { return JSON.stringify(this); - }; + } /** * This method is called by the `instanceof` operator. @@ -62,13 +60,16 @@ class Base extends Object { * @since 2.1.0 */ static [Symbol.hasInstance](that) { - if (that === undefined || that === null || (typeof that !== "object" && typeof that !== "function")) { return false; } - const thatClass = Object.getPrototypeOf(that) - if (thatClass === undefined || thatClass === null || (typeof thatClass !== "object" && typeof thatClass !== "function")) { + const thatClass = Object.getPrototypeOf(that); + if ( + thatClass === undefined || + thatClass === null || + (typeof thatClass !== "object" && typeof thatClass !== "function") + ) { return false; } @@ -76,24 +77,20 @@ class Base extends Object { return true; } - // this call the static method of the super class, if there is one return super[Symbol.hasInstance](that); - } - } /** * this function checks if the class has a static getter `instanceSymbol` and if the value of this getter is equal to the - * + * * @private * @param obj * @returns {boolean|any|boolean} * @since 2.1.0 */ function checkInstanceSymbol(obj) { - if (this.hasOwnProperty(instanceSymbol) === false) { return false; } @@ -109,23 +106,16 @@ function checkInstanceSymbol(obj) { const symbol = proto[instanceSymbol]; if (symbol === undefined) { - if (obj.__proto__) { return checkInstanceSymbol(obj.__proto__); } else { return false; } - } if (symbol === this[instanceSymbol]) { return true; } - - return checkInstanceSymbol.apply(this, [obj.__proto__]); - + return checkInstanceSymbol.apply(this, [obj.__proto__]); } - - - diff --git a/application/source/types/basewithoptions.mjs b/application/source/types/basewithoptions.mjs index 0812fc86d..cb0b5469d 100644 --- a/application/source/types/basewithoptions.mjs +++ b/application/source/types/basewithoptions.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {extend} from "../data/extend.mjs"; -import {Pathfinder} from "../data/pathfinder.mjs"; -import {Base} from "./base.mjs"; -import {validateObject} from "./validate.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { extend } from "../data/extend.mjs"; +import { Pathfinder } from "../data/pathfinder.mjs"; +import { Base } from "./base.mjs"; +import { validateObject } from "./validate.mjs"; -export {BaseWithOptions} +export { BaseWithOptions }; /** * This is the base class with options from which some monster classes are derived. @@ -28,7 +28,6 @@ export {BaseWithOptions} * @memberOf Monster.Types */ class BaseWithOptions extends Base { - /** * * @param {object} options @@ -41,7 +40,6 @@ class BaseWithOptions extends Base { } this[internalSymbol] = extend({}, this.defaults, validateObject(options)); - } /** @@ -61,7 +59,7 @@ class BaseWithOptions extends Base { * @return {object} */ get defaults() { - return {} + return {}; } /** @@ -77,13 +75,9 @@ class BaseWithOptions extends Base { try { value = new Pathfinder(this[internalSymbol]).getVia(path); - } catch (e) { - - } + } catch (e) {} if (value === undefined) return defaultValue; return value; } - - } diff --git a/application/source/types/binary.mjs b/application/source/types/binary.mjs index 3d1c7c402..a4970fd69 100644 --- a/application/source/types/binary.mjs +++ b/application/source/types/binary.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {validateString} from "./validate.mjs"; +import { validateString } from "./validate.mjs"; -export {toBinary, fromBinary} +export { toBinary, fromBinary }; /** * You can call the function via the monster namespace `Monster.Types.toBinary()`. @@ -26,7 +26,7 @@ function toBinary(string) { } const charCodes = new Uint8Array(codeUnits.buffer); - let result = ''; + let result = ""; for (let i = 0; i < charCodes.byteLength; i++) { result += String.fromCharCode(charCodes[i]); @@ -51,10 +51,9 @@ function fromBinary(binary) { bytes[i] = binary.charCodeAt(i); } const charCodes = new Uint16Array(bytes.buffer); - let result = ''; + let result = ""; for (let i = 0; i < charCodes.length; i++) { result += String.fromCharCode(charCodes[i]); } return result; } - diff --git a/application/source/types/dataurl.mjs b/application/source/types/dataurl.mjs index b67536a0d..aff702e5c 100644 --- a/application/source/types/dataurl.mjs +++ b/application/source/types/dataurl.mjs @@ -5,18 +5,18 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from "./base.mjs"; -import {isString} from "./is.mjs"; -import {MediaType, parseMediaType} from "./mediatype.mjs"; -import {validateBoolean, validateInstance, validateString} from "./validate.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {DataUrl, parseDataURL} +import { Base } from "./base.mjs"; +import { isString } from "./is.mjs"; +import { MediaType, parseMediaType } from "./mediatype.mjs"; +import { validateBoolean, validateInstance, validateString } from "./validate.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { DataUrl, parseDataURL }; /** * @private * @type {symbol} */ -const internal = Symbol('internal'); +const internal = Symbol("internal"); /** * You can create an object via the monster namespace `new Monster.Types.DataUrl()`. @@ -29,7 +29,6 @@ const internal = Symbol('internal'); * @see https://datatracker.ietf.org/doc/html/rfc2397 */ class DataUrl extends Base { - /** * * @param {String} content @@ -46,10 +45,8 @@ class DataUrl extends Base { this[internal] = { content: validateString(content), mediatype: validateInstance(mediatype, MediaType), - base64: validateBoolean(base64 === undefined ? true : base64) - } - - + base64: validateBoolean(base64 === undefined ? true : base64), + }; } /** @@ -61,7 +58,6 @@ class DataUrl extends Base { return Symbol.for("@schukai/monster/types/data-url"); } - get content() { return this[internal].base64 ? atob(this[internal].content) : this[internal].content; } @@ -70,14 +66,12 @@ class DataUrl extends Base { return this[internal].mediatype; } - /** * * @return {string} * @see https://datatracker.ietf.org/doc/html/rfc2397 */ toString() { - let content = this[internal].content; if (this[internal].base64 === true) { @@ -88,7 +82,6 @@ class DataUrl extends Base { return `data:${this[internal].mediatype.toString()}${content}`; } - } /** @@ -112,31 +105,30 @@ class DataUrl extends Base { * @memberOf Monster.Types */ function parseDataURL(dataurl) { - validateString(dataurl); dataurl = dataurl.trim(); - if (dataurl.substring(0, 5) !== 'data:') { - throw new TypeError('incorrect or missing data protocol') + if (dataurl.substring(0, 5) !== "data:") { + throw new TypeError("incorrect or missing data protocol"); } dataurl = dataurl.substring(5); - let p = dataurl.indexOf(','); + let p = dataurl.indexOf(","); if (p === -1) { - throw new TypeError('malformed data url') + throw new TypeError("malformed data url"); } let content = dataurl.substring(p + 1); let mediatypeAndBase64 = dataurl.substring(0, p).trim(); - let mediatype = 'text/plain;charset=US-ASCII'; + let mediatype = "text/plain;charset=US-ASCII"; let base64Flag = false; if (mediatypeAndBase64 !== "") { mediatype = mediatypeAndBase64; - if (mediatypeAndBase64.endsWith('base64')) { - let i = mediatypeAndBase64.lastIndexOf(';'); + if (mediatypeAndBase64.endsWith("base64")) { + let i = mediatypeAndBase64.lastIndexOf(";"); mediatype = mediatypeAndBase64.substring(0, i); base64Flag = true; } else { diff --git a/application/source/types/global.mjs b/application/source/types/global.mjs index 3ebddaa35..e5c67b037 100644 --- a/application/source/types/global.mjs +++ b/application/source/types/global.mjs @@ -1,5 +1,3 @@ - - /** * Copyright schukai GmbH and contributors 2022. All Rights Reserved. * Node module: @schukai/monster @@ -7,10 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ +import { validateFunction, validateObject, validateString } from "./validate.mjs"; -import {validateFunction, validateObject, validateString} from "./validate.mjs"; - -export {getGlobal, getGlobalObject, getGlobalFunction} +export { getGlobal, getGlobalObject, getGlobalFunction }; /** * @type {objec} @@ -23,28 +20,27 @@ let globalReference; * @throws {Error} unsupported environment. */ (function () { - - if (typeof globalThis === 'object') { + if (typeof globalThis === "object") { globalReference = globalThis; return; } - if (typeof self !== 'undefined') { + if (typeof self !== "undefined") { globalReference = self; return; - } else if (typeof window !== 'undefined') { + } else if (typeof window !== "undefined") { globalReference = window; return; } - Object.defineProperty(Object.prototype, '__monster__', { + Object.defineProperty(Object.prototype, "__monster__", { get: function () { return this; }, - configurable: true + configurable: true, }); - if (typeof __monster__ === 'object') { + if (typeof __monster__ === "object") { __monster__.globalThis = __monster__; delete Object.prototype.__monster__; @@ -53,15 +49,11 @@ let globalReference; } try { - globalReference = Function('return this')(); - } catch (e) { - - } + globalReference = Function("return this")(); + } catch (e) {} - throw new Error("unsupported environment.") - - -}()); + throw new Error("unsupported environment."); +})(); /** * Return globalThis @@ -112,7 +104,7 @@ function getGlobal() { function getGlobalObject(name) { validateString(name); let o = globalReference?.[name]; - if (typeof o === 'undefined') throw new Error(`the object ${name} is not defined`); + if (typeof o === "undefined") throw new Error(`the object ${name} is not defined`); validateObject(o); return o; } @@ -150,11 +142,7 @@ function getGlobalObject(name) { function getGlobalFunction(name) { validateString(name); let f = globalReference?.[name]; - if (typeof f === 'undefined') throw new Error(`the function ${name} is not defined`); + if (typeof f === "undefined") throw new Error(`the function ${name} is not defined`); validateFunction(f); return f; } - - - - diff --git a/application/source/types/id.mjs b/application/source/types/id.mjs index b7d726722..6aa7c1a72 100644 --- a/application/source/types/id.mjs +++ b/application/source/types/id.mjs @@ -5,16 +5,16 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {validateString} from "./validate.mjs"; +import { Base } from "./base.mjs"; +import { validateString } from "./validate.mjs"; -export {ID} +export { ID }; /** * @private * @type {Map<string, integer>} */ -let internalCounter = new Map; +let internalCounter = new Map(); /** * With the id class, sequences of ids can be created. for this purpose, an internal counter is incremented for each prefix. @@ -32,7 +32,6 @@ let internalCounter = new Map; * @summary Automatic generation of ids */ class ID extends Base { - /** * create new id with prefix * @@ -63,5 +62,4 @@ class ID extends Base { toString() { return this.id; } - } diff --git a/application/source/types/is.mjs b/application/source/types/is.mjs index 56e5cb3b3..a829c9f28 100644 --- a/application/source/types/is.mjs +++ b/application/source/types/is.mjs @@ -5,7 +5,7 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -export {isIterable, isPrimitive, isSymbol, isBoolean, isString, isObject, isInstance, isArray, isFunction, isInteger} +export { isIterable, isPrimitive, isSymbol, isBoolean, isString, isObject, isInstance, isArray, isFunction, isInteger }; /** * With this function you can check if a value is iterable. @@ -25,10 +25,9 @@ export {isIterable, isPrimitive, isSymbol, isBoolean, isString, isObject, isInst function isIterable(value) { if (value === undefined) return false; if (value === null) return false; - return typeof value?.[Symbol.iterator] === 'function'; + return typeof value?.[Symbol.iterator] === "function"; } - /** * Checks whether the value passed is a primitive (string, number, boolean, NaN, undefined, null or symbol) * @@ -51,7 +50,7 @@ function isPrimitive(value) { type = typeof value; - if (type === 'string' || type === 'number' || type === 'boolean' || type === 'symbol') { + if (type === "string" || type === "number" || type === "boolean" || type === "symbol") { return true; } @@ -72,7 +71,7 @@ function isPrimitive(value) { * @memberOf Monster.Types */ function isSymbol(value) { - return ('symbol' === typeof value) ? true : false; + return "symbol" === typeof value ? true : false; } /** @@ -89,7 +88,6 @@ function isSymbol(value) { * @memberOf Monster.Types */ function isBoolean(value) { - if (value === true || value === false) { return true; } @@ -111,7 +109,7 @@ function isBoolean(value) { * @memberOf Monster.Types */ function isString(value) { - if (value === undefined || typeof value !== 'string') { + if (value === undefined || typeof value !== "string") { return false; } return true; @@ -131,11 +129,10 @@ function isString(value) { * @memberOf Monster.Types */ function isObject(value) { - if (isArray(value)) return false; if (isPrimitive(value)) return false; - if (typeof value === 'object') { + if (typeof value === "object") { return true; } @@ -146,7 +143,7 @@ function isObject(value) { * Checks whether the value passed is a object and instance of instance. * * This method is used in the library to have consistent names. - * + * * @externalExample ../../example/types/is-7.mjs * @param {*} value * @param {*} instance @@ -159,8 +156,8 @@ function isObject(value) { function isInstance(value, instance) { if (!isObject(value)) return false; if (!isFunction(instance)) return false; - if (!instance.hasOwnProperty('prototype')) return false; - return (value instanceof instance) ? true : false; + if (!instance.hasOwnProperty("prototype")) return false; + return value instanceof instance ? true : false; } /** @@ -185,7 +182,7 @@ function isArray(value) { * Checks whether the value passed is a function * * This method is used in the library to have consistent names. - * + * * @externalExample ../../example/types/is-9.mjs * @param {*} value * @returns {boolean} @@ -198,12 +195,11 @@ function isFunction(value) { if (isArray(value)) return false; if (isPrimitive(value)) return false; - if (typeof value === 'function') { + if (typeof value === "function") { return true; } return false; - } /** @@ -222,4 +218,3 @@ function isFunction(value) { function isInteger(value) { return Number.isInteger(value); } - diff --git a/application/source/types/mediatype.mjs b/application/source/types/mediatype.mjs index e188eba44..d335937be 100644 --- a/application/source/types/mediatype.mjs +++ b/application/source/types/mediatype.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from "./base.mjs"; -import {isString} from "./is.mjs"; -import {validateArray, validateString} from "./validate.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {MediaType, parseMediaType} +import { Base } from "./base.mjs"; +import { isString } from "./is.mjs"; +import { validateArray, validateString } from "./validate.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { MediaType, parseMediaType }; /** * @private * @type {symbol} */ -const internal = Symbol('internal'); +const internal = Symbol("internal"); /** * @typedef {Object} Parameter @@ -24,7 +24,6 @@ const internal = Symbol('internal'); * @memberOf Monster.Types */ - /** * You can create an object via the monster namespace `new Monster.Types.MediaType()`. * @@ -34,7 +33,6 @@ const internal = Symbol('internal'); * @memberOf Monster.Types */ class MediaType extends Base { - /** * * @param {String} type @@ -47,14 +45,12 @@ class MediaType extends Base { this[internal] = { type: validateString(type).toLowerCase(), subtype: validateString(subtype).toLowerCase(), - parameter: [] - } + parameter: [], + }; if (parameter !== undefined) { - this[internal]['parameter'] = validateArray(parameter); + this[internal]["parameter"] = validateArray(parameter); } - - } /** @@ -66,7 +62,6 @@ class MediaType extends Base { return Symbol.for("@schukai/monster/types/media-type"); } - /** * @return {String} */ @@ -94,11 +89,9 @@ class MediaType extends Base { * @return {Map} */ get parameter() { + const result = new Map(); - const result = new Map - - this[internal]['parameter'].forEach(p => { - + this[internal]["parameter"].forEach((p) => { let value = p.value; // internally special values are partly stored with quotes, this function removes them. @@ -107,8 +100,7 @@ class MediaType extends Base { } result.set(p.key, value); - }) - + }); return result; } @@ -118,15 +110,15 @@ class MediaType extends Base { * @return {string} */ toString() { - let parameter = []; for (let a of this[internal].parameter) { parameter.push(`${a.key}=${a.value}`); } - return `${this[internal].type}/${this[internal].subtype}${(parameter.length > 0 ? `;${parameter.join(';')}` : '')}`; + return `${this[internal].type}/${this[internal].subtype}${ + parameter.length > 0 ? `;${parameter.join(";")}` : "" + }`; } - } /** @@ -166,26 +158,24 @@ class MediaType extends Base { * @memberOf Monster.Types */ function parseMediaType(mediatype) { - - const regex = /(?<type>[A-Za-z]+|\*)\/(?<subtype>([a-zA-Z0-9.\+_\-]+)|\*|)(?<parameter>\s*;\s*([a-zA-Z0-9]+)\s*(=\s*("?[A-Za-z0-9_\-]+"?))?)*/g; + const regex = + /(?<type>[A-Za-z]+|\*)\/(?<subtype>([a-zA-Z0-9.\+_\-]+)|\*|)(?<parameter>\s*;\s*([a-zA-Z0-9]+)\s*(=\s*("?[A-Za-z0-9_\-]+"?))?)*/g; const result = regex.exec(validateString(mediatype)); - const groups = result?.['groups']; + const groups = result?.["groups"]; if (groups === undefined) { - throw new TypeError('the mimetype can not be parsed') + throw new TypeError("the mimetype can not be parsed"); } - const type = groups?.['type']; - const subtype = groups?.['subtype']; - const parameter = groups?.['parameter']; + const type = groups?.["type"]; + const subtype = groups?.["subtype"]; + const parameter = groups?.["parameter"]; if (subtype === "" || type === "") { - throw new TypeError('blank value is not allowed'); + throw new TypeError("blank value is not allowed"); } return new MediaType(type, subtype, parseParameter(parameter)); - - } /** @@ -197,21 +187,19 @@ function parseMediaType(mediatype) { * @memberOf Monster.Types */ function parseParameter(parameter) { - if (!isString(parameter)) { return undefined; } let result = []; - parameter.split(';').forEach((entry) => { - + parameter.split(";").forEach((entry) => { entry = entry.trim(); if (entry === "") { return; } - const kv = entry.split('=') + const kv = entry.split("="); let key = validateString(kv?.[0]).trim(); let value = validateString(kv?.[1]).trim(); @@ -219,12 +207,9 @@ function parseParameter(parameter) { // if values are quoted, they remain so internally result.push({ key: key, - value: value - }) - - - }) + value: value, + }); + }); return result; - } diff --git a/application/source/types/namespace.mjs b/application/source/types/namespace.mjs index 2cf27f2ca..f9449ac58 100644 --- a/application/source/types/namespace.mjs +++ b/application/source/types/namespace.mjs @@ -11,4 +11,3 @@ * @author schukai GmbH */ const ns = {}; - diff --git a/application/source/types/node.mjs b/application/source/types/node.mjs index ac2ab5fd1..a8596192f 100644 --- a/application/source/types/node.mjs +++ b/application/source/types/node.mjs @@ -5,26 +5,25 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {isPrimitive} from "./is.mjs"; -import {NodeList} from './nodelist.mjs'; -import {validateInstance} from './validate.mjs'; -import {instanceSymbol} from '../constants.mjs'; +import { Base } from "./base.mjs"; +import { isPrimitive } from "./is.mjs"; +import { NodeList } from "./nodelist.mjs"; +import { validateInstance } from "./validate.mjs"; +import { instanceSymbol } from "../constants.mjs"; -export {Node} +export { Node }; /** * @private * @type {symbol} */ -const internalValueSymbol = Symbol('internalData'); +const internalValueSymbol = Symbol("internalData"); /** * @private * @type {symbol} */ -const treeStructureSymbol = Symbol('treeStructure'); - +const treeStructureSymbol = Symbol("treeStructure"); /** * You can create the instance via the monster namespace `new Monster.Types.Node()`. @@ -37,7 +36,6 @@ const treeStructureSymbol = Symbol('treeStructure'); * @see https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Iteration_protocols */ class Node extends Base { - /** * @param {*} [value] */ @@ -47,10 +45,9 @@ class Node extends Base { this[treeStructureSymbol] = { parent: null, - childNodes: new NodeList, - level: 0 - } - + childNodes: new NodeList(), + level: 0, + }; } /** @@ -62,7 +59,6 @@ class Node extends Base { return Symbol.for("@schukai/monster/types/node"); } - /** * @property {*} */ @@ -155,11 +151,10 @@ class Node extends Base { * @return {string} */ toString() { - let parts = []; if (this[internalValueSymbol]) { let label = this[internalValueSymbol]; - if (!isPrimitive(label)) label = JSON.stringify(this[internalValueSymbol]) + if (!isPrimitive(label)) label = JSON.stringify(this[internalValueSymbol]); parts.push(label); } @@ -173,13 +168,12 @@ class Node extends Base { for (const node of this.childNodes) { counter++; - const prefix = (count === counter ? '└' : '├').padStart(2 * node.level, ' |'); + const prefix = (count === counter ? "└" : "├").padStart(2 * node.level, " |"); parts.push(prefix + node.toString()); } return parts.join("\n"); } - } /** @@ -192,7 +186,7 @@ function setChildLevelAndParent(node, operand) { const self = this; if (node !== this) { - node[treeStructureSymbol].parent = this + node[treeStructureSymbol].parent = this; } node[treeStructureSymbol].childNodes.forEach(function (child) { diff --git a/application/source/types/nodelist.mjs b/application/source/types/nodelist.mjs index 1c432b4ba..d7b611d4d 100644 --- a/application/source/types/nodelist.mjs +++ b/application/source/types/nodelist.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isArray, isInstance} from "./is.mjs"; -import {Node} from "./node.mjs"; -import {validateInstance} from "./validate.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {NodeList} +import { isArray, isInstance } from "./is.mjs"; +import { Node } from "./node.mjs"; +import { validateInstance } from "./validate.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { NodeList }; /** * You can create the instance via the monster namespace `new Monster.Types.NodeList()`. @@ -21,7 +21,6 @@ export {NodeList} * @summary A NodeList class */ class NodeList extends Set { - /** * @throws {Error} invalid value type * @param {NodeList|Node|Array<Node>}values @@ -29,18 +28,18 @@ class NodeList extends Set { constructor(values) { super(); - const self = this + const self = this; if (values === undefined) return; if (isArray(values)) { - values.forEach(value => self.add(value)); + values.forEach((value) => self.add(value)); } else if (isInstance(values, NodeList)) { - values.forEach(value => self.add(value)); + values.forEach((value) => self.add(value)); } else if (isInstance(values, Node)) { self.add(values); } else { - throw new Error('invalid value type'); + throw new Error("invalid value type"); } } @@ -52,7 +51,6 @@ class NodeList extends Set { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/types/node-list"); } - /** * @@ -110,7 +108,7 @@ class NodeList extends Set { let parts = []; for (const node of this.toArray()) { - parts.push(node.toString()) + parts.push(node.toString()); } return parts.join("\n"); @@ -120,4 +118,3 @@ class NodeList extends Set { return super.size; } } - diff --git a/application/source/types/noderecursiveiterator.mjs b/application/source/types/noderecursiveiterator.mjs index d4253c087..646e118cd 100644 --- a/application/source/types/noderecursiveiterator.mjs +++ b/application/source/types/noderecursiveiterator.mjs @@ -5,21 +5,21 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; +import { internalSymbol } from "../constants.mjs"; -import {Base} from './base.mjs'; -import {isInstance} from "./is.mjs"; -import {Node} from "./node.mjs"; -import {NodeList} from "./nodelist.mjs"; -import {validateInstance} from "./validate.mjs"; +import { Base } from "./base.mjs"; +import { isInstance } from "./is.mjs"; +import { Node } from "./node.mjs"; +import { NodeList } from "./nodelist.mjs"; +import { validateInstance } from "./validate.mjs"; -export {NodeRecursiveIterator} +export { NodeRecursiveIterator }; /** * @private * @type {symbol} */ -const isNodeListSymbol = Symbol('isNodeList'); +const isNodeListSymbol = Symbol("isNodeList"); /** * You can create the instance via the monster namespace `new Monster.Types.NodeRecursiveIterator()`. @@ -31,8 +31,7 @@ const isNodeListSymbol = Symbol('isNodeList'); * @memberOf Monster.Types * @summary An iterator to run recursively through a tree of nodes */ - class NodeRecursiveIterator extends Base { - +class NodeRecursiveIterator extends Base { /** * @param {Node} [data] */ @@ -57,7 +56,6 @@ const isNodeListSymbol = Symbol('isNodeList'); * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield */ [Symbol.iterator] = function* () { - /** * The end of the generator function is reached. In this case, execution of the generator * ends and an IteratorResult is returned to the caller in which the value is undefined and done is true. @@ -66,7 +64,7 @@ const isNodeListSymbol = Symbol('isNodeList'); if (this[internalSymbol] === undefined) { return; } - + // iterator is a nodelist and the main node is only a placeholder if (this[isNodeListSymbol] !== true) { yield this[internalSymbol]; @@ -81,7 +79,7 @@ const isNodeListSymbol = Symbol('isNodeList'); } return; - } + }; /** * @param {function} callback @@ -93,5 +91,4 @@ const isNodeListSymbol = Symbol('isNodeList'); } return this; } - } diff --git a/application/source/types/observablequeue.mjs b/application/source/types/observablequeue.mjs index f395561bb..b50b97407 100644 --- a/application/source/types/observablequeue.mjs +++ b/application/source/types/observablequeue.mjs @@ -5,17 +5,17 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Queue} from './queue.mjs'; -import {instanceSymbol, internalSymbol} from '../constants.mjs'; -import {ObserverList} from "./observerlist.mjs"; +import { Queue } from "./queue.mjs"; +import { instanceSymbol, internalSymbol } from "../constants.mjs"; +import { ObserverList } from "./observerlist.mjs"; -export {ObservableQueue}; +export { ObservableQueue }; /** * An observable queue is a list of items that are processed one after another (first in, first out). - * + * * `Queue.add()` and `Queue.clear()` notify all observers. - * + * * @externalExample ../../example/types/queue.mjs * @license AGPLv3 * @since 3.3.0 @@ -24,14 +24,13 @@ export {ObservableQueue}; * @summary An observable Queue (Fifo) */ class ObservableQueue extends Queue { - /** * */ constructor() { super(); - this[internalSymbol]= { - observers: new ObserverList() + this[internalSymbol] = { + observers: new ObserverList(), }; } @@ -43,7 +42,7 @@ class ObservableQueue extends Queue { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/types/observablequeue"); } - + /** * Add a new element to the end of the queue. * @@ -74,7 +73,7 @@ class ObservableQueue extends Queue { * @returns {ProxyObserver} */ attachObserver(observer) { - this[internalSymbol].observers.attach(observer) + this[internalSymbol].observers.attach(observer); return this; } @@ -85,7 +84,7 @@ class ObservableQueue extends Queue { * @returns {ProxyObserver} */ detachObserver(observer) { - this[internalSymbol].observers.detach(observer) + this[internalSymbol].observers.detach(observer); return this; } @@ -103,8 +102,6 @@ class ObservableQueue extends Queue { * @returns {boolean} */ containsObserver(observer) { - return this[internalSymbol].observers.contains(observer) - } - - + return this[internalSymbol].observers.contains(observer); + } } diff --git a/application/source/types/observer.mjs b/application/source/types/observer.mjs index dea9f58c5..e91ccd30c 100644 --- a/application/source/types/observer.mjs +++ b/application/source/types/observer.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {isObject} from './is.mjs'; -import {TokenList} from './tokenlist.mjs'; -import {UniqueQueue} from './uniquequeue.mjs'; -import {instanceSymbol} from '../constants.mjs'; -export {Observer} +import { Base } from "./base.mjs"; +import { isObject } from "./is.mjs"; +import { TokenList } from "./tokenlist.mjs"; +import { UniqueQueue } from "./uniquequeue.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Observer }; /** * An observer manages a callback function @@ -32,7 +32,7 @@ export {Observer} * * ```js * Observer(function(a, b, c) { - * console.log(a, b, c); // ↦ "a", 2, true + * console.log(a, b, c); // ↦ "a", 2, true * }, "a", 2, true) * ``` * @@ -45,7 +45,6 @@ export {Observer} * @memberOf Monster.Types */ class Observer extends Base { - /** * * @param {function} callback @@ -54,13 +53,13 @@ class Observer extends Base { constructor(callback, ...args) { super(); - if (typeof callback !== 'function') { - throw new Error("observer callback must be a function") + if (typeof callback !== "function") { + throw new Error("observer callback must be a function"); } this.callback = callback; this.arguments = args; - this.tags = new TokenList; + this.tags = new TokenList(); this.queue = new UniqueQueue(); } @@ -72,8 +71,7 @@ class Observer extends Base { static get [instanceSymbol]() { return Symbol.for("@schukai/monster/types/observer"); } - - + /** * * @param {string} tag @@ -99,7 +97,7 @@ class Observer extends Base { * @returns {Array} */ getTags() { - return this.tags.entries() + return this.tags.entries(); } /** @@ -108,7 +106,7 @@ class Observer extends Base { * @returns {boolean} */ hasTag(tag) { - return this.tags.contains(tag) + return this.tags.contains(tag); } /** @@ -128,9 +126,8 @@ class Observer extends Base { self.queue.add(subject); setTimeout(() => { - try { - // the queue and the settimeout ensure that an object is not + // the queue and the settimeout ensure that an object is not // informed of the same change more than once. if (self.queue.isEmpty()) { resolve(); @@ -146,14 +143,10 @@ class Observer extends Base { } resolve(result); - } catch (e) { reject(e); } - }, 0) - + }, 0); }); - - }; - + } } diff --git a/application/source/types/observerlist.mjs b/application/source/types/observerlist.mjs index 10e1797fd..773c28a77 100644 --- a/application/source/types/observerlist.mjs +++ b/application/source/types/observerlist.mjs @@ -1,5 +1,3 @@ - - /** * Copyright schukai GmbH and contributors 2022. All Rights Reserved. * Node module: @schukai/monster @@ -7,12 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ +import { Base } from "./base.mjs"; +import { Observer } from "./observer.mjs"; +import { validateInstance } from "./validate.mjs"; -import {Base} from './base.mjs'; -import {Observer} from "./observer.mjs"; -import {validateInstance} from "./validate.mjs"; - -export {ObserverList} +export { ObserverList }; /** * With the help of the ObserverList class, observer can be managed. @@ -23,7 +20,6 @@ export {ObserverList} * @memberOf Monster.Types */ class ObserverList extends Base { - /** * */ @@ -39,11 +35,11 @@ class ObserverList extends Base { * @throws {TypeError} value is not an instance of Observer */ attach(observer) { - validateInstance(observer, Observer) + validateInstance(observer, Observer); this.observers.push(observer); return this; - }; + } /** * @@ -52,7 +48,7 @@ class ObserverList extends Base { * @throws {TypeError} value is not an instance of Observer */ detach(observer) { - validateInstance(observer, Observer) + validateInstance(observer, Observer); var i = 0; var l = this.observers.length; @@ -63,7 +59,7 @@ class ObserverList extends Base { } return this; - }; + } /** * @@ -72,7 +68,7 @@ class ObserverList extends Base { * @throws {TypeError} value is not an instance of Observer */ contains(observer) { - validateInstance(observer, Observer) + validateInstance(observer, Observer); var i = 0; var l = this.observers.length; for (; i < l; i++) { @@ -81,7 +77,7 @@ class ObserverList extends Base { } } return false; - }; + } /** * @@ -89,8 +85,7 @@ class ObserverList extends Base { * @return {Promise} */ notify(subject) { - - let pomises = [] + let pomises = []; let i = 0; let l = this.observers.length; @@ -99,6 +94,5 @@ class ObserverList extends Base { } return Promise.all(pomises); - }; - + } } diff --git a/application/source/types/proxyobserver.mjs b/application/source/types/proxyobserver.mjs index 9cb536054..5af551088 100644 --- a/application/source/types/proxyobserver.mjs +++ b/application/source/types/proxyobserver.mjs @@ -5,19 +5,19 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {isArray, isObject, isPrimitive} from "./is.mjs"; -import {Observer} from "./observer.mjs"; -import {ObserverList} from "./observerlist.mjs"; -import {validateObject} from "./validate.mjs"; -import {extend} from "../data/extend.mjs"; -import {instanceSymbol} from '../constants.mjs'; -export {ProxyObserver} +import { Base } from "./base.mjs"; +import { isArray, isObject, isPrimitive } from "./is.mjs"; +import { Observer } from "./observer.mjs"; +import { ObserverList } from "./observerlist.mjs"; +import { validateObject } from "./validate.mjs"; +import { extend } from "../data/extend.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { ProxyObserver }; /** * An observer manages a callback function * - * With the ProxyObserver you can attach observer for observation. + * With the ProxyObserver you can attach observer for observation. * With each change at the object to be observed an update takes place. * * This also applies to nested objects. @@ -28,8 +28,7 @@ export {ProxyObserver} * @copyright schukai GmbH * @memberOf Monster.Types */ - class ProxyObserver extends Base { - +class ProxyObserver extends Base { /** * * @param {object} object @@ -47,7 +46,7 @@ export {ProxyObserver} this.proxyMap = new WeakMap(); this.proxyMap.set(this.subject, this.realSubject); - this.observers = new ObserverList; + this.observers = new ObserverList(); } /** @@ -59,7 +58,6 @@ export {ProxyObserver} return Symbol.for("@schukai/monster/types/proxy-observer"); } - /** * Get the real object * @@ -68,7 +66,7 @@ export {ProxyObserver} * @returns {object} */ getSubject() { - return this.subject + return this.subject; } /** @@ -77,7 +75,6 @@ export {ProxyObserver} * @return {Monster.Types.ProxyObserver} */ setSubject(obj) { - let i; let k = Object.keys(this.subject); for (i = 0; i < k.length; i++) { @@ -94,7 +91,7 @@ export {ProxyObserver} * @returns {object} */ getRealSubject() { - return this.realSubject + return this.realSubject; } /** @@ -104,7 +101,7 @@ export {ProxyObserver} * @returns {ProxyObserver} */ attachObserver(observer) { - this.observers.attach(observer) + this.observers.attach(observer); return this; } @@ -115,7 +112,7 @@ export {ProxyObserver} * @returns {ProxyObserver} */ detachObserver(observer) { - this.observers.detach(observer) + this.observers.detach(observer); return this; } @@ -133,9 +130,8 @@ export {ProxyObserver} * @returns {boolean} */ containsObserver(observer) { - return this.observers.contains(observer) + return this.observers.contains(observer); } - } /** @@ -145,15 +141,12 @@ export {ProxyObserver} * @see {@link https://gitlab.schukai.com/-/snippets/49} */ function getHandler() { - const proxy = this; // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots const handler = { - // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots-get-p-receiver get: function (target, key, receiver) { - const value = Reflect.get(target, key, receiver); if (typeof key === "symbol") { @@ -165,7 +158,7 @@ function getHandler() { } // set value as proxy if object or array - if ((isArray(value) || isObject(value))) { + if (isArray(value) || isObject(value)) { if (proxy.objectMap.has(value)) { return proxy.objectMap.get(value); } else if (proxy.proxyMap.has(value)) { @@ -176,16 +169,13 @@ function getHandler() { proxy.proxyMap.set(p, value); return p; } - } return value; - }, - // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver + // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots-set-p-v-receiver set: function (target, key, value, receiver) { - if (proxy.proxyMap.has(value)) { value = proxy.proxyMap.get(value); } @@ -210,11 +200,11 @@ function getHandler() { descriptor = { writable: true, enumerable: true, - configurable: true - } + configurable: true, + }; } - descriptor['value'] = value; + descriptor["value"] = value; result = Reflect.defineProperty(target, key, descriptor); if (typeof key !== "symbol") { @@ -224,7 +214,6 @@ function getHandler() { return result; }, - // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots-delete-p deleteProperty: function (target, key) { if (key in target) { @@ -241,7 +230,6 @@ function getHandler() { // https://262.ecma-international.org/9.0/#sec-proxy-object-internal-methods-and-internal-slots-defineownproperty-p-desc defineProperty: function (target, key, descriptor) { - let result = Reflect.defineProperty(target, key, descriptor); if (typeof key !== "symbol") { proxy.observers.notify(proxy); @@ -258,10 +246,8 @@ function getHandler() { } return result; - } - + }, }; - return handler; } diff --git a/application/source/types/queue.mjs b/application/source/types/queue.mjs index c6e691923..0bea6e069 100644 --- a/application/source/types/queue.mjs +++ b/application/source/types/queue.mjs @@ -5,20 +5,20 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {instanceSymbol} from '../constants.mjs'; +import { Base } from "./base.mjs"; +import { instanceSymbol } from "../constants.mjs"; -export {Queue} +export { Queue }; /** * A queue is a list of items that are processed one after another (first in, first out). - * + * * With a queue you can add items to the end of the list `Queue.add()` and remove items from the beginning of the list `Queue.pop()`. - * + * * With `Queue.peek()` you can get the first item without removing it from the list. - * + * * You can create the instance via `new Queue()`. - * + * * @externalExample ../../example/types/queue.mjs * @license AGPLv3 * @since 1.4.0 @@ -27,7 +27,6 @@ export {Queue} * @summary A Queue (Fifo) */ class Queue extends Base { - /** * */ @@ -45,8 +44,6 @@ class Queue extends Base { return Symbol.for("@schukai/monster/types/queue"); } - - /** * @return {boolean} */ @@ -74,7 +71,7 @@ class Queue extends Base { * @returns {Queue} */ add(value) { - this.data.push(value) + this.data.push(value); return this; } @@ -100,6 +97,4 @@ class Queue extends Base { } return this.data.shift(); } - - } diff --git a/application/source/types/randomid.mjs b/application/source/types/randomid.mjs index 0767da510..48c159997 100644 --- a/application/source/types/randomid.mjs +++ b/application/source/types/randomid.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {random} from "../math/random.mjs"; -import {getGlobal} from "./global.mjs"; -import {ID} from "./id.mjs"; +import { random } from "../math/random.mjs"; +import { getGlobal } from "./global.mjs"; +import { ID } from "./id.mjs"; -export {RandomID} +export { RandomID }; /** * @private @@ -27,7 +27,6 @@ let internalCounter = 0; * @summary class to generate random numbers */ class RandomID extends ID { - /** * create new object */ @@ -36,10 +35,11 @@ class RandomID extends ID { internalCounter += 1; - this.id = getGlobal().btoa(random(1, 10000)) - .replace(/=/g, '') - /** No numbers at the beginning of the ID, because of possible problems with DOM */ - .replace(/^[0-9]+/, 'X') + internalCounter; + this.id = + getGlobal() + .btoa(random(1, 10000)) + .replace(/=/g, "") + /** No numbers at the beginning of the ID, because of possible problems with DOM */ + .replace(/^[0-9]+/, "X") + internalCounter; } - } diff --git a/application/source/types/regex.mjs b/application/source/types/regex.mjs index 04736365d..ad1ea3b81 100644 --- a/application/source/types/regex.mjs +++ b/application/source/types/regex.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {validateString} from "./validate.mjs"; +import { validateString } from "./validate.mjs"; -export {escapeString} +export { escapeString }; /** * This function prefixes all special characters that may appear in a regex with a slash. @@ -21,7 +21,5 @@ export {escapeString} * @throws {TypeError} value is not a string */ function escapeString(value) { - return validateString(value) - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); + return validateString(value).replace(/[|\\{}()[\]^$+*?.]/g, "\\$&").replace(/-/g, "\\x2d"); } diff --git a/application/source/types/stack.mjs b/application/source/types/stack.mjs index 802e7f273..85574c890 100644 --- a/application/source/types/stack.mjs +++ b/application/source/types/stack.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {instanceSymbol} from '../constants.mjs'; -export {Stack} +import { Base } from "./base.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Stack }; /** * You can call the method via the monster namespace `new Monster.Types.Queue()`. @@ -18,7 +18,6 @@ export {Stack} * @memberOf Monster.Types */ class Stack extends Base { - /** * */ @@ -36,7 +35,6 @@ class Stack extends Base { return Symbol.for("@schukai/monster/types/stack"); } - /** * @return {boolean} */ @@ -64,7 +62,7 @@ class Stack extends Base { * @returns {Queue} */ push(value) { - this.data.push(value) + this.data.push(value); return this; } @@ -91,6 +89,4 @@ class Stack extends Base { } return this.data.pop(); } - - } diff --git a/application/source/types/tokenlist.mjs b/application/source/types/tokenlist.mjs index f5054e82b..d37fdb4b3 100644 --- a/application/source/types/tokenlist.mjs +++ b/application/source/types/tokenlist.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {isIterable, isString} from '../types/is.mjs'; -import {validateFunction, validateString} from '../types/validate.mjs'; -import {Base} from './base.mjs'; +import { isIterable, isString } from "../types/is.mjs"; +import { validateFunction, validateString } from "../types/validate.mjs"; +import { Base } from "./base.mjs"; -export {TokenList} +export { TokenList }; /** * A `TokenList` allows you to manage tokens (individual character strings such as css classes in an attribute string). @@ -25,7 +25,6 @@ export {TokenList} * @memberOf Monster.Types */ class TokenList extends Base { - /** * * @param {array|string|iteratable} init @@ -37,7 +36,6 @@ class TokenList extends Base { if (typeof init !== "undefined") { this.add(init); } - } /** @@ -59,17 +57,17 @@ class TokenList extends Base { // iterations over the iterable safe for non-trivial cases, // such as use of break or nested looping over the same iterable. let index = 0; - let entries = this.entries() + let entries = this.entries(); return { next: () => { if (index < entries.length) { - return {value: entries?.[index++], done: false} + return { value: entries?.[index++], done: false }; } else { - return {done: true} + return { done: true }; } - } - } + }, + }; } /** @@ -81,12 +79,12 @@ class TokenList extends Base { */ contains(value) { if (isString(value)) { - value = value.trim() + value = value.trim(); let counter = 0; - value.split(" ").forEach(token => { + value.split(" ").forEach((token) => { if (this.tokens.has(token.trim()) === false) return false; - counter++ - }) + counter++; + }); return counter > 0 ? true : false; } @@ -95,7 +93,7 @@ class TokenList extends Base { for (let token of value) { validateString(token); if (this.tokens.has(token.trim()) === false) return false; - counter++ + counter++; } return counter > 0 ? true : false; } @@ -113,9 +111,9 @@ class TokenList extends Base { */ add(value) { if (isString(value)) { - value.split(" ").forEach(token => { + value.split(" ").forEach((token) => { this.tokens.add(token.trim()); - }) + }); } else if (isIterable(value)) { for (let token of value) { validateString(token); @@ -148,9 +146,9 @@ class TokenList extends Base { */ remove(value) { if (isString(value)) { - value.split(" ").forEach(token => { + value.split(" ").forEach((token) => { this.tokens.delete(token.trim()); - }) + }); } else if (isIterable(value)) { for (let token of value) { validateString(token); @@ -180,7 +178,7 @@ class TokenList extends Base { return this; } - let a = Array.from(this.tokens) + let a = Array.from(this.tokens); let i = a.indexOf(token); if (i === -1) return this; @@ -189,8 +187,6 @@ class TokenList extends Base { this.add(a); return this; - - } /** @@ -202,11 +198,10 @@ class TokenList extends Base { * @throws {TypeError} unsupported value */ toggle(value) { - if (isString(value)) { - value.split(" ").forEach(token => { + value.split(" ").forEach((token) => { toggleValue.call(this, token); - }) + }); } else if (isIterable(value)) { for (let token of value) { toggleValue.call(this, token); @@ -216,7 +211,6 @@ class TokenList extends Base { } return this; - } /** @@ -225,7 +219,7 @@ class TokenList extends Base { * @returns {array} */ entries() { - return Array.from(this.tokens) + return Array.from(this.tokens); } /** @@ -246,9 +240,8 @@ class TokenList extends Base { * @returns {string} */ toString() { - return this.entries().join(' '); + return this.entries().join(" "); } - } /** @@ -258,7 +251,7 @@ class TokenList extends Base { * @throws {Error} must be called with TokenList.call */ function toggleValue(token) { - if (!(this instanceof TokenList)) throw Error("must be called with TokenList.call") + if (!(this instanceof TokenList)) throw Error("must be called with TokenList.call"); validateString(token); token = token.trim(); if (this.contains(token)) { diff --git a/application/source/types/typeof.mjs b/application/source/types/typeof.mjs index c71723851..c06551f83 100644 --- a/application/source/types/typeof.mjs +++ b/application/source/types/typeof.mjs @@ -5,7 +5,7 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -export {typeOf} +export { typeOf }; /** * The built-in typeof method is known to have some historical weaknesses. This function tries to provide a better and more accurate result. @@ -20,18 +20,16 @@ export {typeOf} * @throws {TypeError} value is not a primitive */ function typeOf(value) { - let type = ({}).toString.call(value).match(/\s([a-zA-Z]+)/)[1]; - if ('Object' === type) { - + let type = {}.toString.call(value).match(/\s([a-zA-Z]+)/)[1]; + if ("Object" === type) { const name = value.constructor.name; if (name) { return name.toLowerCase(); } - const results = (/^(class|function)\s+(\w+)/).exec(value.constructor.toString()); - type = (results && results.length > 2) ? results[2] : ''; + const results = /^(class|function)\s+(\w+)/.exec(value.constructor.toString()); + type = results && results.length > 2 ? results[2] : ""; } return type.toLowerCase(); } - diff --git a/application/source/types/uniquequeue.mjs b/application/source/types/uniquequeue.mjs index 4d43b3913..1d53482c7 100644 --- a/application/source/types/uniquequeue.mjs +++ b/application/source/types/uniquequeue.mjs @@ -5,11 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Queue} from "./queue.mjs"; -import {internalSymbol} from "../constants.mjs"; -import {validateObject} from "./validate.mjs"; +import { Queue } from "./queue.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { validateObject } from "./validate.mjs"; -export {UniqueQueue} +export { UniqueQueue }; /** * An UniqueQueue is a queue that contains items only once. @@ -20,15 +20,14 @@ export {UniqueQueue} * @memberOf Monster.Types * @summary A queue for unique values */ - class UniqueQueue extends Queue { - +class UniqueQueue extends Queue { /** * */ constructor() { super(); - this[internalSymbol]={ - unique : new WeakSet() + this[internalSymbol] = { + unique: new WeakSet(), }; } @@ -40,7 +39,6 @@ export {UniqueQueue} * @throws {TypeError} value is not a object */ add(value) { - validateObject(value); if (!this[internalSymbol].unique.has(value)) { @@ -58,7 +56,7 @@ export {UniqueQueue} */ clear() { super.clear(); - this[internalSymbol].unique = new WeakSet; + this[internalSymbol].unique = new WeakSet(); return this; } @@ -69,7 +67,6 @@ export {UniqueQueue} * @return {object} */ poll() { - if (this.isEmpty()) { return undefined; } @@ -77,6 +74,4 @@ export {UniqueQueue} this[internalSymbol].unique.delete(value); return value; } - - } diff --git a/application/source/types/uuid.mjs b/application/source/types/uuid.mjs index 96ad59b04..181c399e8 100644 --- a/application/source/types/uuid.mjs +++ b/application/source/types/uuid.mjs @@ -5,25 +5,24 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {random} from "../math/random.mjs"; -import {isObject} from '../types/is.mjs'; -import {Base} from "./base.mjs"; -import {getGlobalObject} from "./global.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { random } from "../math/random.mjs"; +import { isObject } from "../types/is.mjs"; +import { Base } from "./base.mjs"; +import { getGlobalObject } from "./global.mjs"; -export {UUID} +export { UUID }; /** * The UUID class makes it possible to get a unique UUID for an object. - * + * * @license AGPLv3 * @since 1.25.0 * @copyright schukai GmbH * @memberOf Monster.Types * @throws {Error} unsupported */ - class UUID extends Base { - +class UUID extends Base { /** * */ @@ -36,15 +35,13 @@ export {UUID} uuid = createWithRandom(); } - if (uuid === undefined) { - throw new Error('unsupported') + throw new Error("unsupported"); } this[internalSymbol] = { - value: uuid - } - + value: uuid, + }; } /** @@ -52,10 +49,8 @@ export {UUID} * @return {string} */ toString() { - return this[internalSymbol]['value']; + return this[internalSymbol]["value"]; } - - } /** @@ -63,22 +58,20 @@ export {UUID} * @return {string|undefined} */ function createWithRandom() { - return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - const r = random(0, 65000) * 16 | 0; - const v = ((c === 'x') ? r : (r & 0x3 | 0x8)); + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + const r = (random(0, 65000) * 16) | 0; + const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16)[0]; - }) + }); } - /** * @private * @return {string|undefined} */ function createWithCrypto() { - const crypt = getGlobalObject('crypto'); + const crypt = getGlobalObject("crypto"); if (!isObject(crypt)) return; - if (typeof crypt?.['randomUUID']) return; + if (typeof crypt?.["randomUUID"]) return; return crypt.randomUUID(); } - diff --git a/application/source/types/validate.mjs b/application/source/types/validate.mjs index 4abf40192..39b62e63e 100644 --- a/application/source/types/validate.mjs +++ b/application/source/types/validate.mjs @@ -15,8 +15,8 @@ import { isObject, isPrimitive, isString, - isSymbol -} from './is.mjs'; + isSymbol, +} from "./is.mjs"; export { validateIterable, @@ -28,8 +28,8 @@ export { validateArray, validateSymbol, validateFunction, - validateInteger -} + validateInteger, +}; /** * This method checks if the type matches the primitive type. this function is identical to isPrimitive() except that a TypeError is thrown. @@ -55,9 +55,9 @@ export { */ function validateIterable(value) { if (!isIterable(value)) { - throw new TypeError('value is not iterable') + throw new TypeError("value is not iterable"); } - return value + return value; } /** @@ -84,9 +84,9 @@ function validateIterable(value) { */ function validatePrimitive(value) { if (!isPrimitive(value)) { - throw new TypeError('value is not a primitive') + throw new TypeError("value is not a primitive"); } - return value + return value; } /** @@ -112,9 +112,9 @@ function validatePrimitive(value) { */ function validateBoolean(value) { if (!isBoolean(value)) { - throw new TypeError('value is not a boolean') + throw new TypeError("value is not a boolean"); } - return value + return value; } /** @@ -138,12 +138,11 @@ function validateBoolean(value) { */ function validateString(value) { if (!isString(value)) { - throw new TypeError('value is not a string') + throw new TypeError("value is not a string"); } - return value + return value; } - /** * This method checks if the type matches the object type. this function is identical to isObject() except that a TypeError is thrown. * @@ -166,9 +165,9 @@ function validateString(value) { */ function validateObject(value) { if (!isObject(value)) { - throw new TypeError('value is not a object') + throw new TypeError("value is not a object"); } - return value + return value; } /** @@ -195,16 +194,16 @@ function validateInstance(value, instance) { if (!isInstance(value, instance)) { let n = ""; if (isObject(instance) || isFunction(instance)) { - n = instance?.['name'] + n = instance?.["name"]; } if (n) { n = ` ${n}`; } - throw new TypeError(`value is not an instance of${n}`) + throw new TypeError(`value is not an instance of${n}`); } - return value + return value; } /** @@ -228,9 +227,9 @@ function validateInstance(value, instance) { */ function validateArray(value) { if (!isArray(value)) { - throw new TypeError('value is not an array') + throw new TypeError("value is not an array"); } - return value + return value; } /** @@ -254,9 +253,9 @@ function validateArray(value) { */ function validateSymbol(value) { if (!isSymbol(value)) { - throw new TypeError('value is not an symbol') + throw new TypeError("value is not an symbol"); } - return value + return value; } /** @@ -281,9 +280,9 @@ function validateSymbol(value) { */ function validateFunction(value) { if (!isFunction(value)) { - throw new TypeError('value is not a function') + throw new TypeError("value is not a function"); } - return value + return value; } /** @@ -308,7 +307,7 @@ function validateFunction(value) { */ function validateInteger(value) { if (!isInteger(value)) { - throw new TypeError('value is not an integer') + throw new TypeError("value is not an integer"); } - return value + return value; } diff --git a/application/source/types/version.mjs b/application/source/types/version.mjs index 6c8f68660..fa0219c38 100644 --- a/application/source/types/version.mjs +++ b/application/source/types/version.mjs @@ -5,11 +5,10 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from './base.mjs'; -import {instanceSymbol} from '../constants.mjs'; - -export {Version, getMonsterVersion} +import { Base } from "./base.mjs"; +import { instanceSymbol } from "../constants.mjs"; +export { Version, getMonsterVersion }; /** * The version object contains a semantic version number @@ -23,7 +22,6 @@ export {Version, getMonsterVersion} * @summary The version object contains a sematic version number */ class Version extends Base { - /** * * @param major @@ -36,16 +34,15 @@ class Version extends Base { constructor(major, minor, patch) { super(); - if (typeof major === 'string' && minor === undefined && patch === undefined) { - - let parts = major.toString().split('.'); + if (typeof major === "string" && minor === undefined && patch === undefined) { + let parts = major.toString().split("."); major = parseInt(parts[0] || 0); minor = parseInt(parts[1] || 0); patch = parseInt(parts[2] || 0); } if (major === undefined) { - throw new Error("major version is undefined"); + throw new Error("major version is undefined"); } if (minor === undefined) { @@ -61,17 +58,16 @@ class Version extends Base { this.patch = parseInt(patch); if (isNaN(this.major)) { - throw new Error("major is not a number"); + throw new Error("major is not a number"); } if (isNaN(this.minor)) { - throw new Error("minor is not a number"); + throw new Error("minor is not a number"); } if (isNaN(this.patch)) { - throw new Error("patch is not a number"); + throw new Error("patch is not a number"); } - } /** @@ -83,7 +79,6 @@ class Version extends Base { return Symbol.for("@schukai/monster/types/version"); } - /** * * @returns {string} @@ -100,13 +95,12 @@ class Version extends Base { * @returns {number} */ compareTo(version) { - if (version instanceof Version) { version = version.toString(); } - if (typeof version !== 'string') { - throw new Error("type exception"); + if (typeof version !== "string") { + throw new Error("type exception"); } if (version === this.toString()) { @@ -114,20 +108,19 @@ class Version extends Base { } let a = [this.major, this.minor, this.patch]; - let b = version.split('.'); + let b = version.split("."); let len = Math.max(a.length, b.length); for (let i = 0; i < len; i += 1) { - if ((a[i] && !b[i] && parseInt(a[i]) > 0) || (parseInt(a[i]) > parseInt(b[i]))) { + if ((a[i] && !b[i] && parseInt(a[i]) > 0) || parseInt(a[i]) > parseInt(b[i])) { return 1; - } else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || (parseInt(a[i]) < parseInt(b[i]))) { + } else if ((b[i] && !a[i] && parseInt(b[i]) > 0) || parseInt(a[i]) < parseInt(b[i])) { return -1; } } return 0; - }; - + } } let monsterVersion; @@ -149,8 +142,7 @@ function getMonsterVersion() { } /** don't touch, replaced by make with package.json version */ - monsterVersion = new Version('3.5.0') + monsterVersion = new Version("3.5.0"); return monsterVersion; - } diff --git a/application/source/util/clone.mjs b/application/source/util/clone.mjs index 584ec09a6..7b7143509 100644 --- a/application/source/util/clone.mjs +++ b/application/source/util/clone.mjs @@ -5,12 +5,12 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {getGlobal} from '../types/global.mjs'; -import {isArray, isFunction, isObject, isPrimitive} from '../types/is.mjs'; -import {typeOf} from "../types/typeof.mjs"; -import {validateObject} from "../types/validate.mjs"; +import { getGlobal } from "../types/global.mjs"; +import { isArray, isFunction, isObject, isPrimitive } from "../types/is.mjs"; +import { typeOf } from "../types/typeof.mjs"; +import { validateObject } from "../types/validate.mjs"; -export {clone} +export { clone }; /** * With this function, objects can be cloned. @@ -30,7 +30,6 @@ export {clone} * @throws {Error} unable to clone obj! its type isn't supported. */ function clone(obj) { - // typeof null results in 'object'. https://2ality.com/2013/10/typeof-null.html if (null === obj) { return obj; @@ -57,8 +56,6 @@ function clone(obj) { } if (isObject(obj)) { - - // Handle Date if (obj instanceof Date) { let copy = new Date(); @@ -67,17 +64,17 @@ function clone(obj) { } /** Do not clone DOM nodes */ - if (typeof Element !== 'undefined' && obj instanceof Element) return obj; - if (typeof HTMLDocument !== 'undefined' && obj instanceof HTMLDocument) return obj; - if (typeof DocumentFragment !== 'undefined' && obj instanceof DocumentFragment) return obj; + if (typeof Element !== "undefined" && obj instanceof Element) return obj; + if (typeof HTMLDocument !== "undefined" && obj instanceof HTMLDocument) return obj; + if (typeof DocumentFragment !== "undefined" && obj instanceof DocumentFragment) return obj; /** Do not clone global objects */ if (obj === getGlobal()) return obj; - if (typeof globalContext !== 'undefined' && obj === globalContext) return obj; - if (typeof window !== 'undefined' && obj === window) return obj; - if (typeof document !== 'undefined' && obj === document) return obj; - if (typeof navigator !== 'undefined' && obj === navigator) return obj; - if (typeof JSON !== 'undefined' && obj === JSON) return obj; + if (typeof globalContext !== "undefined" && obj === globalContext) return obj; + if (typeof window !== "undefined" && obj === window) return obj; + if (typeof document !== "undefined" && obj === document) return obj; + if (typeof navigator !== "undefined" && obj === navigator) return obj; + if (typeof JSON !== "undefined" && obj === JSON) return obj; // Handle Proxy-Object try { @@ -85,11 +82,9 @@ function clone(obj) { if (obj instanceof Proxy) { return obj; } - } catch (e) { - } - - return cloneObject(obj) + } catch (e) {} + return cloneObject(obj); } throw new Error("unable to clone obj! its type isn't supported."); @@ -102,29 +97,26 @@ function clone(obj) { * @private */ function cloneObject(obj) { - validateObject(obj); - - const fkt = obj?.['constructor']; + + const fkt = obj?.["constructor"]; /** Object has clone method */ - if(typeOf(fkt)==='function') { + if (typeOf(fkt) === "function") { const prototype = fkt?.prototype; - if(typeof prototype==='object') { - if(prototype.hasOwnProperty('getClone')&& typeOf(obj.getClone) === 'function') { - return obj.getClone(); + if (typeof prototype === "object") { + if (prototype.hasOwnProperty("getClone") && typeOf(obj.getClone) === "function") { + return obj.getClone(); } } } let copy = {}; - if (typeof obj.constructor === 'function' && - typeof obj.constructor.call === 'function') { + if (typeof obj.constructor === "function" && typeof obj.constructor.call === "function") { copy = new obj.constructor(); } for (let key in obj) { - if (!obj.hasOwnProperty(key)) { continue; } @@ -139,4 +131,3 @@ function cloneObject(obj) { return copy; } - diff --git a/application/source/util/comparator.mjs b/application/source/util/comparator.mjs index 55d93f4db..8bc63acdb 100644 --- a/application/source/util/comparator.mjs +++ b/application/source/util/comparator.mjs @@ -5,14 +5,14 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {Base} from '../types/base.mjs'; -import {isFunction} from '../types/is.mjs'; +import { Base } from "../types/base.mjs"; +import { isFunction } from "../types/is.mjs"; -export {Comparator} +export { Comparator }; /** * The comparator allows a comparison function to be abstracted. - * + * * The following are some examples of the application of the class. * * ``` @@ -37,7 +37,6 @@ export {Comparator} * @memberOf Monster.Util */ class Comparator extends Base { - /** * create new comparator * @@ -49,9 +48,9 @@ class Comparator extends Base { super(); if (isFunction(callback)) { - this.compare = callback + this.compare = callback; } else if (callback !== undefined) { - throw new TypeError("unsupported type") + throw new TypeError("unsupported type"); } else { // default compare function @@ -62,9 +61,8 @@ class Comparator extends Base { * @return {integer} -1, 0 or 1 */ this.compare = function (a, b) { - if (typeof a !== typeof b) { - throw new TypeError("impractical comparison", "types/comparator.mjs") + throw new TypeError("impractical comparison", "types/comparator.mjs"); } if (a === b) { @@ -73,7 +71,6 @@ class Comparator extends Base { return a < b ? -1 : 1; }; } - } /** @@ -99,7 +96,6 @@ class Comparator extends Base { return this.compare(a, b) === 0; } - /** * Checks if variable `a` is greater than `b` * @@ -147,11 +143,8 @@ class Comparator extends Base { lessThan(a, b) { return this.compare(a, b) < 0; } - - } - /** * This is the description for the callback function used by the operator * @@ -169,4 +162,3 @@ class Comparator extends Base { * @memberOf Monster.Util * @see Monster.Util.Comparator */ - diff --git a/application/source/util/deadmansswitch.mjs b/application/source/util/deadmansswitch.mjs index fa3f7e08d..d5528e9a7 100644 --- a/application/source/util/deadmansswitch.mjs +++ b/application/source/util/deadmansswitch.mjs @@ -5,13 +5,13 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; +import { internalSymbol } from "../constants.mjs"; -import {Base} from "../types/base.mjs"; -import {isInteger} from "../types/is.mjs"; -import {validateFunction, validateInteger} from "../types/validate.mjs"; +import { Base } from "../types/base.mjs"; +import { isInteger } from "../types/is.mjs"; +import { validateFunction, validateInteger } from "../types/validate.mjs"; -export {DeadMansSwitch} +export { DeadMansSwitch }; /** * The dead man's switch allows to set a timer which can be reset again and again within a defined period of time. @@ -23,8 +23,7 @@ export {DeadMansSwitch} * @memberOf Monster.Util * @summary Class to be able to execute function chains */ - class DeadMansSwitch extends Base { - +class DeadMansSwitch extends Base { /** * Create new dead man's switch * @@ -44,18 +43,17 @@ export {DeadMansSwitch} * @param {Integer|undefined} [delay] */ touch(delay) { - - if (this[internalSymbol]['isAlreadyRun'] === true) { - throw new Error('has already run') + if (this[internalSymbol]["isAlreadyRun"] === true) { + throw new Error("has already run"); } if (isInteger(delay)) { - this[internalSymbol]['delay'] = delay + this[internalSymbol]["delay"] = delay; } else if (delay !== undefined) { - throw new Error('unsupported argument') + throw new Error("unsupported argument"); } - clearTimeout(this[internalSymbol]['timer']); + clearTimeout(this[internalSymbol]["timer"]); initCallback.call(this); @@ -67,13 +65,12 @@ export {DeadMansSwitch} * @private */ function initCallback() { - const self = this; - self[internalSymbol]['timer'] = setTimeout(() => { - self[internalSymbol]['isAlreadyRun'] = true; - self[internalSymbol]['callback'](); - }, self[internalSymbol]['delay']) + self[internalSymbol]["timer"] = setTimeout(() => { + self[internalSymbol]["isAlreadyRun"] = true; + self[internalSymbol]["callback"](); + }, self[internalSymbol]["delay"]); } /** @@ -88,12 +85,8 @@ function init(delay, callback) { callback, delay, isAlreadyRun: false, - timer: undefined + timer: undefined, }; initCallback.call(self); - } - - - diff --git a/application/source/util/freeze.mjs b/application/source/util/freeze.mjs index 4bdc0ec42..151373308 100644 --- a/application/source/util/freeze.mjs +++ b/application/source/util/freeze.mjs @@ -5,9 +5,9 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {validateObject} from '../types/validate.mjs'; +import { validateObject } from "../types/validate.mjs"; -export {deepFreeze} +export { deepFreeze }; /** * Deep freeze a object @@ -20,9 +20,8 @@ export {deepFreeze} * @copyright schukai GmbH * @throws {TypeError} value is not a object */ - function deepFreeze(object) { - - validateObject(object) +function deepFreeze(object) { + validateObject(object); // Retrieve the defined property names of the object var propNames = Object.getOwnPropertyNames(object); @@ -31,8 +30,7 @@ export {deepFreeze} for (let name of propNames) { let value = object[name]; - object[name] = (value && typeof value === "object") ? - deepFreeze(value) : value; + object[name] = value && typeof value === "object" ? deepFreeze(value) : value; } return Object.freeze(object); diff --git a/application/source/util/namespace.mjs b/application/source/util/namespace.mjs index c5d4c6739..05ee5664b 100644 --- a/application/source/util/namespace.mjs +++ b/application/source/util/namespace.mjs @@ -10,4 +10,4 @@ * @memberOf Monster * @author schukai GmbH */ -const ns = {}; \ No newline at end of file +const ns = {}; diff --git a/application/source/util/processing.mjs b/application/source/util/processing.mjs index 36a1eb275..aef76b248 100644 --- a/application/source/util/processing.mjs +++ b/application/source/util/processing.mjs @@ -5,20 +5,19 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ -import {internalSymbol} from "../constants.mjs"; -import {Base} from "../types/base.mjs"; -import {getGlobalFunction} from "../types/global.mjs"; -import {isFunction, isInteger} from "../types/is.mjs"; -import {Queue} from "../types/queue.mjs"; -import {validateFunction, validateInteger} from "../types/validate.mjs"; +import { internalSymbol } from "../constants.mjs"; +import { Base } from "../types/base.mjs"; +import { getGlobalFunction } from "../types/global.mjs"; +import { isFunction, isInteger } from "../types/is.mjs"; +import { Queue } from "../types/queue.mjs"; +import { validateFunction, validateInteger } from "../types/validate.mjs"; -export {Processing} +export { Processing }; /** * @private */ class Callback { - /** * * @param {function} callback @@ -30,7 +29,7 @@ class Callback { constructor(callback, time) { this[internalSymbol] = { callback: validateFunction(callback), - time: validateInteger(time ?? 0) + time: validateInteger(time ?? 0), }; } @@ -42,20 +41,14 @@ class Callback { run(data) { const self = this; return new Promise((resolve, reject) => { - - getGlobalFunction('setTimeout')(() => { - try { - resolve(self[internalSymbol].callback(data)); - } catch (e) { - reject(e); - } - - }, - self[internalSymbol].time); - - - }) - + getGlobalFunction("setTimeout")(() => { + try { + resolve(self[internalSymbol].callback(data)); + } catch (e) { + reject(e); + } + }, self[internalSymbol].time); + }); } } @@ -81,7 +74,6 @@ class Callback { * @summary Class to be able to execute function chains */ class Processing extends Base { - /** * Create new Processing * @@ -102,26 +94,24 @@ class Processing extends Base { super(); this[internalSymbol] = { - queue: new Queue + queue: new Queue(), }; - let time = 0 + let time = 0; - if (typeof args !== 'object' || args[0] === null) { - throw new TypeError('the arguments must be either integer or functions') - } + if (typeof args !== "object" || args[0] === null) { + throw new TypeError("the arguments must be either integer or functions"); + } for (const [, arg] of Object.entries(args)) { if (isInteger(arg) && arg >= 0) { time = arg; } else if (isFunction(arg)) { - this[internalSymbol].queue.add(new Callback(arg, time)) + this[internalSymbol].queue.add(new Callback(arg, time)); } else { - throw new TypeError('the arguments must be either integer or functions') + throw new TypeError("the arguments must be either integer or functions"); } } - - } /** @@ -134,11 +124,10 @@ class Processing extends Base { * @throws {TypeError} value is not an integer */ add(callback, time) { - this[internalSymbol].queue.add(new Callback(callback, time)) + this[internalSymbol].queue.add(new Callback(callback, time)); return this; } - /** * Executes the defined functions in order. * @@ -151,10 +140,11 @@ class Processing extends Base { return Promise.resolve(data); } - return this[internalSymbol].queue.poll().run(data).then((result) => { - return self.run(result); - }); - + return this[internalSymbol].queue + .poll() + .run(data) + .then((result) => { + return self.run(result); + }); } - } diff --git a/application/source/util/trimspaces.mjs b/application/source/util/trimspaces.mjs index d10d44acd..588d2e3bb 100644 --- a/application/source/util/trimspaces.mjs +++ b/application/source/util/trimspaces.mjs @@ -1,5 +1,3 @@ - - /** * Copyright schukai GmbH and contributors 2022. All Rights Reserved. * Node module: @schukai/monster @@ -7,12 +5,11 @@ * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html */ +import { ID } from "../types/id.mjs"; +import { isObject } from "../types/is.mjs"; +import { validateString } from "../types/validate.mjs"; -import {ID} from "../types/id.mjs"; -import {isObject} from "../types/is.mjs"; -import {validateString} from "../types/validate.mjs"; - -export {trimSpaces} +export { trimSpaces }; /** * This special trim function allows to trim spaces that have been protected by a special escape character. @@ -23,14 +20,14 @@ export {trimSpaces} * trimSpaces(' hello \\ ') * </script> * ``` - * + * * Hint: One stroke is escaped by the javascript interpreter, the second stroke escapes the stroke. - * + * * ```text * a\ b ↦ a b * a\\ b ↦ a\ b * ``` - * + * * @license AGPLv3 * @since 1.24.0 * @memberOf Monster.Util @@ -39,40 +36,36 @@ export {trimSpaces} * @return {string} * @throws {TypeError} value is not a string */ - function trimSpaces(value) { - +function trimSpaces(value) { validateString(value); - let placeholder = new Map; - const regex = /((?<pattern>\\(?<char>.)){1})/mig; + let placeholder = new Map(); + const regex = /((?<pattern>\\(?<char>.)){1})/gim; // The separator for args must be escaped // undefined string which should not occur normally and is also not a regex - let result = value.matchAll(regex) + let result = value.matchAll(regex); for (let m of result) { - let g = m?.['groups']; + let g = m?.["groups"]; if (!isObject(g)) { continue; } - let p = g?.['pattern']; - let c = g?.['char']; + let p = g?.["pattern"]; + let c = g?.["char"]; if (p && c) { let r = `__${new ID().toString()}__`; placeholder.set(r, c); value = value.replace(p, r); } - } value = value.trim(); placeholder.forEach((v, k) => { - value = value.replace(k, `\\${v}`) - }) + value = value.replace(k, `\\${v}`); + }); return value; - } - diff --git a/development/rome.json b/development/rome.json index 5f1dba025..73c4ac108 100644 --- a/development/rome.json +++ b/development/rome.json @@ -8,5 +8,11 @@ "noDelete": "off" } } + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "lineWidth": 120, + "indentSize": 4 } } \ No newline at end of file -- GitLab