Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • 1.31
  • master
  • 1.10.0
  • 1.30.1
  • 1.31.0
  • 1.8.0
  • 1.9.0
  • 3.100.0
  • 3.100.1
  • 3.100.10
  • 3.100.11
  • 3.100.12
  • 3.100.13
  • 3.100.14
  • 3.100.15
  • 3.100.16
  • 3.100.17
  • 3.100.18
  • 3.100.19
  • 3.100.2
  • 3.100.20
  • 3.100.3
  • 3.100.4
  • 3.100.5
  • 3.100.6
  • 3.100.7
  • 3.100.8
  • 3.100.9
  • 3.101.0
  • 3.101.1
  • 3.101.2
  • 3.101.3
  • 3.102.0
  • 3.102.1
  • 3.102.2
  • 3.102.3
  • 3.102.4
  • 3.102.5
  • 3.102.6
  • 3.103.0
  • 3.103.1
  • 3.104.0
  • 3.104.1
  • 3.105.0
  • 3.105.1
  • 3.105.2
  • 3.106.0
  • 3.106.1
  • 3.107.0
  • 3.108.0
  • 3.108.1
  • 3.108.2
  • 3.108.3
  • 3.108.4
  • 3.108.5
  • 3.109.0
  • 3.110.0
  • 3.110.1
  • 3.110.2
  • 3.110.3
  • 3.110.4
  • 3.111.0
  • 3.112.0
  • 3.112.1
  • 3.112.2
  • 3.112.3
  • 3.112.4
  • 3.113.0
  • 3.114.0
  • 3.114.1
  • 3.114.2
  • 3.114.3
  • 3.114.4
  • 3.114.5
  • 3.114.6
  • 3.114.7
  • 3.115.0
  • 3.115.1
  • 3.115.2
  • 3.115.3
  • 3.115.4
  • 3.116.0
  • 3.116.1
  • 3.117.0
  • 3.117.1
  • 3.117.2
  • 3.117.3
  • 3.118.0
  • 3.118.1
  • 3.119.0
  • 3.120.0
  • 3.121.0
  • 3.51.5
  • 3.52.0
  • 3.52.1
  • 3.53.0
  • 3.54.0
  • 3.55.0
  • 3.55.1
  • 3.55.2
  • 3.55.3
  • 3.55.4
102 results

Target

Select target project
  • oss/libraries/javascript/monster
1 result
Select Git revision
  • 1.31
  • master
  • 1.10.0
  • 1.30.1
  • 1.31.0
  • 1.8.0
  • 1.9.0
  • 3.100.0
  • 3.100.1
  • 3.100.10
  • 3.100.11
  • 3.100.12
  • 3.100.13
  • 3.100.14
  • 3.100.15
  • 3.100.16
  • 3.100.17
  • 3.100.18
  • 3.100.19
  • 3.100.2
  • 3.100.20
  • 3.100.3
  • 3.100.4
  • 3.100.5
  • 3.100.6
  • 3.100.7
  • 3.100.8
  • 3.100.9
  • 3.101.0
  • 3.101.1
  • 3.101.2
  • 3.101.3
  • 3.102.0
  • 3.102.1
  • 3.102.2
  • 3.102.3
  • 3.102.4
  • 3.102.5
  • 3.102.6
  • 3.103.0
  • 3.103.1
  • 3.104.0
  • 3.104.1
  • 3.105.0
  • 3.105.1
  • 3.105.2
  • 3.106.0
  • 3.106.1
  • 3.107.0
  • 3.108.0
  • 3.108.1
  • 3.108.2
  • 3.108.3
  • 3.108.4
  • 3.108.5
  • 3.109.0
  • 3.110.0
  • 3.110.1
  • 3.110.2
  • 3.110.3
  • 3.110.4
  • 3.111.0
  • 3.112.0
  • 3.112.1
  • 3.112.2
  • 3.112.3
  • 3.112.4
  • 3.113.0
  • 3.114.0
  • 3.114.1
  • 3.114.2
  • 3.114.3
  • 3.114.4
  • 3.114.5
  • 3.114.6
  • 3.114.7
  • 3.115.0
  • 3.115.1
  • 3.115.2
  • 3.115.3
  • 3.115.4
  • 3.116.0
  • 3.116.1
  • 3.117.0
  • 3.117.1
  • 3.117.2
  • 3.117.3
  • 3.118.0
  • 3.118.1
  • 3.119.0
  • 3.120.0
  • 3.121.0
  • 3.51.5
  • 3.52.0
  • 3.52.1
  • 3.53.0
  • 3.54.0
  • 3.55.0
  • 3.55.1
  • 3.55.2
  • 3.55.3
  • 3.55.4
102 results
Show changes
Showing
with 633 additions and 801 deletions
...@@ -9,13 +9,13 @@ import {internalSymbol,instanceSymbol} from "../../constants.mjs"; ...@@ -9,13 +9,13 @@ import {internalSymbol,instanceSymbol} from "../../constants.mjs";
import { validateString } from "../../types/validate.mjs"; import { validateString } from "../../types/validate.mjs";
import { Datasource } from "../datasource.mjs"; import { Datasource } from "../datasource.mjs";
export {Storage, storageObjectSymbol} export { Storage, storageObjectSymbol };
/** /**
* @private * @private
* @type {symbol} * @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. * The class represents a record.
...@@ -27,7 +27,6 @@ const storageObjectSymbol = Symbol.for ('@schukai/monster/data/datasource/stora ...@@ -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. * @summary The Storage class encapsulates the access to data objects over WebStorageAPI.
*/ */
class Storage extends Datasource { class Storage extends Datasource {
/** /**
* *
* @param {string} key LocalStorage Key * @param {string} key LocalStorage Key
...@@ -35,7 +34,7 @@ class Storage extends Datasource { ...@@ -35,7 +34,7 @@ class Storage extends Datasource {
*/ */
constructor(key) { constructor(key) {
super(); super();
this.setOption('key', validateString(key)); this.setOption("key", validateString(key));
} }
/** /**
...@@ -62,7 +61,7 @@ class Storage extends Datasource { ...@@ -62,7 +61,7 @@ class Storage extends Datasource {
* @private * @private
*/ */
[storageObjectSymbol]() { [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 { ...@@ -77,11 +76,10 @@ class Storage extends Datasource {
const storage = self[storageObjectSymbol](); const storage = self[storageObjectSymbol]();
return new Promise(function (resolve) { return new Promise(function (resolve) {
const data = JSON.parse(storage.getItem(self.getOption('key'))); const data = JSON.parse(storage.getItem(self.getOption("key")));
self.set(data ?? {}); self.set(data ?? {});
resolve(); resolve();
}) });
} }
/** /**
...@@ -94,16 +92,15 @@ class Storage extends Datasource { ...@@ -94,16 +92,15 @@ class Storage extends Datasource {
const storage = self[storageObjectSymbol](); const storage = self[storageObjectSymbol]();
return new Promise(function (resolve) { return new Promise(function (resolve) {
const data = self.get(); const data = self.get();
if (data === undefined) { if (data === undefined) {
storage.removeItem(self.getOption('key')); storage.removeItem(self.getOption("key"));
} else { } else {
storage.setItem(self.getOption('key'), JSON.stringify(data)); storage.setItem(self.getOption("key"), JSON.stringify(data));
} }
resolve(); resolve();
}) });
} }
/** /**
...@@ -111,7 +108,6 @@ class Storage extends Datasource { ...@@ -111,7 +108,6 @@ class Storage extends Datasource {
*/ */
getClone() { getClone() {
const self = this; const self = this;
return new Storage(self[internalSymbol].getRealSubject()['options'].key); return new Storage(self[internalSymbol].getRealSubject()["options"].key);
} }
} }
...@@ -10,7 +10,7 @@ import {getGlobalObject} from "../../../types/global.mjs"; ...@@ -10,7 +10,7 @@ import {getGlobalObject} from "../../../types/global.mjs";
import { Datasource } from "../../datasource.mjs"; import { Datasource } from "../../datasource.mjs";
import { Storage, storageObjectSymbol } from "../storage.mjs"; import { Storage, storageObjectSymbol } from "../storage.mjs";
export {LocalStorage} export { LocalStorage };
/** /**
* The LocalStorage Datasource provides a data store in the browser localStorage. * The LocalStorage Datasource provides a data store in the browser localStorage.
...@@ -22,14 +22,13 @@ export {LocalStorage} ...@@ -22,14 +22,13 @@ export {LocalStorage}
* @summary The LocalStorage class encapsulates the access to data objects. * @summary The LocalStorage class encapsulates the access to data objects.
*/ */
class LocalStorage extends Storage { class LocalStorage extends Storage {
/** /**
* @throws {Error} this method must be implemented by derived classes. * @throws {Error} this method must be implemented by derived classes.
* @return {external:localStorage} * @return {external:localStorage}
* @private * @private
*/ */
[storageObjectSymbol]() { [storageObjectSymbol]() {
return getGlobalObject('localStorage'); return getGlobalObject("localStorage");
} }
/** /**
...@@ -47,8 +46,6 @@ class LocalStorage extends Storage { ...@@ -47,8 +46,6 @@ class LocalStorage extends Storage {
*/ */
getClone() { getClone() {
const self = this; const self = this;
return new LocalStorage(self[internalSymbol].getRealSubject()['options'].key); return new LocalStorage(self[internalSymbol].getRealSubject()["options"].key);
} }
} }
...@@ -10,7 +10,7 @@ import {getGlobalObject} from "../../../types/global.mjs"; ...@@ -10,7 +10,7 @@ import {getGlobalObject} from "../../../types/global.mjs";
import { Datasource } from "../../datasource.mjs"; import { Datasource } from "../../datasource.mjs";
import { Storage, storageObjectSymbol } from "../storage.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. * The SessionStorage class provides a data source that uses the SessionStorage API on the client.
...@@ -22,14 +22,13 @@ export {SessionStorage} ...@@ -22,14 +22,13 @@ export {SessionStorage}
* @summary The LocalStorage class encapsulates the access to data objects. * @summary The LocalStorage class encapsulates the access to data objects.
*/ */
class SessionStorage extends Storage { class SessionStorage extends Storage {
/** /**
* @throws {Error} this method must be implemented by derived classes. * @throws {Error} this method must be implemented by derived classes.
* @return {external:sessionStorage} * @return {external:sessionStorage}
* @private * @private
*/ */
[storageObjectSymbol]() { [storageObjectSymbol]() {
return getGlobalObject('sessionStorage'); return getGlobalObject("sessionStorage");
} }
/** /**
...@@ -48,7 +47,6 @@ class SessionStorage extends Storage { ...@@ -48,7 +47,6 @@ class SessionStorage extends Storage {
*/ */
getClone() { getClone() {
const self = this; const self = this;
return new SessionStorage(self[internalSymbol].getRealSubject()['options'].key); return new SessionStorage(self[internalSymbol].getRealSubject()["options"].key);
} }
} }
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
import { isArray, isObject } from "../types/is.mjs"; import { isArray, isObject } from "../types/is.mjs";
import { typeOf } from "../types/typeof.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. * 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} ...@@ -25,7 +25,7 @@ export {diff}
* @memberOf Monster.Data * @memberOf Monster.Data
*/ */
function diff(first, second) { function diff(first, second) {
return doDiff(first, second) return doDiff(first, second);
} }
/** /**
...@@ -54,37 +54,30 @@ function getKeys(a, b, type) { ...@@ -54,37 +54,30 @@ function getKeys(a, b, type) {
* @return {array} * @return {array}
*/ */
function doDiff(a, b, path, diff) { function doDiff(a, b, path, diff) {
let typeA = typeOf(a);
let typeA = typeOf(a) let typeB = typeOf(b);
let typeB = typeOf(b)
const currPath = path || []; const currPath = path || [];
const currDiff = diff || []; const currDiff = diff || [];
if (typeA === typeB && (typeA === 'object' || typeA ==='array')) { if (typeA === typeB && (typeA === "object" || typeA === "array")) {
getKeys(a, b, typeA).forEach((v) => { getKeys(a, b, typeA).forEach((v) => {
if (!Object.prototype.hasOwnProperty.call(a, v)) {
if (!(Object.prototype.hasOwnProperty.call(a, v))) { currDiff.push(buildResult(a[v], b[v], "add", currPath.concat(v)));
currDiff.push(buildResult(a[v], b[v], 'add', currPath.concat(v))); } else if (!Object.prototype.hasOwnProperty.call(b, v)) {
} else if (!(Object.prototype.hasOwnProperty.call(b, v))) { currDiff.push(buildResult(a[v], b[v], "delete", currPath.concat(v)));
currDiff.push(buildResult(a[v], b[v], 'delete', currPath.concat(v)));
} else { } else {
doDiff(a[v], b[v], currPath.concat(v), currDiff); doDiff(a[v], b[v], currPath.concat(v), currDiff);
} }
}); });
} else { } else {
const o = getOperator(a, b, typeA, typeB); const o = getOperator(a, b, typeA, typeB);
if (o !== undefined) { if (o !== undefined) {
currDiff.push(buildResult(a, b, o, path)); currDiff.push(buildResult(a, b, o, path));
} }
} }
return currDiff; return currDiff;
} }
/** /**
...@@ -97,16 +90,15 @@ function doDiff(a, b, path, diff) { ...@@ -97,16 +90,15 @@ function doDiff(a, b, path, diff) {
* @private * @private
*/ */
function buildResult(a, b, operator, path) { function buildResult(a, b, operator, path) {
const result = { const result = {
operator, operator,
path, path,
}; };
if (operator !== 'add') { if (operator !== "add") {
result.first = { result.first = {
value: a, value: a,
type: typeof a type: typeof a,
}; };
if (isObject(a)) { if (isObject(a)) {
...@@ -117,10 +109,10 @@ function buildResult(a, b, operator, path) { ...@@ -117,10 +109,10 @@ function buildResult(a, b, operator, path) {
} }
} }
if (operator === 'add' || operator === 'update') { if (operator === "add" || operator === "update") {
result.second = { result.second = {
value: b, value: b,
type: typeof b type: typeof b,
}; };
if (isObject(b)) { if (isObject(b)) {
...@@ -129,7 +121,6 @@ function buildResult(a, b, operator, path) { ...@@ -129,7 +121,6 @@ function buildResult(a, b, operator, path) {
result.second.instance = name; result.second.instance = name;
} }
} }
} }
return result; return result;
...@@ -142,7 +133,6 @@ function buildResult(a, b, operator, path) { ...@@ -142,7 +133,6 @@ function buildResult(a, b, operator, path) {
* @return {boolean} * @return {boolean}
*/ */
function isNotEqual(a, b) { function isNotEqual(a, b) {
if (typeof a !== typeof b) { if (typeof a !== typeof b) {
return true; return true;
} }
...@@ -161,7 +151,6 @@ function isNotEqual(a, b) { ...@@ -161,7 +151,6 @@ function isNotEqual(a, b) {
* @return {string|undefined} * @return {string|undefined}
*/ */
function getOperator(a, b) { function getOperator(a, b) {
/** /**
* @type {string|undefined} * @type {string|undefined}
*/ */
...@@ -177,14 +166,13 @@ function getOperator(a, b) { ...@@ -177,14 +166,13 @@ function getOperator(a, b) {
*/ */
let typeB = typeof b; let typeB = typeof b;
if (typeA === 'undefined' && typeB !== 'undefined') { if (typeA === "undefined" && typeB !== "undefined") {
operator = 'add'; operator = "add";
} else if (typeA !== 'undefined' && typeB === 'undefined') { } else if (typeA !== "undefined" && typeB === "undefined") {
operator = 'delete'; operator = "delete";
} else if (isNotEqual(a, b)) { } else if (isNotEqual(a, b)) {
operator = 'update'; operator = "update";
} }
return operator; return operator;
} }
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
import { isArray, isObject } from "../types/is.mjs"; import { isArray, isObject } from "../types/is.mjs";
import { typeOf } from "../types/typeof.mjs"; import { typeOf } from "../types/typeof.mjs";
export {extend} export { extend };
/** /**
* Extend copies all enumerable own properties from one or * Extend copies all enumerable own properties from one or
...@@ -23,15 +23,21 @@ export {extend} ...@@ -23,15 +23,21 @@ export {extend}
* @memberOf Monster.Data * @memberOf Monster.Data
* @throws {Error} unsupported argument * @throws {Error} unsupported argument
* @throws {Error} type mismatch * @throws {Error} type mismatch
* @throws {Error} unsupported argument
*/ */
function extend() { function extend(...args) {
let o, i; let o;
let i;
if (typeof args !== "object" || args[0] === null) {
throw new Error(`unsupported argument ${JSON.stringify(args[0])}`);
}
for (i = 0; i < arguments.length; i++) { for (i = 0; i < args.length; i++) {
let a = arguments[i]; let a = args[i];
if (!(isObject(a) || isArray(a))) { if (!(isObject(a) || isArray(a))) {
throw new Error('unsupported argument ' + JSON.stringify(a)); throw new Error(`unsupported argument ${JSON.stringify(a)}`);
} }
if (o === undefined) { if (o === undefined) {
...@@ -40,15 +46,13 @@ function extend() { ...@@ -40,15 +46,13 @@ function extend() {
} }
for (let k in a) { for (let k in a) {
let v = a?.[k]; let v = a?.[k];
if (v === o?.[k]) { if (v === o?.[k]) {
continue; continue;
} }
if ((isObject(v)&&typeOf(v)==='object') || isArray(v)) { if ((isObject(v) && typeOf(v) === "object") || isArray(v)) {
if (o[k] === undefined) { if (o[k] === undefined) {
if (isArray(v)) { if (isArray(v)) {
o[k] = []; o[k] = [];
...@@ -57,16 +61,18 @@ function extend() { ...@@ -57,16 +61,18 @@ function extend() {
} }
} else { } else {
if (typeOf(o[k]) !== typeOf(v)) { 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); o[k] = extend(o[k], v);
} else { } else {
o[k] = v; o[k] = v;
} }
} }
} }
......
...@@ -3,8 +3,6 @@ ...@@ -3,8 +3,6 @@
* SPDX-License-Identifier: AGPL-3.0 * SPDX-License-Identifier: AGPL-3.0
*/ */
/** /**
* In this namespace you will find classes and methods for handling data. * In this namespace you will find classes and methods for handling data.
* *
......
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
import {Base} from '../types/base.mjs'; import { Base } from "../types/base.mjs";
import {isArray, isInteger, isObject, isPrimitive} from '../types/is.mjs'; import { isArray, isInteger, isObject, isPrimitive } from "../types/is.mjs";
import { Stack } from "../types/stack.mjs"; import { Stack } from "../types/stack.mjs";
import {validateInteger, validateString} from '../types/validate.mjs'; import { validateInteger, validateString } from "../types/validate.mjs";
export {Pathfinder, DELIMITER, WILDCARD} export { Pathfinder, DELIMITER, WILDCARD };
/** /**
* path separator * path separator
...@@ -18,13 +18,13 @@ export {Pathfinder, DELIMITER, WILDCARD} ...@@ -18,13 +18,13 @@ export {Pathfinder, DELIMITER, WILDCARD}
* @private * @private
* @type {string} * @type {string}
*/ */
const DELIMITER = '.'; const DELIMITER = ".";
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const WILDCARD = '*'; const WILDCARD = "*";
/** /**
* Pathfinder is a class to find a path to an object. * Pathfinder is a class to find a path to an object.
...@@ -72,7 +72,6 @@ const WILDCARD = '*'; ...@@ -72,7 +72,6 @@ const WILDCARD = '*';
* @memberOf Monster.Data * @memberOf Monster.Data
*/ */
class Pathfinder extends Base { class Pathfinder extends Base {
/** /**
* @param {array|object|Map|Set} value * @param {array|object|Map|Set} value
* @since 1.4.0 * @since 1.4.0
...@@ -82,7 +81,7 @@ class Pathfinder extends Base { ...@@ -82,7 +81,7 @@ class Pathfinder extends Base {
super(); super();
if (isPrimitive(object)) { 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; this.object = object;
...@@ -165,16 +164,12 @@ class Pathfinder extends Base { ...@@ -165,16 +164,12 @@ class Pathfinder extends Base {
try { try {
getValueViaPath.call(this, this.object, path, true); getValueViaPath.call(this, this.object, path, true);
return true; return true;
} catch (e) { } catch (e) {}
}
return false; return false;
} }
} }
/** /**
* *
* @param {*} subject * @param {*} subject
...@@ -187,12 +182,11 @@ class Pathfinder extends Base { ...@@ -187,12 +182,11 @@ class Pathfinder extends Base {
* @private * @private
*/ */
function iterate(subject, path, check) { function iterate(subject, path, check) {
const result = new Map();
const result = new Map;
if (isObject(subject) || isArray(subject)) { if (isObject(subject) || isArray(subject)) {
for (const [key, value] of Object.entries(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 { } else {
let key = path.split(DELIMITER).shift(); let key = path.split(DELIMITER).shift();
...@@ -200,8 +194,6 @@ function iterate(subject, path, check) { ...@@ -200,8 +194,6 @@ function iterate(subject, path, check) {
} }
return result; return result;
} }
/** /**
...@@ -216,12 +208,11 @@ function iterate(subject, path, check) { ...@@ -216,12 +208,11 @@ function iterate(subject, path, check) {
* @private * @private
*/ */
function getValueViaPath(subject, path, check) { function getValueViaPath(subject, path, check) {
if (path === "") { if (path === "") {
return subject; return subject;
} }
let parts = path.split(DELIMITER) let parts = path.split(DELIMITER);
let current = parts.shift(); let current = parts.shift();
if (current === this.wildCard) { if (current === this.wildCard) {
...@@ -229,51 +220,43 @@ function getValueViaPath(subject, path, check) { ...@@ -229,51 +220,43 @@ function getValueViaPath(subject, path, check) {
} }
if (isObject(subject) || isArray(subject)) { if (isObject(subject) || isArray(subject)) {
let anchor; let anchor;
if (subject instanceof Map || subject instanceof WeakMap) { if (subject instanceof Map || subject instanceof WeakMap) {
anchor = subject.get(current); anchor = subject.get(current);
} else if (subject instanceof Set || subject instanceof WeakSet) { } else if (subject instanceof Set || subject instanceof WeakSet) {
current = parseInt(current); current = parseInt(current);
validateInteger(current) validateInteger(current);
anchor = [...subject]?.[current]; anchor = [...subject]?.[current];
} else if (typeof WeakRef === "function" && subject instanceof WeakRef) {
} else if (typeof WeakRef === 'function' && subject instanceof WeakRef) { throw Error("unsupported action for this data type");
throw Error('unsupported action for this data type');
} else if (isArray(subject)) { } else if (isArray(subject)) {
current = parseInt(current); current = parseInt(current);
validateInteger(current) validateInteger(current);
anchor = subject?.[current]; anchor = subject?.[current];
} else { } else {
anchor = subject?.[current]; anchor = subject?.[current];
} }
if (isObject(anchor) || isArray(anchor)) { 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) { if (parts.length > 0) {
throw Error("the journey is not at its end (" + parts.join(DELIMITER) + ")"); throw Error(`the journey is not at its end (${parts.join(DELIMITER)})`);
} }
if (check === true) { if (check === true) {
const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(subject), current); const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(subject), current);
if (!subject.hasOwnProperty(current) && descriptor === undefined) { if (!subject.hasOwnProperty(current) && descriptor === undefined) {
throw Error('unknown value'); throw Error("unknown value");
} }
} }
return anchor; return anchor;
} }
throw TypeError("unsupported type " + typeof subject) throw TypeError(`unsupported type ${typeof subject}`);
} }
/** /**
...@@ -289,23 +272,19 @@ function getValueViaPath(subject, path, check) { ...@@ -289,23 +272,19 @@ function getValueViaPath(subject, path, check) {
* @private * @private
*/ */
function setValueViaPath(object, path, value) { function setValueViaPath(object, path, value) {
validateString(path); validateString(path);
let parts = path.split(DELIMITER) let parts = path.split(DELIMITER);
let last = parts.pop(); let last = parts.pop();
let subpath = parts.join(DELIMITER); let subpath = parts.join(DELIMITER);
let stack = new Stack() let stack = new Stack();
let current = subpath; let current = subpath;
while (true) { while (true) {
try { try {
getValueViaPath.call(this, object, current, true) getValueViaPath.call(this, object, current, true);
break; break;
} catch (e) { } catch (e) {}
}
stack.push(current); stack.push(current);
parts.pop(); parts.pop();
...@@ -323,7 +302,6 @@ function setValueViaPath(object, path, value) { ...@@ -323,7 +302,6 @@ function setValueViaPath(object, path, value) {
if (isInteger(parseInt(n))) { if (isInteger(parseInt(n))) {
obj = []; obj = [];
} }
} }
setValueViaPath.call(this, object, current, obj); setValueViaPath.call(this, object, current, obj);
...@@ -331,27 +309,23 @@ function setValueViaPath(object, path, value) { ...@@ -331,27 +309,23 @@ function setValueViaPath(object, path, value) {
let anchor = getValueViaPath.call(this, object, subpath); let anchor = getValueViaPath.call(this, object, subpath);
if (!isObject(object) && !isArray(object)) { if (!(isObject(object) || isArray(object))) {
throw TypeError("unsupported type: " + typeof object); throw TypeError(`unsupported type: ${typeof object}`);
} }
if (anchor instanceof Map || anchor instanceof WeakMap) { if (anchor instanceof Map || anchor instanceof WeakMap) {
anchor.set(last, value); anchor.set(last, value);
} else if (anchor instanceof Set || anchor instanceof WeakSet) { } else if (anchor instanceof Set || anchor instanceof WeakSet) {
anchor.append(value) anchor.append(value);
} else if (typeof WeakRef === "function" && anchor instanceof WeakRef) {
} else if (typeof WeakRef === 'function' && anchor instanceof WeakRef) { throw Error("unsupported action for this data type");
throw Error('unsupported action for this data type');
} else if (isArray(anchor)) { } else if (isArray(anchor)) {
last = parseInt(last); last = parseInt(last);
validateInteger(last) validateInteger(last);
assignProperty(anchor, last, value); assignProperty(anchor, last, value);
} else { } else {
assignProperty(anchor, last, value); assignProperty(anchor, last, value);
} }
} }
/** /**
...@@ -361,7 +335,6 @@ function setValueViaPath(object, path, value) { ...@@ -361,7 +335,6 @@ function setValueViaPath(object, path, value) {
* @param {*} value * @param {*} value
*/ */
function assignProperty(object, key, value) { function assignProperty(object, key, value) {
if (!object.hasOwnProperty(key)) { if (!object.hasOwnProperty(key)) {
object[key] = value; object[key] = value;
return; return;
...@@ -372,7 +345,6 @@ function assignProperty(object, key, value) { ...@@ -372,7 +345,6 @@ function assignProperty(object, key, value) {
} }
object[key] = value; object[key] = value;
} }
/** /**
...@@ -389,8 +361,7 @@ function assignProperty(object, key, value) { ...@@ -389,8 +361,7 @@ function assignProperty(object, key, value) {
* @private * @private
*/ */
function deleteValueViaPath(object, path) { function deleteValueViaPath(object, path) {
const parts = path.split(DELIMITER);
const parts = path.split(DELIMITER)
let last = parts.pop(); let last = parts.pop();
const subpath = parts.join(DELIMITER); const subpath = parts.join(DELIMITER);
...@@ -398,16 +369,18 @@ function deleteValueViaPath(object, path) { ...@@ -398,16 +369,18 @@ function deleteValueViaPath(object, path) {
if (anchor instanceof Map) { if (anchor instanceof Map) {
anchor.delete(last); anchor.delete(last);
} else if (anchor instanceof Set || anchor instanceof WeakMap || anchor instanceof WeakSet || (typeof WeakRef === 'function' && anchor instanceof WeakRef)) { } else if (
throw Error('unsupported action for this data type'); 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)) { } else if (isArray(anchor)) {
last = parseInt(last); last = parseInt(last);
validateInteger(last) validateInteger(last);
delete anchor[last]; delete anchor[last];
} else { } else {
delete anchor[last]; delete anchor[last];
} }
} }
...@@ -5,17 +5,17 @@ ...@@ -5,17 +5,17 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
import {Base} from '../types/base.mjs'; import { Base } from "../types/base.mjs";
import {validateString} from '../types/validate.mjs'; import { validateString } from "../types/validate.mjs";
import {Transformer} from './transformer.mjs'; import { Transformer } from "./transformer.mjs";
export {Pipe} export { Pipe };
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const DELIMITER = '|'; const DELIMITER = "|";
/** /**
* The pipe class makes it possible to combine several processing steps. * The pipe class makes it possible to combine several processing steps.
...@@ -32,7 +32,6 @@ const DELIMITER = '|'; ...@@ -32,7 +32,6 @@ const DELIMITER = '|';
* @memberOf Monster.Data * @memberOf Monster.Data
*/ */
class Pipe extends Base { class Pipe extends Base {
/** /**
* @param {string} pipe a pipe consists of commands whose input and output are connected with the pipe symbol `|`. * @param {string} pipe a pipe consists of commands whose input and output are connected with the pipe symbol `|`.
* @throws {TypeError} * @throws {TypeError}
...@@ -44,8 +43,6 @@ class Pipe extends Base { ...@@ -44,8 +43,6 @@ class Pipe extends Base {
this.pipe = pipe.split(DELIMITER).map((v) => { this.pipe = pipe.split(DELIMITER).map((v) => {
return new Transformer(v); return new Transformer(v);
}); });
} }
/** /**
...@@ -57,7 +54,6 @@ class Pipe extends Base { ...@@ -57,7 +54,6 @@ class Pipe extends Base {
* @throws {TypeError} value is not a function * @throws {TypeError} value is not a function
*/ */
setCallback(name, callback, context) { setCallback(name, callback, context) {
for (const [, t] of Object.entries(this.pipe)) { for (const [, t] of Object.entries(this.pipe)) {
t.setCallback(name, callback, context); t.setCallback(name, callback, context);
} }
......
/** /**
* Copyright schukai GmbH and contributors 2022. All Rights Reserved. * Copyright schukai GmbH and contributors 2022. All Rights Reserved.
* Node module: @schukai/monster * Node module: @schukai/monster
...@@ -7,22 +5,21 @@ ...@@ -7,22 +5,21 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
import { Base } from "../types/base.mjs";
import {Base} from '../types/base.mjs';
import { getGlobal, getGlobalObject } from "../types/global.mjs"; import { getGlobal, getGlobalObject } from "../types/global.mjs";
import {ID} from '../types/id.mjs'; import { ID } from "../types/id.mjs";
import {isArray, isObject, isString} from '../types/is.mjs'; import { isArray, isObject, isString } from "../types/is.mjs";
import { import {
validateFunction, validateFunction,
validateInteger, validateInteger,
validateObject, validateObject,
validatePrimitive, validatePrimitive,
validateString validateString,
} from '../types/validate.mjs'; } from "../types/validate.mjs";
import { clone } from "../util/clone.mjs"; import { clone } from "../util/clone.mjs";
import { Pathfinder } from "./pathfinder.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. * The transformer class is a swiss army knife for manipulating values. especially in combination with the pipe, processing chains can be built up.
...@@ -120,9 +117,8 @@ class Transformer extends Base { ...@@ -120,9 +117,8 @@ class Transformer extends Base {
constructor(definition) { constructor(definition) {
super(); super();
this.args = disassemble(definition); this.args = disassemble(definition);
this.command = this.args.shift() this.command = this.args.shift();
this.callbacks = new Map(); this.callbacks = new Map();
} }
/** /**
...@@ -135,8 +131,8 @@ class Transformer extends Base { ...@@ -135,8 +131,8 @@ class Transformer extends Base {
* @throws {TypeError} value is not a function * @throws {TypeError} value is not a function
*/ */
setCallback(name, callback, context) { setCallback(name, callback, context) {
validateString(name) validateString(name);
validateFunction(callback) validateFunction(callback);
if (context !== undefined) { if (context !== undefined) {
validateObject(context); validateObject(context);
...@@ -159,7 +155,7 @@ class Transformer extends Base { ...@@ -159,7 +155,7 @@ class Transformer extends Base {
* @throws {Error} type not supported * @throws {Error} type not supported
*/ */
run(value) { run(value) {
return transform.apply(this, [value]) return transform.apply(this, [value]);
} }
} }
...@@ -170,33 +166,31 @@ class Transformer extends Base { ...@@ -170,33 +166,31 @@ class Transformer extends Base {
* @private * @private
*/ */
function disassemble(command) { function disassemble(command) {
validateString(command); validateString(command);
let placeholder = new Map; let placeholder = new Map();
const regex = /((?<pattern>\\(?<char>.)){1})/mig; const regex = /((?<pattern>\\(?<char>.)){1})/gim;
// The separator for args must be escaped // The separator for args must be escaped
// undefined string which should not occur normally and is also not a regex // 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) { for (let m of result) {
let g = m?.['groups']; let g = m?.["groups"];
if (!isObject(g)) { if (!isObject(g)) {
continue; continue;
} }
let p = g?.['pattern']; let p = g?.["pattern"];
let c = g?.['char']; let c = g?.["char"];
if (p && c) { if (p && c) {
let r = '__' + new ID().toString() + '__'; let r = `__${new ID().toString()}__`;
placeholder.set(r, c); placeholder.set(r, c);
command = command.replace(p, r); command = command.replace(p, r);
} }
} }
let parts = command.split(':'); let parts = command.split(":");
parts = parts.map(function (value) { parts = parts.map(function (value) {
let v = value.trim(); let v = value.trim();
...@@ -204,11 +198,9 @@ function disassemble(command) { ...@@ -204,11 +198,9 @@ function disassemble(command) {
v = v.replace(k[0], k[1]); v = v.replace(k[0], k[1]);
} }
return v; return v;
}); });
return parts return parts;
} }
/** /**
...@@ -219,12 +211,11 @@ function disassemble(command) { ...@@ -219,12 +211,11 @@ function disassemble(command) {
* @private * @private
*/ */
function convertToString(value) { function convertToString(value) {
if (isObject(value) && value.hasOwnProperty("toString")) {
if (isObject(value) && value.hasOwnProperty('toString')) {
value = value.toString(); value = value.toString();
} }
validateString(value) validateString(value);
return value; return value;
} }
...@@ -239,59 +230,56 @@ function convertToString(value) { ...@@ -239,59 +230,56 @@ function convertToString(value) {
* @throws {Error} missing key parameter * @throws {Error} missing key parameter
*/ */
function transform(value) { function transform(value) {
const console = getGlobalObject("console");
const console = getGlobalObject('console');
let args = clone(this.args); let args = clone(this.args);
let key, defaultValue; let key;
let defaultValue;
switch (this.command) { switch (this.command) {
case "static":
return this.args.join(":");
case 'static': case "tolower":
return this.args.join(':'); case "strtolower":
case "tolowercase":
case 'tolower': validateString(value);
case 'strtolower':
case 'tolowercase':
validateString(value)
return value.toLowerCase(); return value.toLowerCase();
case 'toupper': case "toupper":
case 'strtoupper': case "strtoupper":
case 'touppercase': case "touppercase":
validateString(value) validateString(value);
return value.toUpperCase(); return value.toUpperCase();
case 'tostring': case "tostring":
return "" + value; return `${value}`;
case 'tointeger': case "tointeger":
let n = parseInt(value); let n = parseInt(value);
validateInteger(n); validateInteger(n);
return n return n;
case 'tojson': case "tojson":
return JSON.stringify(value); return JSON.stringify(value);
case 'fromjson': case "fromjson":
return JSON.parse(value); return JSON.parse(value);
case 'trim': case "trim":
validateString(value) validateString(value);
return value.trim(); return value.trim();
case 'rawurlencode': case "rawurlencode":
validateString(value) validateString(value);
return encodeURIComponent(value) return encodeURIComponent(value)
.replace(/!/g, '%21') .replace(/!/g, "%21")
.replace(/'/g, '%27') .replace(/'/g, "%27")
.replace(/\(/g, '%28') .replace(/\(/g, "%28")
.replace(/\)/g, '%29') .replace(/\)/g, "%29")
.replace(/\*/g, '%2A'); .replace(/\*/g, "%2A");
case 'call':
case "call":
/** /**
* callback-definition * callback-definition
* function callback(value, ...args) { * function callback(value, ...args) {
...@@ -307,9 +295,9 @@ function transform(value) { ...@@ -307,9 +295,9 @@ function transform(value) {
callback = value[callbackName]; callback = value[callbackName];
} else if (this.callbacks.has(callbackName)) { } else if (this.callbacks.has(callbackName)) {
let s = this.callbacks.get(callbackName); let s = this.callbacks.get(callbackName);
callback = s?.['callback']; callback = s?.["callback"];
context = s?.['context']; context = s?.["context"];
} else if (typeof window === 'object' && window.hasOwnProperty(callbackName)) { } else if (typeof window === "object" && window.hasOwnProperty(callbackName)) {
callback = window[callbackName]; callback = window[callbackName];
} }
validateFunction(callback); validateFunction(callback);
...@@ -317,119 +305,117 @@ function transform(value) { ...@@ -317,119 +305,117 @@ function transform(value) {
args.unshift(value); args.unshift(value);
return callback.call(context, ...args); return callback.call(context, ...args);
case 'plain': case "plain":
case 'plaintext': case "plaintext":
validateString(value); validateString(value);
let doc = new DOMParser().parseFromString(value, 'text/html'); let doc = new DOMParser().parseFromString(value, "text/html");
return doc.body.textContent || ""; return doc.body.textContent || "";
case 'if': case "if":
case '?': case "?":
validatePrimitive(value); validatePrimitive(value);
let trueStatement = (args.shift() || undefined); let trueStatement = args.shift() || undefined;
let falseStatement = (args.shift() || undefined); let falseStatement = args.shift() || undefined;
if (trueStatement === 'value') { if (trueStatement === "value") {
trueStatement = value; trueStatement = value;
} }
if (trueStatement === '\\value') { if (trueStatement === "\\value") {
trueStatement = 'value'; trueStatement = "value";
} }
if (falseStatement === 'value') { if (falseStatement === "value") {
falseStatement = value; falseStatement = value;
} }
if (falseStatement === '\\value') { if (falseStatement === "\\value") {
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; return condition ? trueStatement : falseStatement;
case "ucfirst":
case 'ucfirst':
validateString(value); validateString(value);
let firstchar = value.charAt(0).toUpperCase(); let firstchar = value.charAt(0).toUpperCase();
return firstchar + value.substr(1); return firstchar + value.substr(1);
case 'ucwords': case "ucwords":
validateString(value); validateString(value);
return value.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function (v) { return value.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function (v) {
return v.toUpperCase(); return v.toUpperCase();
}); });
case 'count': case "count":
case 'length': case "length":
if ((isString(value) || isObject(value) || isArray(value)) && value.hasOwnProperty("length")) {
if ((isString(value) || isObject(value) || isArray(value)) && value.hasOwnProperty('length')) {
return value.length; return value.length;
} }
throw new TypeError("unsupported type " + typeof value); throw new TypeError(`unsupported type ${typeof value}`);
case 'to-base64': case "to-base64":
case 'btoa': case "btoa":
case 'base64': case "base64":
return btoa(convertToString(value)); return btoa(convertToString(value));
case 'atob': case "atob":
case 'from-base64': case "from-base64":
return atob(convertToString(value)); return atob(convertToString(value));
case 'empty': case "empty":
return ''; return "";
case 'undefined': case "undefined":
return undefined; return undefined;
case 'debug': case "debug":
if (isObject(console)) { if (isObject(console)) {
console.log(value); console.log(value);
} }
return value; return value;
case 'prefix': case "prefix":
validateString(value); validateString(value);
let prefix = args?.[0]; let prefix = args?.[0];
return prefix + value; return prefix + value;
case 'suffix': case "suffix":
validateString(value); validateString(value);
let suffix = args?.[0]; let suffix = args?.[0];
return value + suffix; return value + suffix;
case 'uniqid': case "uniqid":
return (new ID()).toString(); return new ID().toString();
case 'first-key':
case 'last-key':
case 'nth-last-key':
case 'nth-key':
case "first-key":
case "last-key":
case "nth-last-key":
case "nth-key":
if (!isObject(value)) { 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; key = 0;
} else if (this.command === 'last-key') { } else if (this.command === "last-key") {
key = keys.length - 1; key = keys.length - 1;
} else { } else {
key = validateInteger(parseInt(args.shift())); key = validateInteger(parseInt(args.shift()));
if (this.command === 'nth-last-key') { if (this.command === "nth-last-key") {
key = keys.length - key - 1; key = keys.length - key - 1;
} }
} }
defaultValue = (args.shift() || ''); defaultValue = args.shift() || "";
let useKey = keys?.[key]; let useKey = keys?.[key];
...@@ -439,18 +425,16 @@ function transform(value) { ...@@ -439,18 +425,16 @@ function transform(value) {
return defaultValue; return defaultValue;
case "key":
case 'key': case "property":
case 'property': case "index":
case 'index':
key = args.shift() || undefined; key = args.shift() || undefined;
if (key === 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 instanceof Map) {
if (!value.has(key)) { if (!value.has(key)) {
...@@ -460,7 +444,6 @@ function transform(value) { ...@@ -460,7 +444,6 @@ function transform(value) {
} }
if (isObject(value) || isArray(value)) { if (isObject(value) || isArray(value)) {
if (value?.[key]) { if (value?.[key]) {
return value?.[key]; return value?.[key];
} }
...@@ -468,22 +451,20 @@ function transform(value) { ...@@ -468,22 +451,20 @@ function transform(value) {
return defaultValue; return defaultValue;
} }
throw new Error("type not supported") throw new Error("type not supported");
case 'path-exists':
case "path-exists":
key = args.shift(); key = args.shift();
if (key === undefined) { if (key === undefined) {
throw new Error("missing key parameter") throw new Error("missing key parameter");
} }
return new Pathfinder(value).exists(key); return new Pathfinder(value).exists(key);
case 'path': case "path":
key = args.shift(); key = args.shift();
if (key === undefined) { if (key === undefined) {
throw new Error("missing key parameter") throw new Error("missing key parameter");
} }
let pf = new Pathfinder(value); let pf = new Pathfinder(value);
...@@ -494,9 +475,7 @@ function transform(value) { ...@@ -494,9 +475,7 @@ function transform(value) {
return pf.getVia(key); return pf.getVia(key);
case "substring":
case 'substring':
validateString(value); validateString(value);
let start = parseInt(args[0]) || 0; let start = parseInt(args[0]) || 0;
...@@ -504,11 +483,11 @@ function transform(value) { ...@@ -504,11 +483,11 @@ function transform(value) {
return value.substring(start, end); return value.substring(start, end);
case 'nop': case "nop":
return value; return value;
case '??': case "??":
case 'default': case "default":
if (value !== undefined && value !== null) { if (value !== undefined && value !== null) {
return value; return value;
} }
...@@ -516,34 +495,39 @@ function transform(value) { ...@@ -516,34 +495,39 @@ function transform(value) {
defaultValue = args.shift(); defaultValue = args.shift();
let defaultType = args.shift(); let defaultType = args.shift();
if (defaultType === undefined) { if (defaultType === undefined) {
defaultType = 'string'; defaultType = "string";
} }
switch (defaultType) { switch (defaultType) {
case 'int': case "int":
case 'integer': case "integer":
return parseInt(defaultValue); return parseInt(defaultValue);
case 'float': case "float":
return parseFloat(defaultValue); return parseFloat(defaultValue);
case 'undefined': case "undefined":
return undefined return undefined;
case 'bool': case "bool":
case 'boolean': case "boolean":
defaultValue = defaultValue.toLowerCase() defaultValue = defaultValue.toLowerCase();
return ((defaultValue !== 'undefined' && defaultValue !== '' && defaultValue !== 'off' && defaultValue !== 'false' && defaultValue !== 'false') || defaultValue === 'on' || defaultValue === 'true' || defaultValue === 'true'); return (
case 'string': (defaultValue !== "undefined" &&
return "" + defaultValue; defaultValue !== "" &&
defaultValue !== "off" &&
defaultValue !== "false" &&
defaultValue !== "false") ||
defaultValue === "on" ||
defaultValue === "true" ||
defaultValue === "true"
);
case "string":
return `${defaultValue}`;
case "object": case "object":
return JSON.parse(atob(defaultValue)); return JSON.parse(atob(defaultValue));
} }
throw new Error("type not supported") throw new Error("type not supported");
default: default:
throw new Error("unknown command " + this.command) throw new Error(`unknown command ${this.command}`);
} }
return value;
} }
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
import {Base} from '../types/base.mjs'; import { Base } from "../types/base.mjs";
import { getGlobalFunction } from "../types/global.mjs"; import { getGlobalFunction } from "../types/global.mjs";
import { ProxyObserver } from "../types/proxyobserver.mjs"; import { ProxyObserver } from "../types/proxyobserver.mjs";
import { validateInstance, validateString } from "../types/validate.mjs"; import { validateInstance, validateString } from "../types/validate.mjs";
export {ATTRIBUTEPREFIX,Assembler} export { ATTRIBUTEPREFIX, Assembler };
/** /**
* attribute prefix * attribute prefix
...@@ -30,7 +30,6 @@ const ATTRIBUTEPREFIX = "data-monster-"; ...@@ -30,7 +30,6 @@ const ATTRIBUTEPREFIX = "data-monster-";
* @summary Allows you to build an html fragment * @summary Allows you to build an html fragment
*/ */
class Assembler extends Base { class Assembler extends Base {
/** /**
* @param {DocumentFragment} fragment * @param {DocumentFragment} fragment
* @throws {TypeError} value is not an instance of * @throws {TypeError} value is not an instance of
...@@ -40,7 +39,7 @@ class Assembler extends Base { ...@@ -40,7 +39,7 @@ class Assembler extends Base {
constructor(fragment) { constructor(fragment) {
super(); super();
this.attributePrefix = ATTRIBUTEPREFIX; this.attributePrefix = ATTRIBUTEPREFIX;
validateInstance(fragment, getGlobalFunction('DocumentFragment')); validateInstance(fragment, getGlobalFunction("DocumentFragment"));
this.fragment = fragment; this.fragment = fragment;
} }
...@@ -71,7 +70,6 @@ class Assembler extends Base { ...@@ -71,7 +70,6 @@ class Assembler extends Base {
* @throws {TypeError} value is not an instance of * @throws {TypeError} value is not an instance of
*/ */
createDocumentFragment(data) { createDocumentFragment(data) {
if (data === undefined) { if (data === undefined) {
data = new ProxyObserver({}); data = new ProxyObserver({});
} }
...@@ -80,5 +78,4 @@ class Assembler extends Base { ...@@ -80,5 +78,4 @@ class Assembler extends Base {
let fragment = this.fragment.cloneNode(true); let fragment = this.fragment.cloneNode(true);
return fragment; return fragment;
} }
} }
...@@ -23,8 +23,8 @@ export { ...@@ -23,8 +23,8 @@ export {
replaceAttributeToken, replaceAttributeToken,
clearAttributeTokens, clearAttributeTokens,
findClosestByAttribute, findClosestByAttribute,
findClosestByClass findClosestByClass,
} };
/** /**
* Get the closest object link of a node * Get the closest object link of a node
...@@ -57,18 +57,16 @@ function findClosestObjectLink(element) { ...@@ -57,18 +57,16 @@ function findClosestObjectLink(element) {
* @return {boolean} * @return {boolean}
*/ */
function addToObjectLink(element, symbol, object) { function addToObjectLink(element, symbol, object) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateSymbol(symbol) validateSymbol(symbol);
if (element?.[symbol] === undefined) { if (element?.[symbol] === undefined) {
element[symbol] = new Set; element[symbol] = new Set();
} }
addAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); addAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString());
element[symbol].add(object); element[symbol].add(object);
return element; return element;
} }
/** /**
...@@ -83,21 +81,18 @@ function addToObjectLink(element, symbol, object) { ...@@ -83,21 +81,18 @@ function addToObjectLink(element, symbol, object) {
* @return {boolean} * @return {boolean}
*/ */
function removeObjectLink(element, symbol) { function removeObjectLink(element, symbol) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateSymbol(symbol) validateSymbol(symbol);
if (element?.[symbol] === undefined) { if (element?.[symbol] === undefined) {
return element return element;
} }
removeAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); removeAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString());
delete element[symbol]; delete element[symbol];
return element; return element;
} }
/** /**
* Checks if an element has an object link * Checks if an element has an object link
* *
...@@ -110,16 +105,14 @@ function removeObjectLink(element, symbol) { ...@@ -110,16 +105,14 @@ function removeObjectLink(element, symbol) {
* @return {boolean} * @return {boolean}
*/ */
function hasObjectLink(element, symbol) { function hasObjectLink(element, symbol) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateSymbol(symbol) validateSymbol(symbol);
if (element?.[symbol] === undefined) { if (element?.[symbol] === undefined) {
return false return false;
} }
return containsAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString()); return containsAttributeToken(element, ATTRIBUTE_OBJECTLINK, symbol.toString());
} }
/** /**
...@@ -140,19 +133,16 @@ function hasObjectLink(element, symbol) { ...@@ -140,19 +133,16 @@ function hasObjectLink(element, symbol) {
* @throws {Error} there is no object link for symbol * @throws {Error} there is no object link for symbol
*/ */
function getLinkedObjects(element, symbol) { function getLinkedObjects(element, symbol) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateSymbol(symbol) validateSymbol(symbol);
if (element?.[symbol] === undefined) { if (element?.[symbol] === undefined) {
throw new Error('there is no object link for ' + symbol.toString()); throw new Error(`there is no object link for ${symbol.toString()}`);
} }
return element?.[symbol][Symbol.iterator](); 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. * 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) { ...@@ -169,8 +159,8 @@ function getLinkedObjects(element, symbol) {
*/ */
function toggleAttributeToken(element, key, token) { function toggleAttributeToken(element, key, token) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(token) validateString(token);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
element.setAttribute(key, token); element.setAttribute(key, token);
...@@ -179,7 +169,7 @@ function toggleAttributeToken(element, key, token) { ...@@ -179,7 +169,7 @@ function toggleAttributeToken(element, key, token) {
element.setAttribute(key, new TokenList(element.getAttribute(key)).toggle(token).toString()); element.setAttribute(key, new TokenList(element.getAttribute(key)).toggle(token).toString());
return element return element;
} }
/** /**
...@@ -196,8 +186,8 @@ function toggleAttributeToken(element, key, token) { ...@@ -196,8 +186,8 @@ function toggleAttributeToken(element, key, token) {
*/ */
function addAttributeToken(element, key, token) { function addAttributeToken(element, key, token) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(token) validateString(token);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
element.setAttribute(key, token); element.setAttribute(key, token);
...@@ -206,7 +196,7 @@ function addAttributeToken(element, key, token) { ...@@ -206,7 +196,7 @@ function addAttributeToken(element, key, token) {
element.setAttribute(key, new TokenList(element.getAttribute(key)).add(token).toString()); element.setAttribute(key, new TokenList(element.getAttribute(key)).add(token).toString());
return element return element;
} }
/** /**
...@@ -225,8 +215,8 @@ function addAttributeToken(element, key, token) { ...@@ -225,8 +215,8 @@ function addAttributeToken(element, key, token) {
*/ */
function removeAttributeToken(element, key, token) { function removeAttributeToken(element, key, token) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(token) validateString(token);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
return element; return element;
...@@ -234,7 +224,7 @@ function removeAttributeToken(element, key, token) { ...@@ -234,7 +224,7 @@ function removeAttributeToken(element, key, token) {
element.setAttribute(key, new TokenList(element.getAttribute(key)).remove(token).toString()); element.setAttribute(key, new TokenList(element.getAttribute(key)).remove(token).toString());
return element return element;
} }
/** /**
...@@ -253,15 +243,14 @@ function removeAttributeToken(element, key, token) { ...@@ -253,15 +243,14 @@ function removeAttributeToken(element, key, token) {
*/ */
function containsAttributeToken(element, key, token) { function containsAttributeToken(element, key, token) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(token) validateString(token);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
return false; return false;
} }
return new TokenList(element.getAttribute(key)).contains(token); return new TokenList(element.getAttribute(key)).contains(token);
} }
/** /**
...@@ -279,9 +268,9 @@ function containsAttributeToken(element, key, token) { ...@@ -279,9 +268,9 @@ function containsAttributeToken(element, key, token) {
*/ */
function replaceAttributeToken(element, key, from, to) { function replaceAttributeToken(element, key, from, to) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(from) validateString(from);
validateString(to) validateString(to);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
return element; return element;
...@@ -289,7 +278,7 @@ function replaceAttributeToken(element, key, from, to) { ...@@ -289,7 +278,7 @@ function replaceAttributeToken(element, key, from, to) {
element.setAttribute(key, new TokenList(element.getAttribute(key)).replace(from, to).toString()); 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) { ...@@ -305,7 +294,7 @@ function replaceAttributeToken(element, key, from, to) {
*/ */
function clearAttributeTokens(element, key) { function clearAttributeTokens(element, key) {
validateInstance(element, HTMLElement); validateInstance(element, HTMLElement);
validateString(key) validateString(key);
if (!element.hasAttribute(key)) { if (!element.hasAttribute(key)) {
return element; return element;
...@@ -313,7 +302,7 @@ function clearAttributeTokens(element, key) { ...@@ -313,7 +302,7 @@ function clearAttributeTokens(element, key) {
element.setAttribute(key, ""); element.setAttribute(key, "");
return element return element;
} }
/** /**
...@@ -346,7 +335,7 @@ function clearAttributeTokens(element, key) { ...@@ -346,7 +335,7 @@ function clearAttributeTokens(element, key) {
* @summary find closest node * @summary find closest node
*/ */
function findClosestByAttribute(element, key, value) { function findClosestByAttribute(element, key, value) {
validateInstance(element, getGlobalFunction('HTMLElement')); validateInstance(element, getGlobalFunction("HTMLElement"));
if (element.hasAttribute(key)) { if (element.hasAttribute(key)) {
if (value === undefined) { if (value === undefined) {
...@@ -356,12 +345,11 @@ function findClosestByAttribute(element, key, value) { ...@@ -356,12 +345,11 @@ function findClosestByAttribute(element, key, value) {
if (element.getAttribute(key) === value) { if (element.getAttribute(key) === value) {
return element; return element;
} }
} }
let selector = validateString(key); let selector = validateString(key);
if (value !== undefined) selector += "=" + validateString(value); if (value !== undefined) selector += `=${validateString(value)}`;
let result = element.closest('[' + selector + ']'); let result = element.closest(`[${selector}]`);
if (result instanceof HTMLElement) { if (result instanceof HTMLElement) {
return result; return result;
} }
...@@ -400,13 +388,13 @@ function findClosestByAttribute(element, key, value) { ...@@ -400,13 +388,13 @@ function findClosestByAttribute(element, key, value) {
* @summary find closest node * @summary find closest node
*/ */
function findClosestByClass(element, className) { function findClosestByClass(element, className) {
validateInstance(element, getGlobalFunction('HTMLElement')); validateInstance(element, getGlobalFunction("HTMLElement"));
if (element?.classList?.contains(validateString(className))) { if (element?.classList?.contains(validateString(className))) {
return element; return element;
} }
let result = element.closest('.' + className); let result = element.closest(`.${className}`);
if (result instanceof HTMLElement) { if (result instanceof HTMLElement) {
return result; return result;
} }
......
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
export { export {
DEFAULT_THEME, DEFAULT_THEME,
ATTRIBUTE_PREFIX, ATTRIBUTE_PREFIX,
...@@ -59,16 +58,15 @@ export { ...@@ -59,16 +58,15 @@ export {
ATTRIBUTE_EXPORTPARTS, ATTRIBUTE_EXPORTPARTS,
ATTRIBUTE_HIDDEN, ATTRIBUTE_HIDDEN,
objectUpdaterLinkSymbol, objectUpdaterLinkSymbol,
customElementUpdaterLinkSymbol customElementUpdaterLinkSymbol,
};
}
/** /**
* default theme * default theme
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {string} * @type {string}
*/ */
const DEFAULT_THEME = 'monster'; const DEFAULT_THEME = "monster";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -76,7 +74,7 @@ const DEFAULT_THEME = 'monster'; ...@@ -76,7 +74,7 @@ const DEFAULT_THEME = 'monster';
* @since 1.8.0 * @since 1.8.0
* @type {string} * @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 * This is the name of the attribute to pass options to a control
...@@ -86,7 +84,7 @@ const ATTRIBUTE_PREFIX = 'data-monster-'; ...@@ -86,7 +84,7 @@ const ATTRIBUTE_PREFIX = 'data-monster-';
* @since 1.8.0 * @since 1.8.0
* @type {string} * @type {string}
*/ */
const ATTRIBUTE_OPTIONS = ATTRIBUTE_PREFIX + 'options'; const ATTRIBUTE_OPTIONS = `${ATTRIBUTE_PREFIX}options`;
/** /**
* This is the name of the attribute to pass options to a control * This is the name of the attribute to pass options to a control
...@@ -96,7 +94,7 @@ const ATTRIBUTE_OPTIONS = ATTRIBUTE_PREFIX + 'options'; ...@@ -96,7 +94,7 @@ const ATTRIBUTE_OPTIONS = ATTRIBUTE_PREFIX + 'options';
* @since 1.30.0 * @since 1.30.0
* @type {string} * @type {string}
*/ */
const ATTRIBUTE_OPTIONS_SELECTOR = ATTRIBUTE_PREFIX + 'options-selector'; const ATTRIBUTE_OPTIONS_SELECTOR = `${ATTRIBUTE_PREFIX}options-selector`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -104,13 +102,13 @@ const ATTRIBUTE_OPTIONS_SELECTOR = ATTRIBUTE_PREFIX + 'options-selector'; ...@@ -104,13 +102,13 @@ const ATTRIBUTE_OPTIONS_SELECTOR = ATTRIBUTE_PREFIX + 'options-selector';
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_THEME_PREFIX = ATTRIBUTE_PREFIX + 'theme-'; const ATTRIBUTE_THEME_PREFIX = `${ATTRIBUTE_PREFIX}theme-`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {string} * @type {string}
*/ */
const ATTRIBUTE_THEME_NAME = ATTRIBUTE_THEME_PREFIX + 'name'; const ATTRIBUTE_THEME_NAME = `${ATTRIBUTE_THEME_PREFIX}name`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -118,7 +116,7 @@ const ATTRIBUTE_THEME_NAME = ATTRIBUTE_THEME_PREFIX + 'name'; ...@@ -118,7 +116,7 @@ const ATTRIBUTE_THEME_NAME = ATTRIBUTE_THEME_PREFIX + 'name';
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_UPDATER_ATTRIBUTES = ATTRIBUTE_PREFIX + 'attributes'; const ATTRIBUTE_UPDATER_ATTRIBUTES = `${ATTRIBUTE_PREFIX}attributes`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -126,7 +124,7 @@ const ATTRIBUTE_UPDATER_ATTRIBUTES = ATTRIBUTE_PREFIX + 'attributes'; ...@@ -126,7 +124,7 @@ const ATTRIBUTE_UPDATER_ATTRIBUTES = ATTRIBUTE_PREFIX + 'attributes';
* @license AGPLv3 * @license AGPLv3
* @since 1.27.1 * @since 1.27.1
*/ */
const ATTRIBUTE_UPDATER_SELECT_THIS = ATTRIBUTE_PREFIX + 'select-this'; const ATTRIBUTE_UPDATER_SELECT_THIS = `${ATTRIBUTE_PREFIX}select-this`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -134,7 +132,7 @@ const ATTRIBUTE_UPDATER_SELECT_THIS = ATTRIBUTE_PREFIX + 'select-this'; ...@@ -134,7 +132,7 @@ const ATTRIBUTE_UPDATER_SELECT_THIS = ATTRIBUTE_PREFIX + 'select-this';
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_UPDATER_REPLACE = ATTRIBUTE_PREFIX + 'replace'; const ATTRIBUTE_UPDATER_REPLACE = `${ATTRIBUTE_PREFIX}replace`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -142,7 +140,7 @@ const ATTRIBUTE_UPDATER_REPLACE = ATTRIBUTE_PREFIX + 'replace'; ...@@ -142,7 +140,7 @@ const ATTRIBUTE_UPDATER_REPLACE = ATTRIBUTE_PREFIX + 'replace';
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_UPDATER_INSERT = ATTRIBUTE_PREFIX + 'insert'; const ATTRIBUTE_UPDATER_INSERT = `${ATTRIBUTE_PREFIX}insert`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -150,7 +148,7 @@ const ATTRIBUTE_UPDATER_INSERT = ATTRIBUTE_PREFIX + 'insert'; ...@@ -150,7 +148,7 @@ const ATTRIBUTE_UPDATER_INSERT = ATTRIBUTE_PREFIX + 'insert';
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_UPDATER_INSERT_REFERENCE = ATTRIBUTE_PREFIX + 'insert-reference'; const ATTRIBUTE_UPDATER_INSERT_REFERENCE = `${ATTRIBUTE_PREFIX}insert-reference`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -158,7 +156,7 @@ const ATTRIBUTE_UPDATER_INSERT_REFERENCE = ATTRIBUTE_PREFIX + 'insert-reference' ...@@ -158,7 +156,7 @@ const ATTRIBUTE_UPDATER_INSERT_REFERENCE = ATTRIBUTE_PREFIX + 'insert-reference'
* @license AGPLv3 * @license AGPLv3
* @since 1.8.0 * @since 1.8.0
*/ */
const ATTRIBUTE_UPDATER_REMOVE = ATTRIBUTE_PREFIX + 'remove'; const ATTRIBUTE_UPDATER_REMOVE = `${ATTRIBUTE_PREFIX}remove`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -166,7 +164,7 @@ const ATTRIBUTE_UPDATER_REMOVE = ATTRIBUTE_PREFIX + 'remove'; ...@@ -166,7 +164,7 @@ const ATTRIBUTE_UPDATER_REMOVE = ATTRIBUTE_PREFIX + 'remove';
* @license AGPLv3 * @license AGPLv3
* @since 1.9.0 * @since 1.9.0
*/ */
const ATTRIBUTE_UPDATER_BIND = ATTRIBUTE_PREFIX + 'bind'; const ATTRIBUTE_UPDATER_BIND = `${ATTRIBUTE_PREFIX}bind`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -174,7 +172,7 @@ const ATTRIBUTE_UPDATER_BIND = ATTRIBUTE_PREFIX + 'bind'; ...@@ -174,7 +172,7 @@ const ATTRIBUTE_UPDATER_BIND = ATTRIBUTE_PREFIX + 'bind';
* @license AGPLv3 * @license AGPLv3
* @since 1.27.0 * @since 1.27.0
*/ */
const ATTRIBUTE_TEMPLATE_PREFIX = ATTRIBUTE_PREFIX + 'template-prefix'; const ATTRIBUTE_TEMPLATE_PREFIX = `${ATTRIBUTE_PREFIX}template-prefix`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -182,7 +180,7 @@ const ATTRIBUTE_TEMPLATE_PREFIX = ATTRIBUTE_PREFIX + 'template-prefix'; ...@@ -182,7 +180,7 @@ const ATTRIBUTE_TEMPLATE_PREFIX = ATTRIBUTE_PREFIX + 'template-prefix';
* @license AGPLv3 * @license AGPLv3
* @since 1.14.0 * @since 1.14.0
*/ */
const ATTRIBUTE_ROLE = ATTRIBUTE_PREFIX + 'role'; const ATTRIBUTE_ROLE = `${ATTRIBUTE_PREFIX}role`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -190,7 +188,7 @@ const ATTRIBUTE_ROLE = ATTRIBUTE_PREFIX + 'role'; ...@@ -190,7 +188,7 @@ const ATTRIBUTE_ROLE = ATTRIBUTE_PREFIX + 'role';
* @license AGPLv3 * @license AGPLv3
* @since 1.24.0 * @since 1.24.0
*/ */
const ATTRIBUTE_DISABLED = 'disabled'; const ATTRIBUTE_DISABLED = "disabled";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -198,7 +196,7 @@ const ATTRIBUTE_DISABLED = 'disabled'; ...@@ -198,7 +196,7 @@ const ATTRIBUTE_DISABLED = 'disabled';
* @license AGPLv3 * @license AGPLv3
* @since 1.24.0 * @since 1.24.0
*/ */
const ATTRIBUTE_VALUE = 'value'; const ATTRIBUTE_VALUE = "value";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -206,7 +204,7 @@ const ATTRIBUTE_VALUE = 'value'; ...@@ -206,7 +204,7 @@ const ATTRIBUTE_VALUE = 'value';
* @license AGPLv3 * @license AGPLv3
* @since 1.9.0 * @since 1.9.0
*/ */
const ATTRIBUTE_OBJECTLINK = ATTRIBUTE_PREFIX + 'objectlink'; const ATTRIBUTE_OBJECTLINK = `${ATTRIBUTE_PREFIX}objectlink`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -214,7 +212,7 @@ const ATTRIBUTE_OBJECTLINK = ATTRIBUTE_PREFIX + 'objectlink'; ...@@ -214,7 +212,7 @@ const ATTRIBUTE_OBJECTLINK = ATTRIBUTE_PREFIX + 'objectlink';
* @license AGPLv3 * @license AGPLv3
* @since 1.24.0 * @since 1.24.0
*/ */
const ATTRIBUTE_ERRORMESSAGE = ATTRIBUTE_PREFIX + 'error'; const ATTRIBUTE_ERRORMESSAGE = `${ATTRIBUTE_PREFIX}error`;
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -222,7 +220,7 @@ const ATTRIBUTE_ERRORMESSAGE = ATTRIBUTE_PREFIX + 'error'; ...@@ -222,7 +220,7 @@ const ATTRIBUTE_ERRORMESSAGE = ATTRIBUTE_PREFIX + 'error';
* @license AGPLv3 * @license AGPLv3
* @since 1.24.0 * @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 * @memberOf Monster.DOM
...@@ -230,7 +228,7 @@ const objectUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/@@object-update ...@@ -230,7 +228,7 @@ const objectUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/@@object-update
* @license AGPLv3 * @license AGPLv3
* @since 1.24.0 * @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 * @memberOf Monster.DOM
...@@ -238,7 +236,7 @@ const customElementUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/custom-e ...@@ -238,7 +236,7 @@ const customElementUpdaterLinkSymbol = Symbol.for('@schukai/monster/dom/custom-e
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const TAG_SCRIPT = 'script'; const TAG_SCRIPT = "script";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -246,7 +244,7 @@ const TAG_SCRIPT = 'script'; ...@@ -246,7 +244,7 @@ const TAG_SCRIPT = 'script';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const TAG_STYLE = 'style'; const TAG_STYLE = "style";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -254,7 +252,7 @@ const TAG_STYLE = 'style'; ...@@ -254,7 +252,7 @@ const TAG_STYLE = 'style';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const TAG_LINK = 'link'; const TAG_LINK = "link";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -263,7 +261,7 @@ const TAG_LINK = 'link'; ...@@ -263,7 +261,7 @@ const TAG_LINK = 'link';
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ID = 'id'; const ATTRIBUTE_ID = "id";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -272,7 +270,7 @@ const ATTRIBUTE_ID = 'id'; ...@@ -272,7 +270,7 @@ const ATTRIBUTE_ID = 'id';
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_CLASS = 'class'; const ATTRIBUTE_CLASS = "class";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -280,7 +278,7 @@ const ATTRIBUTE_CLASS = 'class'; ...@@ -280,7 +278,7 @@ const ATTRIBUTE_CLASS = 'class';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_TITLE = 'title'; const ATTRIBUTE_TITLE = "title";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -288,14 +286,14 @@ const ATTRIBUTE_TITLE = 'title'; ...@@ -288,14 +286,14 @@ const ATTRIBUTE_TITLE = 'title';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_SRC = 'src'; const ATTRIBUTE_SRC = "src";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {string} * @type {string}
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_HREF = 'href'; const ATTRIBUTE_HREF = "href";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -303,7 +301,7 @@ const ATTRIBUTE_HREF = 'href'; ...@@ -303,7 +301,7 @@ const ATTRIBUTE_HREF = 'href';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_TYPE = 'type'; const ATTRIBUTE_TYPE = "type";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -311,7 +309,7 @@ const ATTRIBUTE_TYPE = 'type'; ...@@ -311,7 +309,7 @@ const ATTRIBUTE_TYPE = 'type';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_NONCE = 'nonce'; const ATTRIBUTE_NONCE = "nonce";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -319,8 +317,7 @@ const ATTRIBUTE_NONCE = 'nonce'; ...@@ -319,8 +317,7 @@ const ATTRIBUTE_NONCE = 'nonce';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_TRANSLATE = 'translate'; const ATTRIBUTE_TRANSLATE = "translate";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -328,8 +325,7 @@ const ATTRIBUTE_TRANSLATE = 'translate'; ...@@ -328,8 +325,7 @@ const ATTRIBUTE_TRANSLATE = 'translate';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_TABINDEX = 'tabindex'; const ATTRIBUTE_TABINDEX = "tabindex";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -337,8 +333,7 @@ const ATTRIBUTE_TABINDEX = 'tabindex'; ...@@ -337,8 +333,7 @@ const ATTRIBUTE_TABINDEX = 'tabindex';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_SPELLCHECK = 'spellcheck'; const ATTRIBUTE_SPELLCHECK = "spellcheck";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -346,8 +341,7 @@ const ATTRIBUTE_SPELLCHECK = 'spellcheck'; ...@@ -346,8 +341,7 @@ const ATTRIBUTE_SPELLCHECK = 'spellcheck';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_SLOT = 'slot'; const ATTRIBUTE_SLOT = "slot";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -355,8 +349,7 @@ const ATTRIBUTE_SLOT = 'slot'; ...@@ -355,8 +349,7 @@ const ATTRIBUTE_SLOT = 'slot';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_PART = 'part'; const ATTRIBUTE_PART = "part";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -364,8 +357,7 @@ const ATTRIBUTE_PART = 'part'; ...@@ -364,8 +357,7 @@ const ATTRIBUTE_PART = 'part';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_LANG = 'lang'; const ATTRIBUTE_LANG = "lang";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -373,8 +365,7 @@ const ATTRIBUTE_LANG = 'lang'; ...@@ -373,8 +365,7 @@ const ATTRIBUTE_LANG = 'lang';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ITEMTYPE = 'itemtype'; const ATTRIBUTE_ITEMTYPE = "itemtype";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -382,8 +373,7 @@ const ATTRIBUTE_ITEMTYPE = 'itemtype'; ...@@ -382,8 +373,7 @@ const ATTRIBUTE_ITEMTYPE = 'itemtype';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ITEMSCOPE = 'itemscope'; const ATTRIBUTE_ITEMSCOPE = "itemscope";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -391,8 +381,7 @@ const ATTRIBUTE_ITEMSCOPE = 'itemscope'; ...@@ -391,8 +381,7 @@ const ATTRIBUTE_ITEMSCOPE = 'itemscope';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ITEMREF = 'itemref'; const ATTRIBUTE_ITEMREF = "itemref";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -400,8 +389,7 @@ const ATTRIBUTE_ITEMREF = 'itemref'; ...@@ -400,8 +389,7 @@ const ATTRIBUTE_ITEMREF = 'itemref';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ITEMID = 'itemid'; const ATTRIBUTE_ITEMID = "itemid";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -409,8 +397,7 @@ const ATTRIBUTE_ITEMID = 'itemid'; ...@@ -409,8 +397,7 @@ const ATTRIBUTE_ITEMID = 'itemid';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ITEMPROP = 'itemprop'; const ATTRIBUTE_ITEMPROP = "itemprop";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -418,8 +405,7 @@ const ATTRIBUTE_ITEMPROP = 'itemprop'; ...@@ -418,8 +405,7 @@ const ATTRIBUTE_ITEMPROP = 'itemprop';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_IS = 'is'; const ATTRIBUTE_IS = "is";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -427,8 +413,7 @@ const ATTRIBUTE_IS = 'is'; ...@@ -427,8 +413,7 @@ const ATTRIBUTE_IS = 'is';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_INPUTMODE = 'inputmode'; const ATTRIBUTE_INPUTMODE = "inputmode";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -436,7 +421,7 @@ const ATTRIBUTE_INPUTMODE = 'inputmode'; ...@@ -436,7 +421,7 @@ const ATTRIBUTE_INPUTMODE = 'inputmode';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ACCESSKEY = 'accesskey'; const ATTRIBUTE_ACCESSKEY = "accesskey";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -444,7 +429,7 @@ const ATTRIBUTE_ACCESSKEY = 'accesskey'; ...@@ -444,7 +429,7 @@ const ATTRIBUTE_ACCESSKEY = 'accesskey';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_AUTOCAPITALIZE = 'autocapitalize'; const ATTRIBUTE_AUTOCAPITALIZE = "autocapitalize";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -452,7 +437,7 @@ const ATTRIBUTE_AUTOCAPITALIZE = 'autocapitalize'; ...@@ -452,7 +437,7 @@ const ATTRIBUTE_AUTOCAPITALIZE = 'autocapitalize';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_AUTOFOCUS = 'autofocus'; const ATTRIBUTE_AUTOFOCUS = "autofocus";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -460,7 +445,7 @@ const ATTRIBUTE_AUTOFOCUS = 'autofocus'; ...@@ -460,7 +445,7 @@ const ATTRIBUTE_AUTOFOCUS = 'autofocus';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_CONTENTEDITABLE = 'contenteditable'; const ATTRIBUTE_CONTENTEDITABLE = "contenteditable";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -468,7 +453,7 @@ const ATTRIBUTE_CONTENTEDITABLE = 'contenteditable'; ...@@ -468,7 +453,7 @@ const ATTRIBUTE_CONTENTEDITABLE = 'contenteditable';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_DIR = 'dir'; const ATTRIBUTE_DIR = "dir";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -476,8 +461,7 @@ const ATTRIBUTE_DIR = 'dir'; ...@@ -476,8 +461,7 @@ const ATTRIBUTE_DIR = 'dir';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_DRAGGABLE = 'draggable'; const ATTRIBUTE_DRAGGABLE = "draggable";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
...@@ -485,18 +469,18 @@ const ATTRIBUTE_DRAGGABLE = 'draggable'; ...@@ -485,18 +469,18 @@ const ATTRIBUTE_DRAGGABLE = 'draggable';
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_ENTERKEYHINT = 'enterkeyhint'; const ATTRIBUTE_ENTERKEYHINT = "enterkeyhint";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {string} * @type {string}
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_EXPORTPARTS = 'exportparts'; const ATTRIBUTE_EXPORTPARTS = "exportparts";
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {string} * @type {string}
* @license AGPLv3 * @license AGPLv3
* @since 1.25.0 * @since 1.25.0
*/ */
const ATTRIBUTE_HIDDEN = 'hidden'; const ATTRIBUTE_HIDDEN = "hidden";
...@@ -8,14 +8,14 @@ ...@@ -8,14 +8,14 @@
import { extend } from "../data/extend.mjs"; import { extend } from "../data/extend.mjs";
import { ATTRIBUTE_VALUE } from "./constants.mjs"; import { ATTRIBUTE_VALUE } from "./constants.mjs";
import { CustomElement, attributeObserverSymbol } from "./customelement.mjs"; import { CustomElement, attributeObserverSymbol } from "./customelement.mjs";
import {instanceSymbol} from '../constants.mjs'; import { instanceSymbol } from "../constants.mjs";
export {CustomControl} export { CustomControl };
/** /**
* @private * @private
* @type {symbol} * @type {symbol}
*/ */
const attachedInternalSymbol = Symbol('attachedInternal'); const attachedInternalSymbol = Symbol("attachedInternal");
/** /**
* To define a new HTML control we need the power of CustomElement * To define a new HTML control we need the power of CustomElement
...@@ -47,7 +47,6 @@ const attachedInternalSymbol = Symbol('attachedInternal'); ...@@ -47,7 +47,6 @@ const attachedInternalSymbol = Symbol('attachedInternal');
* @memberOf Monster.DOM * @memberOf Monster.DOM
*/ */
class CustomControl extends CustomElement { 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>. * 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 { ...@@ -57,7 +56,7 @@ class CustomControl extends CustomElement {
constructor() { constructor() {
super(); super();
if (typeof this['attachInternals'] === 'function') { if (typeof this["attachInternals"] === "function") {
/** /**
* currently only supported by chrome * currently only supported by chrome
* @property {Object} * @property {Object}
...@@ -67,7 +66,6 @@ class CustomControl extends CustomElement { ...@@ -67,7 +66,6 @@ class CustomControl extends CustomElement {
} }
initObserver.call(this); initObserver.call(this);
} }
/** /**
...@@ -79,7 +77,6 @@ class CustomControl extends CustomElement { ...@@ -79,7 +77,6 @@ class CustomControl extends CustomElement {
return Symbol.for("@schukai/monster/dom/custom-control"); return Symbol.for("@schukai/monster/dom/custom-control");
} }
/** /**
* This method determines which attributes are to be monitored by `attributeChangedCallback()`. * This method determines which attributes are to be monitored by `attributeChangedCallback()`.
* *
...@@ -131,7 +128,7 @@ class CustomControl extends CustomElement { ...@@ -131,7 +128,7 @@ class CustomControl extends CustomElement {
* @throws {Error} the value getter must be overwritten by the derived class * @throws {Error} the value getter must be overwritten by the derived class
*/ */
get value() { 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 { ...@@ -144,7 +141,7 @@ class CustomControl extends CustomElement {
* @throws {Error} the value setter must be overwritten by the derived class * @throws {Error} the value setter must be overwritten by the derived class
*/ */
set value(value) { 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 { ...@@ -165,7 +162,7 @@ class CustomControl extends CustomElement {
* @return {string|null} * @return {string|null}
*/ */
get name() { get name() {
return this.getAttribute('name'); return this.getAttribute("name");
} }
/** /**
...@@ -301,7 +298,6 @@ class CustomControl extends CustomElement { ...@@ -301,7 +298,6 @@ class CustomControl extends CustomElement {
reportValidity() { reportValidity() {
return getInternal.call(this)?.reportValidity(); return getInternal.call(this)?.reportValidity();
} }
} }
/** /**
...@@ -314,7 +310,7 @@ function getInternal() { ...@@ -314,7 +310,7 @@ function getInternal() {
const self = this; const self = this;
if (!(attachedInternalSymbol in 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]; return this[attachedInternalSymbol];
...@@ -329,8 +325,7 @@ function initObserver() { ...@@ -329,8 +325,7 @@ function initObserver() {
const self = this; const self = this;
// value // value
self[attributeObserverSymbol]['value'] = () => { self[attributeObserverSymbol]["value"] = () => {
self.setOption('value', self.getAttribute('value')); self.setOption("value", self.getAttribute("value"));
} };
} }
...@@ -22,11 +22,11 @@ import { ...@@ -22,11 +22,11 @@ import {
ATTRIBUTE_ERRORMESSAGE, ATTRIBUTE_ERRORMESSAGE,
ATTRIBUTE_OPTIONS, ATTRIBUTE_OPTIONS,
ATTRIBUTE_OPTIONS_SELECTOR, ATTRIBUTE_OPTIONS_SELECTOR,
customElementUpdaterLinkSymbol customElementUpdaterLinkSymbol,
} from "./constants.mjs"; } from "./constants.mjs";
import { findDocumentTemplate, Template } from "./template.mjs"; import { findDocumentTemplate, Template } from "./template.mjs";
import { addObjectWithUpdaterToElement } from "./updater.mjs"; import { addObjectWithUpdaterToElement } from "./updater.mjs";
import {instanceSymbol} from '../constants.mjs'; import { instanceSymbol } from "../constants.mjs";
export { export {
CustomElement, CustomElement,
...@@ -34,28 +34,27 @@ export { ...@@ -34,28 +34,27 @@ export {
assembleMethodSymbol, assembleMethodSymbol,
attributeObserverSymbol, attributeObserverSymbol,
registerCustomElement, registerCustomElement,
getSlottedElements getSlottedElements,
} };
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {symbol} * @type {symbol}
*/ */
const initMethodSymbol = Symbol.for('@schukai/monster/dom/@@initMethodSymbol'); const initMethodSymbol = Symbol.for("@schukai/monster/dom/@@initMethodSymbol");
/** /**
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {symbol} * @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. * this symbol holds the attribute observer callbacks. The key is the attribute name.
* @memberOf Monster.DOM * @memberOf Monster.DOM
* @type {symbol} * @type {symbol}
*/ */
const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObserver'); const attributeObserverSymbol = Symbol.for("@schukai/monster/dom/@@attributeObserver");
/** /**
* HTMLElement * HTMLElement
...@@ -100,7 +99,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse ...@@ -100,7 +99,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse
* @enduml * @enduml
*/ */
/** /**
* To define a new HTML element we need the power of CustomElement * To define a new HTML element we need the power of CustomElement
* *
...@@ -187,7 +185,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse ...@@ -187,7 +185,6 @@ const attributeObserverSymbol = Symbol.for('@schukai/monster/dom/@@attributeObse
* @summary A base class for HTML5 customcontrols * @summary A base class for HTML5 customcontrols
*/ */
class CustomElement extends HTMLElement { class CustomElement extends HTMLElement {
/** /**
* A new object is created. First the `initOptions` method is called. Here the * 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. * options can be defined in derived classes. Subsequently, the shadowRoot is initialized.
...@@ -197,7 +194,9 @@ class CustomElement extends HTMLElement { ...@@ -197,7 +194,9 @@ class CustomElement extends HTMLElement {
*/ */
constructor() { constructor() {
super(); super();
this[internalSymbol] = new ProxyObserver({'options': extend({}, this.defaults)}); this[internalSymbol] = new ProxyObserver({
options: extend({}, this.defaults),
});
this[attributeObserverSymbol] = {}; this[attributeObserverSymbol] = {};
initOptionObserver.call(this); initOptionObserver.call(this);
this[initMethodSymbol](); this[initMethodSymbol]();
...@@ -212,7 +211,6 @@ class CustomElement extends HTMLElement { ...@@ -212,7 +211,6 @@ class CustomElement extends HTMLElement {
return Symbol.for("@schukai/monster/dom/custom-element"); return Symbol.for("@schukai/monster/dom/custom-element");
} }
/** /**
* This method determines which attributes are to be monitored by `attributeChangedCallback()`. * This method determines which attributes are to be monitored by `attributeChangedCallback()`.
* *
...@@ -275,11 +273,11 @@ class CustomElement extends HTMLElement { ...@@ -275,11 +273,11 @@ class CustomElement extends HTMLElement {
get defaults() { get defaults() {
return { return {
ATTRIBUTE_DISABLED: this.getAttribute(ATTRIBUTE_DISABLED), ATTRIBUTE_DISABLED: this.getAttribute(ATTRIBUTE_DISABLED),
shadowMode: 'open', shadowMode: "open",
delegatesFocus: true, delegatesFocus: true,
templates: { templates: {
main: undefined main: undefined,
} },
}; };
} }
...@@ -329,7 +327,7 @@ class CustomElement extends HTMLElement { ...@@ -329,7 +327,7 @@ class CustomElement extends HTMLElement {
* @returns {CustomElement} * @returns {CustomElement}
*/ */
attachObserver(observer) { attachObserver(observer) {
this[internalSymbol].attachObserver(observer) this[internalSymbol].attachObserver(observer);
return this; return this;
} }
...@@ -340,7 +338,7 @@ class CustomElement extends HTMLElement { ...@@ -340,7 +338,7 @@ class CustomElement extends HTMLElement {
* @returns {CustomElement} * @returns {CustomElement}
*/ */
detachObserver(observer) { detachObserver(observer) {
this[internalSymbol].detachObserver(observer) this[internalSymbol].detachObserver(observer);
return this; return this;
} }
...@@ -349,7 +347,7 @@ class CustomElement extends HTMLElement { ...@@ -349,7 +347,7 @@ class CustomElement extends HTMLElement {
* @returns {ProxyObserver} * @returns {ProxyObserver}
*/ */
containsObserver(observer) { containsObserver(observer) {
return this[internalSymbol].containsObserver(observer) return this[internalSymbol].containsObserver(observer);
} }
/** /**
...@@ -364,10 +362,8 @@ class CustomElement extends HTMLElement { ...@@ -364,10 +362,8 @@ class CustomElement extends HTMLElement {
let value; let value;
try { try {
value = new Pathfinder(this[internalSymbol].getRealSubject()['options']).getVia(path); value = new Pathfinder(this[internalSymbol].getRealSubject()["options"]).getVia(path);
} catch (e) { } catch (e) {}
}
if (value === undefined) return defaultValue; if (value === undefined) return defaultValue;
return value; return value;
...@@ -382,7 +378,7 @@ class CustomElement extends HTMLElement { ...@@ -382,7 +378,7 @@ class CustomElement extends HTMLElement {
* @since 1.14.0 * @since 1.14.0
*/ */
setOption(path, value) { setOption(path, value) {
new Pathfinder(this[internalSymbol].getSubject()['options']).setVia(path, value); new Pathfinder(this[internalSymbol].getSubject()["options"]).setVia(path, value);
return this; return this;
} }
...@@ -392,13 +388,12 @@ class CustomElement extends HTMLElement { ...@@ -392,13 +388,12 @@ class CustomElement extends HTMLElement {
* @return {CustomElement} * @return {CustomElement}
*/ */
setOptions(options) { setOptions(options) {
if (isString(options)) { if (isString(options)) {
options = parseOptionsJSON.call(this, options) options = parseOptionsJSON.call(this, options);
} }
const self = this; const self = this;
extend(self[internalSymbol].getSubject()['options'], self.defaults, options); extend(self[internalSymbol].getSubject()["options"], self.defaults, options);
return self; return self;
} }
...@@ -420,9 +415,9 @@ class CustomElement extends HTMLElement { ...@@ -420,9 +415,9 @@ class CustomElement extends HTMLElement {
* @since 1.8.0 * @since 1.8.0
*/ */
[assembleMethodSymbol]() { [assembleMethodSymbol]() {
const self = this; const self = this;
let elements, nodeList; let elements;
let nodeList;
const AttributeOptions = getOptionsFromAttributes.call(self); const AttributeOptions = getOptionsFromAttributes.call(self);
if (isObject(AttributeOptions) && Object.keys(AttributeOptions).length > 0) { if (isObject(AttributeOptions) && Object.keys(AttributeOptions).length > 0) {
...@@ -434,15 +429,11 @@ class CustomElement extends HTMLElement { ...@@ -434,15 +429,11 @@ class CustomElement extends HTMLElement {
self.setOptions(ScriptOptions); self.setOptions(ScriptOptions);
} }
if (self.getOption("shadowMode", false) !== false) {
if (self.getOption('shadowMode', false) !== false) {
try { try {
initShadowRoot.call(self); initShadowRoot.call(self);
elements = self.shadowRoot.childNodes; elements = self.shadowRoot.childNodes;
} catch (e) {}
} catch (e) {
}
try { try {
initCSSStylesheet.call(this); initCSSStylesheet.call(this);
...@@ -459,15 +450,17 @@ class CustomElement extends HTMLElement { ...@@ -459,15 +450,17 @@ class CustomElement extends HTMLElement {
} }
try { try {
nodeList = new Set([ nodeList = new Set([...elements, ...getSlottedElements.call(self)]);
...elements,
...getSlottedElements.call(self)
])
} catch (e) { } 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; return self;
} }
...@@ -481,7 +474,7 @@ class CustomElement extends HTMLElement { ...@@ -481,7 +474,7 @@ class CustomElement extends HTMLElement {
connectedCallback() { connectedCallback() {
let self = this; let self = this;
if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) { if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) {
self[assembleMethodSymbol]() self[assembleMethodSymbol]();
} }
} }
...@@ -491,9 +484,7 @@ class CustomElement extends HTMLElement { ...@@ -491,9 +484,7 @@ class CustomElement extends HTMLElement {
* @return {void} * @return {void}
* @since 1.7.0 * @since 1.7.0
*/ */
disconnectedCallback() { disconnectedCallback() {}
}
/** /**
* The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)). * The custom element has been moved into a new document (e.g. someone called document.adoptNode(el)).
...@@ -501,9 +492,7 @@ class CustomElement extends HTMLElement { ...@@ -501,9 +492,7 @@ class CustomElement extends HTMLElement {
* @return {void} * @return {void}
* @since 1.7.0 * @since 1.7.0
*/ */
adoptedCallback() { adoptedCallback() {}
}
/** /**
* Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial * Called when an observed attribute has been added, removed, updated, or replaced. Also called for initial
...@@ -524,7 +513,6 @@ class CustomElement extends HTMLElement { ...@@ -524,7 +513,6 @@ class CustomElement extends HTMLElement {
if (isFunction(callback)) { if (isFunction(callback)) {
callback.call(self, newVal, oldVal); callback.call(self, newVal, oldVal);
} }
} }
/** /**
...@@ -546,9 +534,7 @@ class CustomElement extends HTMLElement { ...@@ -546,9 +534,7 @@ class CustomElement extends HTMLElement {
} }
return containChildNode.call(self.shadowRoot, node); return containChildNode.call(self.shadowRoot, node);
} }
} }
/** /**
...@@ -563,27 +549,25 @@ class CustomElement extends HTMLElement { ...@@ -563,27 +549,25 @@ class CustomElement extends HTMLElement {
*/ */
function getSlottedElements(query, name) { function getSlottedElements(query, name) {
const self = this; const self = this;
const result = new Set; const result = new Set();
if (!(self.shadowRoot instanceof ShadowRoot)) { if (!(self.shadowRoot instanceof ShadowRoot)) {
return result; return result;
} }
let selector = 'slot'; let selector = "slot";
if (name !== undefined) { if (name !== undefined) {
if (name === null) { if (name === null) {
selector += ':not([name])'; selector += ":not([name])";
} else { } else {
selector += '[name=' + validateString(name) + ']'; selector += `[name=${validateString(name)}]`;
} }
} }
const slots = self.shadowRoot.querySelectorAll(selector); const slots = self.shadowRoot.querySelectorAll(selector);
for (const [, slot] of Object.entries(slots)) { for (const [, slot] of Object.entries(slots)) {
slot.assignedElements().forEach(function (node) { slot.assignedElements().forEach(function (node) {
if (!(node instanceof HTMLElement)) return; if (!(node instanceof HTMLElement)) return;
if (isString(query)) { if (isString(query)) {
...@@ -594,13 +578,12 @@ function getSlottedElements(query, name) { ...@@ -594,13 +578,12 @@ function getSlottedElements(query, name) {
if (node.matches(query)) { if (node.matches(query)) {
result.add(node); result.add(node);
} }
} else if (query !== undefined) { } else if (query !== undefined) {
throw new Error('query must be a string') throw new Error("query must be a string");
} else { } else {
result.add(node); result.add(node);
} }
}) });
} }
return result; return result;
...@@ -627,7 +610,6 @@ function containChildNode(node) { ...@@ -627,7 +610,6 @@ function containChildNode(node) {
containChildNode.call(e, node); containChildNode.call(e, node);
} }
return false; return false;
} }
...@@ -641,8 +623,9 @@ function initOptionObserver() { ...@@ -641,8 +623,9 @@ function initOptionObserver() {
const self = this; const self = this;
let lastDisabledValue = undefined; let lastDisabledValue = undefined;
self.attachObserver(new Observer(function () { self.attachObserver(
const flag = self.getOption('disabled'); new Observer(function () {
const flag = self.getOption("disabled");
if (flag === lastDisabledValue) { if (flag === lastDisabledValue) {
return; return;
...@@ -654,31 +637,29 @@ function initOptionObserver() { ...@@ -654,31 +637,29 @@ function initOptionObserver() {
return; return;
} }
const query = 'button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]'; const query =
"button, command, fieldset, keygen, optgroup, option, select, textarea, input, [data-monster-objectlink]";
const elements = self.shadowRoot.querySelectorAll(query); const elements = self.shadowRoot.querySelectorAll(query);
let nodeList; let nodeList;
try { try {
nodeList = new Set([ nodeList = new Set([...elements, ...getSlottedElements.call(self, query)]);
...elements,
...getSlottedElements.call(self, query)
])
} catch (e) { } catch (e) {
nodeList = elements nodeList = elements;
} }
for (const element of [...nodeList]) { for (const element of [...nodeList]) {
if (flag === true) { if (flag === true) {
element.setAttribute(ATTRIBUTE_DISABLED, ''); element.setAttribute(ATTRIBUTE_DISABLED, "");
} else { } else {
element.removeAttribute(ATTRIBUTE_DISABLED); element.removeAttribute(ATTRIBUTE_DISABLED);
} }
} }
}),
);
})); self.attachObserver(
new Observer(function () {
self.attachObserver(new Observer(function () {
// not initialised // not initialised
if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) { if (!hasObjectLink(self, customElementUpdaterLinkSymbol)) {
return; return;
...@@ -688,12 +669,12 @@ function initOptionObserver() { ...@@ -688,12 +669,12 @@ function initOptionObserver() {
for (const list of updaters) { for (const list of updaters) {
for (const updater of list) { for (const updater of list) {
let d = clone(self[internalSymbol].getRealSubject()['options']); let d = clone(self[internalSymbol].getRealSubject()["options"]);
Object.assign(updater.getSubject(), d); Object.assign(updater.getSubject(), d);
} }
} }
}),
})); );
// disabled // disabled
self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => { self[attributeObserverSymbol][ATTRIBUTE_DISABLED] = () => {
...@@ -702,7 +683,7 @@ function initOptionObserver() { ...@@ -702,7 +683,7 @@ function initOptionObserver() {
} else { } else {
self.setOption(ATTRIBUTE_DISABLED, undefined); self.setOption(ATTRIBUTE_DISABLED, undefined);
} }
} };
// data-monster-options // data-monster-options
self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => { self[attributeObserverSymbol][ATTRIBUTE_OPTIONS] = () => {
...@@ -710,7 +691,7 @@ function initOptionObserver() { ...@@ -710,7 +691,7 @@ function initOptionObserver() {
if (isObject(options) && Object.keys(options).length > 0) { if (isObject(options) && Object.keys(options).length > 0) {
self.setOptions(options); self.setOptions(options);
} }
} };
// data-monster-options-selector // data-monster-options-selector
self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => { self[attributeObserverSymbol][ATTRIBUTE_OPTIONS_SELECTOR] = () => {
...@@ -718,9 +699,7 @@ function initOptionObserver() { ...@@ -718,9 +699,7 @@ function initOptionObserver() {
if (isObject(options) && Object.keys(options).length > 0) { if (isObject(options) && Object.keys(options).length > 0) {
self.setOptions(options); self.setOptions(options);
} }
} };
} }
/** /**
...@@ -737,20 +716,29 @@ function getOptionsFromScriptTag() { ...@@ -737,20 +716,29 @@ function getOptionsFromScriptTag() {
const node = document.querySelector(self.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR)); const node = document.querySelector(self.getAttribute(ATTRIBUTE_OPTIONS_SELECTOR));
if (!(node instanceof HTMLScriptElement)) { 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 {}; return {};
} }
let obj = {}; let obj = {};
try { try {
obj = parseOptionsJSON.call(this, node.textContent.trim()) obj = parseOptionsJSON.call(this, node.textContent.trim());
} catch (e) { } 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; return obj;
} }
/** /**
...@@ -762,9 +750,15 @@ function getOptionsFromAttributes() { ...@@ -762,9 +750,15 @@ function getOptionsFromAttributes() {
if (this.hasAttribute(ATTRIBUTE_OPTIONS)) { if (this.hasAttribute(ATTRIBUTE_OPTIONS)) {
try { try {
return parseOptionsJSON.call(self, this.getAttribute(ATTRIBUTE_OPTIONS)) return parseOptionsJSON.call(self, this.getAttribute(ATTRIBUTE_OPTIONS));
} catch (e) { } 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}`,
);
} }
} }
...@@ -777,8 +771,7 @@ function getOptionsFromAttributes() { ...@@ -777,8 +771,7 @@ function getOptionsFromAttributes() {
* @return {Object} * @return {Object}
*/ */
function parseOptionsJSON(data) { function parseOptionsJSON(data) {
let obj = {};
const self = this, obj = {};
if (!isString(data)) { if (!isString(data)) {
return obj; return obj;
...@@ -788,19 +781,15 @@ function parseOptionsJSON(data) { ...@@ -788,19 +781,15 @@ function parseOptionsJSON(data) {
try { try {
let dataUrl = parseDataURL(data); let dataUrl = parseDataURL(data);
data = dataUrl.content; data = dataUrl.content;
} catch (e) { } catch (e) {}
}
try { try {
let obj = JSON.parse(data); obj = JSON.parse(data);
return validateObject(obj);
} catch (e) { } catch (e) {
throw e; throw e;
} }
return validateObject(obj);
return obj;
} }
/** /**
...@@ -808,21 +797,17 @@ function parseOptionsJSON(data) { ...@@ -808,21 +797,17 @@ function parseOptionsJSON(data) {
* @return {initHtmlContent} * @return {initHtmlContent}
*/ */
function initHtmlContent() { function initHtmlContent() {
try { try {
let template = findDocumentTemplate(this.constructor.getTag()); let template = findDocumentTemplate(this.constructor.getTag());
this.appendChild(template.createDocumentFragment()); this.appendChild(template.createDocumentFragment());
} catch (e) { } catch (e) {
let html = this.getOption("templates.main", "");
let html = this.getOption('templates.main', '');
if (isString(html) && html.length > 0) { if (isString(html) && html.length > 0) {
this.innerHTML = html; this.innerHTML = html;
} }
} }
return this; return this;
} }
/** /**
...@@ -850,11 +835,10 @@ function initCSSStylesheet() { ...@@ -850,11 +835,10 @@ function initCSSStylesheet() {
} else if (isArray(styleSheet)) { } else if (isArray(styleSheet)) {
const assign = []; const assign = [];
for (let s of styleSheet) { for (let s of styleSheet) {
if (isString(s)) { if (isString(s)) {
let trimedStyleSheet = s.trim() let trimedStyleSheet = s.trim();
if (trimedStyleSheet !== '') { if (trimedStyleSheet !== "") {
const style = document.createElement('style') const style = document.createElement("style");
style.innerHTML = trimedStyleSheet; style.innerHTML = trimedStyleSheet;
self.shadowRoot.prepend(style); self.shadowRoot.prepend(style);
} }
...@@ -866,26 +850,21 @@ function initCSSStylesheet() { ...@@ -866,26 +850,21 @@ function initCSSStylesheet() {
if (s.cssRules.length > 0) { if (s.cssRules.length > 0) {
assign.push(s); assign.push(s);
} }
} }
if (assign.length > 0) { if (assign.length > 0) {
this.shadowRoot.adoptedStyleSheets = assign; this.shadowRoot.adoptedStyleSheets = assign;
} }
} else if (isString(styleSheet)) { } else if (isString(styleSheet)) {
let trimedStyleSheet = styleSheet.trim();
let trimedStyleSheet = styleSheet.trim() if (trimedStyleSheet !== "") {
if (trimedStyleSheet !== '') { const style = document.createElement("style");
const style = document.createElement('style')
style.innerHTML = styleSheet; style.innerHTML = styleSheet;
self.shadowRoot.prepend(style); self.shadowRoot.prepend(style);
} }
} }
return self; return self;
} }
/** /**
...@@ -898,23 +877,21 @@ function initCSSStylesheet() { ...@@ -898,23 +877,21 @@ function initCSSStylesheet() {
* @since 1.8.0 * @since 1.8.0
*/ */
function initShadowRoot() { function initShadowRoot() {
let template;
let template, html; let html;
try { try {
template = findDocumentTemplate(this.constructor.getTag()); template = findDocumentTemplate(this.constructor.getTag());
} catch (e) { } catch (e) {
html = this.getOption("templates.main", "");
html = this.getOption('templates.main', '');
if (!isString(html) || html === undefined || html === "") { if (!isString(html) || html === undefined || html === "") {
throw new Error("html is not set."); throw new Error("html is not set.");
} }
} }
this.attachShadow({ this.attachShadow({
mode: this.getOption('shadowMode', 'open'), mode: this.getOption("shadowMode", "open"),
delegatesFocus: this.getOption('delegatesFocus', true) delegatesFocus: this.getOption("delegatesFocus", true),
}); });
if (template instanceof Template) { if (template instanceof Template) {
...@@ -939,6 +916,5 @@ function initShadowRoot() { ...@@ -939,6 +916,5 @@ function initShadowRoot() {
*/ */
function registerCustomElement(element) { function registerCustomElement(element) {
validateFunction(element); validateFunction(element);
getGlobalObject('customElements').define(element.getTag(), element); getGlobalObject("customElements").define(element.getTag(), element);
} }
...@@ -9,7 +9,7 @@ import {isArray, isObject} from "../types/is.mjs"; ...@@ -9,7 +9,7 @@ import {isArray, isObject} from "../types/is.mjs";
import { validateInstance, validateString } from "../types/validate.mjs"; import { validateInstance, validateString } from "../types/validate.mjs";
import { getDocument } from "./util.mjs"; import { getDocument } from "./util.mjs";
export {fireEvent, fireCustomEvent, findTargetElementFromEvent} export { fireEvent, fireCustomEvent, findTargetElementFromEvent };
/** /**
* The function sends an event * The function sends an event
...@@ -25,12 +25,10 @@ export {fireEvent, fireCustomEvent, findTargetElementFromEvent} ...@@ -25,12 +25,10 @@ export {fireEvent, fireCustomEvent, findTargetElementFromEvent}
* @summary Construct and send and event * @summary Construct and send and event
*/ */
function fireEvent(element, type) { function fireEvent(element, type) {
const document = getDocument(); const document = getDocument();
if (element instanceof HTMLElement) { if (element instanceof HTMLElement) {
if (type === "click") {
if (type === 'click') {
element.click(); element.click();
return; return;
} }
...@@ -41,15 +39,13 @@ function fireEvent(element, type) { ...@@ -41,15 +39,13 @@ function fireEvent(element, type) {
}); });
element.dispatchEvent(event); element.dispatchEvent(event);
} else if (element instanceof HTMLCollection || element instanceof NodeList) { } else if (element instanceof HTMLCollection || element instanceof NodeList) {
for (let e of element) { for (let e of element) {
fireEvent(e, type); fireEvent(e, type);
} }
} else { } 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,11 +62,9 @@ function fireEvent(element, type) { ...@@ -66,11 +62,9 @@ function fireEvent(element, type) {
* @summary Construct and send and event * @summary Construct and send and event
*/ */
function fireCustomEvent(element, type, detail) { function fireCustomEvent(element, type, detail) {
const document = getDocument(); const document = getDocument();
if (element instanceof HTMLElement) { if (element instanceof HTMLElement) {
if (!isObject(detail)) { if (!isObject(detail)) {
detail = { detail }; detail = { detail };
} }
...@@ -78,19 +72,17 @@ function fireCustomEvent(element, type, detail) { ...@@ -78,19 +72,17 @@ function fireCustomEvent(element, type, detail) {
let event = new CustomEvent(validateString(type), { let event = new CustomEvent(validateString(type), {
bubbles: true, bubbles: true,
cancelable: true, cancelable: true,
detail detail,
}); });
element.dispatchEvent(event); element.dispatchEvent(event);
} else if (element instanceof HTMLCollection || element instanceof NodeList) { } else if (element instanceof HTMLCollection || element instanceof NodeList) {
for (let e of element) { for (let e of element) {
fireCustomEvent(e, type, detail); fireCustomEvent(e, type, detail);
} }
} else { } 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");
} }
} }
/** /**
...@@ -112,8 +104,8 @@ function fireCustomEvent(element, type, detail) { ...@@ -112,8 +104,8 @@ function fireCustomEvent(element, type, detail) {
function findTargetElementFromEvent(event, attributeName, attributeValue) { function findTargetElementFromEvent(event, attributeName, attributeValue) {
validateInstance(event, Event); validateInstance(event, Event);
if (typeof event.composedPath !== 'function') { if (typeof event.composedPath !== "function") {
throw new Error('unsupported event'); throw new Error("unsupported event");
} }
const path = event.composedPath(); const path = event.composedPath();
...@@ -123,14 +115,15 @@ function findTargetElementFromEvent(event, attributeName, attributeValue) { ...@@ -123,14 +115,15 @@ function findTargetElementFromEvent(event, attributeName, attributeValue) {
for (let i = 0; i < path.length; i++) { for (let i = 0; i < path.length; i++) {
const o = path[i]; const o = path[i];
if (o instanceof HTMLElement && if (
o.hasAttribute(attributeName) o instanceof HTMLElement &&
&& (attributeValue === undefined || o.getAttribute(attributeName) === attributeValue)) { o.hasAttribute(attributeName) &&
(attributeValue === undefined || o.getAttribute(attributeName) === attributeValue)
) {
return o; return o;
} }
} }
} }
return undefined; return undefined;
} }
...@@ -11,28 +11,26 @@ import {getGlobalObject} from "../types/global.mjs"; ...@@ -11,28 +11,26 @@ import {getGlobalObject} from "../types/global.mjs";
import { isArray } from "../types/is.mjs"; import { isArray } from "../types/is.mjs";
import { Stack } from "../types/stack.mjs"; import { Stack } from "../types/stack.mjs";
import { validateInstance, validateString } from "../types/validate.mjs"; import { validateInstance, validateString } from "../types/validate.mjs";
import {instanceSymbol} from '../constants.mjs'; import { instanceSymbol } from "../constants.mjs";
export {FocusManager} export { FocusManager };
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const KEY_DOCUMENT = 'document'; const KEY_DOCUMENT = "document";
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const KEY_CONTEXT = 'context'; const KEY_CONTEXT = "context";
/** /**
* @private * @private
* @type {Symbol} * @type {Symbol}
*/ */
const stackSymbol = Symbol('stack'); const stackSymbol = Symbol("stack");
/** /**
* With the focusmanager the focus can be stored in a document, recalled and moved. * With the focusmanager the focus can be stored in a document, recalled and moved.
...@@ -45,7 +43,6 @@ const stackSymbol = Symbol('stack'); ...@@ -45,7 +43,6 @@ const stackSymbol = Symbol('stack');
* @summary Handle the focus * @summary Handle the focus
*/ */
class FocusManager extends BaseWithOptions { class FocusManager extends BaseWithOptions {
/** /**
* *
* @param {Object|undefined} options * @param {Object|undefined} options
...@@ -66,15 +63,14 @@ const stackSymbol = Symbol('stack'); ...@@ -66,15 +63,14 @@ const stackSymbol = Symbol('stack');
return Symbol.for("@schukai/monster/dom/focusmanager"); return Symbol.for("@schukai/monster/dom/focusmanager");
} }
/** /**
* @property {HTMLDocument} document the document object into which the node is to be appended * @property {HTMLDocument} document the document object into which the node is to be appended
*/ */
get defaults() { get defaults() {
return extend({}, super.defaults, { return extend({}, super.defaults, {
[KEY_DOCUMENT]: getGlobalObject('document'), [KEY_DOCUMENT]: getGlobalObject("document"),
[KEY_CONTEXT]: undefined, [KEY_CONTEXT]: undefined,
}) });
} }
/** /**
...@@ -84,10 +80,9 @@ const stackSymbol = Symbol('stack'); ...@@ -84,10 +80,9 @@ const stackSymbol = Symbol('stack');
* @return {Monster.DOM.FocusManager} * @return {Monster.DOM.FocusManager}
*/ */
storeFocus() { storeFocus() {
const active = this.getActive(); const active = this.getActive();
if (active instanceof Node) { if (active instanceof Node) {
this[stackSymbol].push(active) this[stackSymbol].push(active);
} }
return this; return this;
} }
...@@ -98,7 +93,6 @@ const stackSymbol = Symbol('stack'); ...@@ -98,7 +93,6 @@ const stackSymbol = Symbol('stack');
* @return {Monster.DOM.FocusManager} * @return {Monster.DOM.FocusManager}
*/ */
restoreFocus() { restoreFocus() {
const last = this[stackSymbol].pop(); const last = this[stackSymbol].pop();
if (last instanceof Node) { if (last instanceof Node) {
this.focus(last); this.focus(last);
...@@ -115,12 +109,11 @@ const stackSymbol = Symbol('stack'); ...@@ -115,12 +109,11 @@ const stackSymbol = Symbol('stack');
* @return {Monster.DOM.FocusManager} * @return {Monster.DOM.FocusManager}
*/ */
focus(element, preventScroll) { focus(element, preventScroll) {
validateInstance(element, Node);
validateInstance(element, Node)
element.focus({ element.focus({
preventScroll: preventScroll ?? false preventScroll: preventScroll ?? false,
}) });
return this; return this;
} }
...@@ -141,28 +134,28 @@ const stackSymbol = Symbol('stack'); ...@@ -141,28 +134,28 @@ const stackSymbol = Symbol('stack');
* @throws {TypeError} value is not an instance of * @throws {TypeError} value is not an instance of
*/ */
getFocusable(query) { getFocusable(query) {
let contextElement = this.getOption(KEY_CONTEXT); let contextElement = this.getOption(KEY_CONTEXT);
if (contextElement === undefined) { if (contextElement === undefined) {
contextElement = this.getOption(KEY_DOCUMENT); contextElement = this.getOption(KEY_DOCUMENT);
} }
validateInstance(contextElement, Node) validateInstance(contextElement, Node);
if (query !== undefined) { if (query !== undefined) {
validateString(query); validateString(query);
} }
return [...contextElement.querySelectorAll( return [
'details, button, input, [tabindex]:not([tabindex="-1"]), select, textarea, a[href], body' ...contextElement.querySelectorAll(
)].filter((element) => { 'details, button, input, [tabindex]:not([tabindex="-1"]), select, textarea, a[href], body',
),
].filter((element) => {
if (query !== undefined && !element.matches(query)) { if (query !== undefined && !element.matches(query)) {
return false; return false;
} }
if (element.hasAttribute('disabled')) return false; if (element.hasAttribute("disabled")) return false;
if (element.getAttribute("aria-hidden") === 'true') return false; if (element.getAttribute("aria-hidden") === "true") return false;
const rect = element.getBoundingClientRect(); const rect = element.getBoundingClientRect();
if (rect.width === 0) return false; if (rect.width === 0) return false;
...@@ -177,7 +170,6 @@ const stackSymbol = Symbol('stack'); ...@@ -177,7 +170,6 @@ const stackSymbol = Symbol('stack');
* @return {Monster.DOM.FocusManager} * @return {Monster.DOM.FocusManager}
*/ */
focusNext(query) { focusNext(query) {
const current = this.getActive(); const current = this.getActive();
const focusable = this.getFocusable(query); const focusable = this.getFocusable(query);
...@@ -194,7 +186,7 @@ const stackSymbol = Symbol('stack'); ...@@ -194,7 +186,7 @@ const stackSymbol = Symbol('stack');
this.focus(focusable[0]); this.focus(focusable[0]);
} }
} else { } else {
this.focus(focusable[0]) this.focus(focusable[0]);
} }
return this; return this;
...@@ -205,7 +197,6 @@ const stackSymbol = Symbol('stack'); ...@@ -205,7 +197,6 @@ const stackSymbol = Symbol('stack');
* @return {Monster.DOM.FocusManager} * @return {Monster.DOM.FocusManager}
*/ */
focusPrev(query) { focusPrev(query) {
const current = this.getActive(); const current = this.getActive();
const focusable = this.getFocusable(query); const focusable = this.getFocusable(query);
...@@ -222,18 +213,9 @@ const stackSymbol = Symbol('stack'); ...@@ -222,18 +213,9 @@ const stackSymbol = Symbol('stack');
this.focus(focusable[focusable.length - 1]); this.focus(focusable[focusable.length - 1]);
} }
} else { } else {
this.focus(focusable[focusable.length - 1]) this.focus(focusable[focusable.length - 1]);
} }
return this; return this;
} }
} }
...@@ -9,13 +9,13 @@ import {parseLocale} from "../i18n/locale.mjs"; ...@@ -9,13 +9,13 @@ import {parseLocale} from "../i18n/locale.mjs";
import { getDocument } from "./util.mjs"; import { getDocument } from "./util.mjs";
import { getGlobalObject } from "../types/global.mjs"; import { getGlobalObject } from "../types/global.mjs";
export {getLocaleOfDocument} export { getLocaleOfDocument };
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const DEFAULT_LANGUAGE = 'en'; const DEFAULT_LANGUAGE = "en";
/** /**
* With this function you can read the language version set by the document. * With this function you can read the language version set by the document.
...@@ -36,14 +36,13 @@ const DEFAULT_LANGUAGE = 'en'; ...@@ -36,14 +36,13 @@ const DEFAULT_LANGUAGE = 'en';
* @summary Tries to determine the locale used * @summary Tries to determine the locale used
*/ */
function getLocaleOfDocument() { function getLocaleOfDocument() {
const document = getDocument(); const document = getDocument();
let html = document.querySelector('html') let html = document.querySelector("html");
if (html instanceof HTMLElement && html.hasAttribute('lang')) { if (html instanceof HTMLElement && html.hasAttribute("lang")) {
let locale = html.getAttribute('lang'); let locale = html.getAttribute("lang");
if (locale) { if (locale) {
return new parseLocale(locale) return new parseLocale(locale);
} }
} }
...@@ -62,17 +61,16 @@ function getLocaleOfDocument() { ...@@ -62,17 +61,16 @@ function getLocaleOfDocument() {
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/languages
*/ */
const getNavigatorLanguage = () => { const getNavigatorLanguage = () => {
const navigator = getGlobalObject('navigator'); const navigator = getGlobalObject("navigator");
if (navigator === undefined) { if (navigator === undefined) {
return undefined; return undefined;
} }
if (navigator.hasOwnProperty('language')) { if (navigator.hasOwnProperty("language")) {
const language = navigator.language; const language = navigator.language;
if (typeof language === 'string' && language.length > 0) { if (typeof language === "string" && language.length > 0) {
return language; return language;
} }
} }
const languages = navigator?.languages; const languages = navigator?.languages;
...@@ -81,5 +79,4 @@ const getNavigatorLanguage = () => { ...@@ -81,5 +79,4 @@ const getNavigatorLanguage = () => {
} }
return undefined; return undefined;
};
}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
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. * This variable is a promise that is fulfilled as soon as the dom is available.
...@@ -28,18 +28,16 @@ export {domReady, windowReady} ...@@ -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/DOMContentLoaded_event
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState * @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(); const document = getDocument();
if (document.readyState === "loading") { if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', resolve); document.addEventListener("DOMContentLoaded", resolve);
} else { } else {
resolve(); resolve();
} }
}); });
/** /**
* This variable is a promise that is fulfilled as soon as the windows is available. * This variable is a promise that is fulfilled as soon as the windows is available.
* *
...@@ -55,14 +53,13 @@ const domReady = new Promise(resolve => { ...@@ -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/Window/load_event
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState * @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 document = getDocument();
const window = getWindow(); const window = getWindow();
if (document.readyState === 'complete') { if (document.readyState === "complete") {
resolve(); resolve();
} else { } else {
window.addEventListener('load', resolve); window.addEventListener("load", resolve);
} }
}); });
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
* License text available at https://www.gnu.org/licenses/agpl-3.0.en.html * License text available at https://www.gnu.org/licenses/agpl-3.0.en.html
*/ */
import {internalStateSymbol, internalSymbol,} from "../constants.mjs"; import { internalStateSymbol, internalSymbol } from "../constants.mjs";
import { extend } from "../data/extend.mjs"; import { extend } from "../data/extend.mjs";
import { BaseWithOptions } from "../types/basewithoptions.mjs"; import { BaseWithOptions } from "../types/basewithoptions.mjs";
import { getGlobalObject } from "../types/global.mjs"; import { getGlobalObject } from "../types/global.mjs";
...@@ -16,31 +16,31 @@ import {ProxyObserver} from "../types/proxyobserver.mjs"; ...@@ -16,31 +16,31 @@ import {ProxyObserver} from "../types/proxyobserver.mjs";
import { ATTRIBUTE_CLASS, ATTRIBUTE_ID, ATTRIBUTE_TITLE } from "./constants.mjs"; import { ATTRIBUTE_CLASS, ATTRIBUTE_ID, ATTRIBUTE_TITLE } from "./constants.mjs";
import { instanceSymbol } from "../constants.mjs"; import { instanceSymbol } from "../constants.mjs";
export {Resource, KEY_DOCUMENT, KEY_QUERY, referenceSymbol} export { Resource, KEY_DOCUMENT, KEY_QUERY, referenceSymbol };
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const KEY_DOCUMENT = 'document'; const KEY_DOCUMENT = "document";
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const KEY_QUERY = 'query'; const KEY_QUERY = "query";
/** /**
* @private * @private
* @type {string} * @type {string}
*/ */
const KEY_TIMEOUT = 'timeout'; const KEY_TIMEOUT = "timeout";
/** /**
* @private * @private
* @type {symbol} * @type {symbol}
*/ */
const referenceSymbol = Symbol('reference'); const referenceSymbol = Symbol("reference");
/** /**
* This class is the base class for all resources to be loaded. * This class is the base class for all resources to be loaded.
...@@ -52,7 +52,6 @@ const referenceSymbol = Symbol('reference'); ...@@ -52,7 +52,6 @@ const referenceSymbol = Symbol('reference');
* @summary A Resource class * @summary A Resource class
*/ */
class Resource extends BaseWithOptions { class Resource extends BaseWithOptions {
/** /**
* *
* @param {Object|undefined} options * @param {Object|undefined} options
...@@ -63,28 +62,26 @@ class Resource extends BaseWithOptions { ...@@ -63,28 +62,26 @@ class Resource extends BaseWithOptions {
let uri = this.getOption(this.constructor.getURLAttribute()); let uri = this.getOption(this.constructor.getURLAttribute());
if (uri === undefined) { if (uri === undefined) {
throw new Error('missing source') throw new Error("missing source");
} else if (uri instanceof URL) { } else if (uri instanceof URL) {
uri = uri.toString(); uri = uri.toString();
} else if (!isString(uri)) { } else if (!isString(uri)) {
throw new Error('unsupported url type') throw new Error("unsupported url type");
} }
this[internalSymbol][this.constructor.getURLAttribute()] = uri; this[internalSymbol][this.constructor.getURLAttribute()] = uri;
this[internalStateSymbol] = new ProxyObserver({ this[internalStateSymbol] = new ProxyObserver({
loaded: false, loaded: false,
error: undefined, error: undefined,
}) });
this[referenceSymbol] = undefined; this[referenceSymbol] = undefined;
} }
/** /**
* @return {boolean} * @return {boolean}
*/ */
isConnected() { isConnected() {
if (this[referenceSymbol] instanceof HTMLElement) { if (this[referenceSymbol] instanceof HTMLElement) {
return this[referenceSymbol].isConnected; return this[referenceSymbol].isConnected;
} }
...@@ -111,7 +108,6 @@ class Resource extends BaseWithOptions { ...@@ -111,7 +108,6 @@ class Resource extends BaseWithOptions {
* @return {Monster.DOM.Resource} * @return {Monster.DOM.Resource}
*/ */
connect() { connect() {
if (!(this[referenceSymbol] instanceof HTMLElement)) { if (!(this[referenceSymbol] instanceof HTMLElement)) {
this.create(); this.create();
} }
...@@ -132,13 +128,13 @@ class Resource extends BaseWithOptions { ...@@ -132,13 +128,13 @@ class Resource extends BaseWithOptions {
get defaults() { get defaults() {
return extend({}, super.defaults, { return extend({}, super.defaults, {
[this.constructor.getURLAttribute()]: undefined, [this.constructor.getURLAttribute()]: undefined,
[KEY_DOCUMENT]: getGlobalObject('document'), [KEY_DOCUMENT]: getGlobalObject("document"),
[KEY_QUERY]: 'head', [KEY_QUERY]: "head",
[KEY_TIMEOUT]: 10000, [KEY_TIMEOUT]: 10000,
[ATTRIBUTE_ID]: (new ID('resource')).toString(), [ATTRIBUTE_ID]: new ID("resource").toString(),
[ATTRIBUTE_CLASS]: undefined, [ATTRIBUTE_CLASS]: undefined,
[ATTRIBUTE_TITLE]: undefined [ATTRIBUTE_TITLE]: undefined,
}) });
} }
/** /**
...@@ -150,40 +146,35 @@ class Resource extends BaseWithOptions { ...@@ -150,40 +146,35 @@ class Resource extends BaseWithOptions {
available() { available() {
const self = this; const self = this;
if (!(self[referenceSymbol] instanceof HTMLElement)) { if (!(self[referenceSymbol] instanceof HTMLElement)) {
return Promise.reject('no element') return Promise.reject("no element");
} }
if (!self.isConnected()) { 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()["loaded"] === true) {
if (self[internalStateSymbol].getSubject()["error"] !== undefined) {
if (self[internalStateSymbol].getSubject()['error'] !== undefined) { return Promise.reject(self[internalStateSymbol].getSubject()["error"]);
return Promise.reject(self[internalStateSymbol].getSubject()['error']);
} }
return Promise.resolve(); return Promise.resolve();
} }
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
reject('timeout'); reject("timeout");
}, self.getOption('timeout')) }, self.getOption("timeout"));
const observer = new Observer(() => { const observer = new Observer(() => {
clearTimeout(timeout); clearTimeout(timeout);
self[internalStateSymbol].detachObserver(observer); self[internalStateSymbol].detachObserver(observer);
resolve(); resolve();
}) });
self[internalStateSymbol].attachObserver(observer); self[internalStateSymbol].attachObserver(observer);
}); });
}
};
/** /**
* @return {string} * @return {string}
...@@ -198,10 +189,8 @@ class Resource extends BaseWithOptions { ...@@ -198,10 +189,8 @@ class Resource extends BaseWithOptions {
static get [instanceSymbol]() { static get [instanceSymbol]() {
return Symbol.for("@schukai/monster/dom/resource"); return Symbol.for("@schukai/monster/dom/resource");
} }
} }
/** /**
* @private * @private
* @return {Promise} * @return {Promise}
...@@ -210,9 +199,9 @@ class Resource extends BaseWithOptions { ...@@ -210,9 +199,9 @@ class Resource extends BaseWithOptions {
function appendToDocument() { function appendToDocument() {
const self = this; 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)) { if (!(targetNode instanceof HTMLElement)) {
throw new Error('target not found') throw new Error("target not found");
} }
addEvents.call(self); addEvents.call(self);
...@@ -229,28 +218,26 @@ function addEvents() { ...@@ -229,28 +218,26 @@ function addEvents() {
const self = this; const self = this;
const onError = () => { const onError = () => {
self[referenceSymbol].removeEventListener("error", onError);
self[referenceSymbol].removeEventListener('error', onError); self[referenceSymbol].removeEventListener("load", onLoad);
self[referenceSymbol].removeEventListener('load', onLoad);
self[internalStateSymbol].setSubject({ self[internalStateSymbol].setSubject({
loaded: true, loaded: true,
error: self[referenceSymbol][self.constructor.getURLAttribute()] + ' is not available', error: `${self[referenceSymbol][self.constructor.getURLAttribute()]} is not available`,
}) });
return; return;
} };
const onLoad = () => { const onLoad = () => {
self[referenceSymbol].removeEventListener('error', onError); self[referenceSymbol].removeEventListener("error", onError);
self[referenceSymbol].removeEventListener('load', onLoad); self[referenceSymbol].removeEventListener("load", onLoad);
self[internalStateSymbol].getSubject()['loaded'] = true; self[internalStateSymbol].getSubject()["loaded"] = true;
return; return;
} };
self[referenceSymbol].addEventListener('load', onLoad, false); self[referenceSymbol].addEventListener("load", onLoad, false);
self[referenceSymbol].addEventListener('error', onError, false); self[referenceSymbol].addEventListener("error", onError, false);
return self; return self;
} }