update repo structure

This commit is contained in:
Rene Haas
2022-07-30 19:45:11 +02:00
parent 908f692569
commit 843d627715
158 changed files with 26998 additions and 9790 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
const resolve = require('./resolve.config');
const resolve = require('@local/config/resolve');
module.exports = {
extends: [
+5
View File
@@ -0,0 +1,5 @@
declare type ResizeListener = (width: number, height: number) => void;
export declare const resize: (element: HTMLElement) => {
addResizeListener(listener: ResizeListener): void;
};
export {};
+72
View File
@@ -0,0 +1,72 @@
// @ts-ignore
import { createDiv, appendChildren, parent, style, on, off, addClass, clientSize, each, } from './support';
export const resize = (element) => {
const resizeListeners = [];
const strMouseTouchDownEvent = 'mousedown touchstart';
const strMouseTouchUpEvent = 'mouseup touchend';
const strMouseTouchMoveEvent = 'mousemove touchmove';
const strSelectStartEvent = 'selectstart';
const dragStartSize = { w: 0, h: 0 };
const dragStartPosition = { x: 0, y: 0 };
const resizeBtn = createDiv('resizeBtn');
appendChildren(element, resizeBtn);
addClass(element, 'resizer');
let dragResizeBtn;
let dragResizer;
const onSelectStart = (event) => {
event.preventDefault();
return false;
};
const resizerResize = (event) => {
const isTouchEvent = event.touches !== undefined;
const mouseOffsetHolder = isTouchEvent
? event.touches[0]
: event;
const sizeStyle = {
width: dragStartSize.w + mouseOffsetHolder.pageX - dragStartPosition.x,
height: dragStartSize.h + mouseOffsetHolder.pageY - dragStartPosition.y,
};
style(dragResizer, sizeStyle);
each(resizeListeners, (listener) => {
if (listener) {
listener(sizeStyle.width, sizeStyle.height);
}
});
event.stopPropagation();
};
const resizerResized = () => {
off(document, strSelectStartEvent, onSelectStart);
off(document, strMouseTouchMoveEvent, resizerResize);
off(document, strMouseTouchUpEvent, resizerResized);
dragResizer = undefined;
dragResizeBtn = undefined;
};
on(resizeBtn, strMouseTouchDownEvent, (event) => {
const { currentTarget } = event;
const correctButton = event.buttons === 1 || event.which === 1;
const isTouchEvent = event.touches !== undefined;
const mouseOffsetHolder = isTouchEvent
? event.touches[0]
: event;
if (correctButton || isTouchEvent) {
dragStartPosition.x = mouseOffsetHolder.pageX;
dragStartPosition.y = mouseOffsetHolder.pageY;
dragResizeBtn = currentTarget;
dragResizer = parent(currentTarget);
const cSize = clientSize(element);
dragStartSize.w = cSize.w;
dragStartSize.h = cSize.h;
on(document, strSelectStartEvent, onSelectStart, { _passive: false });
on(document, strMouseTouchMoveEvent, resizerResize, { _passive: false });
on(document, strMouseTouchUpEvent, resizerResized, { _passive: false });
event.preventDefault();
event.stopPropagation();
}
}, { _passive: false });
return {
addResizeListener(listener) {
resizeListeners.push(listener);
},
};
};
//# sourceMappingURL=Resize.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Resize.js","sourceRoot":"","sources":["../src/Resize.ts"],"names":[],"mappings":"AAAA,aAAa;AACb,OAAO,EACL,SAAS,EACT,cAAc,EACd,MAAM,EACN,KAAK,EACL,EAAE,EACF,GAAG,EACH,QAAQ,EAGR,UAAU,EACV,IAAI,GACL,MAAM,WAAW,CAAC;AAInB,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,OAAoB,EAAE,EAAE;IAC7C,MAAM,eAAe,GAAqB,EAAE,CAAC;IAC7C,MAAM,sBAAsB,GAAG,sBAAsB,CAAC;IACtD,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;IAChD,MAAM,sBAAsB,GAAG,qBAAqB,CAAC;IACrD,MAAM,mBAAmB,GAAG,aAAa,CAAC;IAC1C,MAAM,aAAa,GAAe,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACjD,MAAM,iBAAiB,GAAe,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;IACrD,MAAM,SAAS,GAAG,SAAS,CAAC,WAAW,CAAC,CAAC;IACzC,cAAc,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,SAAS,CAAC,CAAC;IAE7B,IAAI,aAAsC,CAAC;IAC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,QAAwB;YACxC,eAAe,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACjC,CAAC;KACF,CAAC;AACJ,CAAC,CAAC"}
+10
View File
@@ -0,0 +1,10 @@
/// <reference types="jest" />
export declare const generateSelectCallback: (targetElms: HTMLElement[] | HTMLElement | null, callback: (targetAffectedElm: HTMLElement, possibleValues: string[], selectedValue: string) => any) => (event: Event | HTMLSelectElement | null) => void;
export declare const generateClassChangeSelectCallback: (targetElms: HTMLElement[] | HTMLElement | null) => (event: Event | HTMLSelectElement | null) => void;
export declare const selectOption: (select: HTMLSelectElement | null, selectedOption: string | number) => boolean;
export declare const iterateSelect: <T>(select: HTMLSelectElement | null, options?: {
filter?: ((value: string, index: number, array: string[]) => boolean) | undefined;
beforeEach?: (() => T | Promise<T>) | undefined;
check?: ((input: T, selectedOptions: string) => void | Promise<void>) | undefined;
afterEach?: (() => void | Promise<void>) | undefined;
} | undefined) => Promise<void>;
+75
View File
@@ -0,0 +1,75 @@
function isEvent(obj) {
return obj instanceof Event || !!obj.target;
}
// eslint-disable-next-line
const noop = () => {
return {};
};
const getSelectOptions = (selectElement) => Array.from(selectElement.options).map((option) => option.value);
export const generateSelectCallback = (targetElms, callback) => (event) => {
const target = isEvent(event)
? event.target
: event;
if (target) {
const selectedOption = target.value;
const selectOptions = getSelectOptions(target);
const elmsArr = Array.isArray(targetElms) ? targetElms : [targetElms];
elmsArr.forEach((elm) => {
if (elm) {
callback(elm, selectOptions, selectedOption);
}
});
}
};
export const generateClassChangeSelectCallback = (targetElms) => generateSelectCallback(targetElms, (targetAffectedElm, possibleValues, selectedValue) => {
possibleValues.forEach((clazz) => targetAffectedElm.classList.remove(clazz));
targetAffectedElm.classList.add(selectedValue);
});
export const selectOption = (select, selectedOption) => {
if (!select) {
return false;
}
const options = getSelectOptions(select);
const currValue = select.value;
if (selectedOption === currValue) {
return false;
}
if (typeof selectedOption === 'string' && options.includes(selectedOption)) {
select.value = selectedOption;
}
else if (typeof selectedOption === 'number' &&
options.length < selectedOption &&
selectedOption > -1) {
select.selectedIndex = selectedOption;
}
let event;
if (typeof Event === 'function') {
event = new Event('change');
}
else {
event = document.createEvent('Event');
event.initEvent('change', true, true);
}
select.dispatchEvent(event);
return true;
};
export const iterateSelect = async (select, options) => {
if (select) {
const { beforeEach = noop, check = noop, afterEach = noop, filter } = options || {};
const selectOptions = getSelectOptions(select);
const selectOptionsReversed = getSelectOptions(select).reverse();
const iterateOptions = [...selectOptions, ...selectOptionsReversed].filter(filter || (() => true));
for (let i = 0; i < iterateOptions.length; i++) {
const option = iterateOptions[i];
// eslint-disable-next-line
const beforeEachObj = await beforeEach();
if (selectOption(select, option)) {
// eslint-disable-next-line
await check(beforeEachObj, option);
// eslint-disable-next-line
await afterEach();
}
}
}
};
//# sourceMappingURL=Select.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Select.js","sourceRoot":"","sources":["../src/Select.ts"],"names":[],"mappings":"AAAA,SAAS,OAAO,CAAC,GAAQ;IACvB,OAAO,GAAG,YAAY,KAAK,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC;AAC9C,CAAC;AAED,2BAA2B;AAC3B,MAAM,IAAI,GAAG,GAAS,EAAE;IACtB,OAAO,EAAO,CAAC;AACjB,CAAC,CAAC;AAEF,MAAM,gBAAgB,GAAG,CAAC,aAAgC,EAAE,EAAE,CAC5D,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAElE,MAAM,CAAC,MAAM,sBAAsB,GACjC,CACE,UAA8C,EAC9C,QAIQ,EACR,EAAE,CACJ,CAAC,KAAuC,EAAE,EAAE;IAC1C,MAAM,MAAM,GAA6B,OAAO,CAAC,KAAK,CAAC;QACrD,CAAC,CAAE,KAAK,CAAC,MAA4B;QACrC,CAAC,CAAC,KAAK,CAAC;IACV,IAAI,MAAM,EAAE;QACV,M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C5C,IAAI,YAAY,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE;gBAChC,2BAA2B;gBAC3B,MAAM,KAAK,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;gBACnC,2BAA2B;gBAC3B,MAAM,SAAS,EAAE,CAAC;aACnB;SACF;KACF;AACH,CAAC,CAAC"}
+4
View File
@@ -0,0 +1,4 @@
import { waitForOptions } from '@testing-library/dom';
export declare const setTestResult: (result: boolean | null) => void;
export declare const testPassed: () => boolean;
export declare const waitForOrFailTest: <T>(callback: () => T | Promise<T>, options?: waitForOptions) => Promise<T>;
+30
View File
@@ -0,0 +1,30 @@
import { waitFor } from '@testing-library/dom';
const getTestResultElm = () => document.getElementById('testResult');
export const setTestResult = (result) => {
const elm = getTestResultElm();
if (elm) {
if (typeof result === 'boolean') {
if (result) {
if (elm.getAttribute('class') === 'failed') {
return;
}
}
elm.setAttribute('class', result ? 'passed' : 'failed');
}
else {
elm.removeAttribute('class');
}
}
};
export const testPassed = () => {
const elm = getTestResultElm();
return elm ? elm.getAttribute('class') === 'passed' : false;
};
export const waitForOrFailTest = (callback, options) => waitFor(callback, {
...options,
onTimeout(error) {
setTestResult(false);
return error;
},
});
//# sourceMappingURL=TestResult.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"TestResult.js","sourceRoot":"","sources":["../src/TestResult.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAkB,MAAM,sBAAsB,CAAC;AAE/D,MAAM,gBAAgB,GAAG,GAAG,EAAE,CAAC,QAAQ,CAAC,cAAc,CAAC,YAAY,CAAC,CAAC;AAErE,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,MAAsB,EAAE,EAAE;IACtD,MAAM,GAAG,GAAG,gBAAgB,EAAE,CAAC;IAC/B,IAAI,GAAG,EAAE;QACP,IAAI,OAAO,MAAM,KAAK,SAAS,EAAE;YAC/B,IAAI,MAAM,EAAE;gBACV,IAAI,GAAG,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,QAAQ,EAAE;oBAC1C,OAAO;iBACR;aACF;YACD,GAAG,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;SACzD;aAAM;YACL,GAAG,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;SAC9B;KACF;AACH,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,UAAU,GAAG,GAAY,EAAE;IACtC,MAAM,GAAG,GAAG,gBAAgB,EAAE,CAAC;IAC/B,OAAO,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC;AAC9D,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAI,QAA8B,EAAE,OAAwB,EAAE,EAAE,CAC/F,OAAO,CAAC,QAAQ,EAAE;IAChB,GAAG,OAAO;IACV,SAAS,CAAC,KAAY;QACpB,aAAa,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;CACF,CAAC,CAAC"}
+1
View File
@@ -0,0 +1 @@
export declare const timeout: (ms: number) => Promise<unknown>;
+2
View File
@@ -0,0 +1,2 @@
export const timeout = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
//# sourceMappingURL=Timeout.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"Timeout.js","sourceRoot":"","sources":["../src/Timeout.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
export * from './Select';
export * from './TestResult';
export * from './Timeout';
+4
View File
@@ -0,0 +1,4 @@
export * from './Select';
export * from './TestResult';
export * from './Timeout';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,WAAW,CAAC"}
+28
View File
@@ -0,0 +1,28 @@
declare type ClassContainingElement = Node | Element | false | null | undefined;
declare type ClassName = string | false | null | undefined;
/**
* Check whether the given element has the given class name(s).
* @param elm The element.
* @param className The class name(s).
*/
export declare const hasClass: (elm: ClassContainingElement, className: ClassName) => boolean;
/**
* Removes the given class name(s) from the given element.
* @param elm The element.
* @param className The class name(s) which shall be removed. (separated by spaces)
*/
export declare const removeClass: (elm: ClassContainingElement, className: ClassName) => void;
/**
* Adds the given class name(s) to the given element.
* @param elm The element.
* @param className The class name(s) which shall be added. (separated by spaces)
* @returns A function which removes the added class name(s).
*/
export declare const addClass: (elm: ClassContainingElement, className: ClassName) => (() => void);
/**
* Takes two className strings, compares them and returns the difference as array.
* @param classNameA ClassName A.
* @param classNameB ClassName B.
*/
export declare const diffClass: (classNameA: ClassName, classNameB: ClassName) => string[];
export {};
+65
View File
@@ -0,0 +1,65 @@
import { isString } from '../utils/types';
import { each } from '../utils/array';
import { keys } from '../utils/object';
const rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
const classListAction = (elm, className, action) => {
const classList = elm && elm.classList;
let clazz;
let i = 0;
let result = false;
if (classList && className && isString(className)) {
const classes = className.match(rnothtmlwhite) || [];
result = classes.length > 0;
while ((clazz = classes[i++])) {
result = !!action(classList, clazz) && result;
}
}
return result;
};
/**
* Check whether the given element has the given class name(s).
* @param elm The element.
* @param className The class name(s).
*/
export const hasClass = (elm, className) => classListAction(elm, className, (classList, clazz) => classList.contains(clazz));
/**
* Removes the given class name(s) from the given element.
* @param elm The element.
* @param className The class name(s) which shall be removed. (separated by spaces)
*/
export const removeClass = (elm, className) => {
classListAction(elm, className, (classList, clazz) => classList.remove(clazz));
};
/**
* Adds the given class name(s) to the given element.
* @param elm The element.
* @param className The class name(s) which shall be added. (separated by spaces)
* @returns A function which removes the added class name(s).
*/
export const addClass = (elm, className) => {
classListAction(elm, className, (classList, clazz) => classList.add(clazz));
return removeClass.bind(0, elm, className);
};
/**
* Takes two className strings, compares them and returns the difference as array.
* @param classNameA ClassName A.
* @param classNameB ClassName B.
*/
export const diffClass = (classNameA, classNameB) => {
const classNameASplit = classNameA && classNameA.split(' ');
const classNameBSplit = classNameB && classNameB.split(' ');
const tempObj = {};
each(classNameASplit, (className) => {
tempObj[className] = 1;
});
each(classNameBSplit, (className) => {
if (tempObj[className]) {
delete tempObj[className];
}
else {
tempObj[className] = 1;
}
});
return keys(tempObj);
};
//# sourceMappingURL=class.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"class.js","sourceRoot":"","sources":["../../../src/support/dom/class.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAKvC,MAAM,aAAa,GAAG,mBAAmB,CAAC;AAC1C,MAAM,eAAe,GAAG,CACtB,GAA2B,EAC3B,SAAoB,EACpB,MAAqE,EAC5D,EAAE;IACX,MAAM,SAAS,GAAG,GAAG,IAAK,GAAe,CAAC,SAAS,CAAC;IACpD,IAAI,KAAa,CAAC;IAClB,IAAI,CAAC,GAAG,CAAC,CAAC;IACV,IAAI,MAAM,GAAG,KAAK,CAAC;IAEnB,IAAI,SAAS,IAAI,SAAS,IAAI,QAAQ,CAAC,SAAS,CAAC,EAAE;QACjD,MAAM,OAAO,GAAkB,SAAS,CAAC,KAAK,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;QACpE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5B,OAAO,CAAC,KAAK,GAAG,OAAO,CAAC,CAAC,E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AC;IAEnB,IAAI,CAAC,eAAe,EAAE,CAAC,SAAS,EAAE,EAAE;QAClC,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;IACzB,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,eAAe,EAAE,CAAC,SAAS,EAAE,EAAE;QAClC,IAAI,OAAO,CAAC,SAAS,CAAC,EAAE;YACtB,OAAO,OAAO,CAAC,SAAS,CAAC,CAAC;SAC3B;aAAM;YACL,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;SACxB;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;AACvB,CAAC,CAAC"}
+9
View File
@@ -0,0 +1,9 @@
/**
* Creates a div DOM node.
*/
export declare const createDiv: (classNames?: string) => HTMLDivElement;
/**
* Creates DOM nodes modeled after the passed html string and returns the root dom nodes as a array.
* @param html The html string after which the DOM nodes shall be created.
*/
export declare const createDOM: (html: string) => ReadonlyArray<Node>;
+23
View File
@@ -0,0 +1,23 @@
import { each } from '../utils/array';
import { contents } from './traversal';
import { removeElements } from './manipulation';
/**
* Creates a div DOM node.
*/
export const createDiv = (classNames) => {
const div = document.createElement('div');
if (classNames) {
div.setAttribute('class', classNames);
}
return div;
};
/**
* Creates DOM nodes modeled after the passed html string and returns the root dom nodes as a array.
* @param html The html string after which the DOM nodes shall be created.
*/
export const createDOM = (html) => {
const createdDiv = createDiv();
createdDiv.innerHTML = html.trim();
return each(contents(createdDiv), (elm) => removeElements(elm));
};
//# sourceMappingURL=create.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"create.js","sourceRoot":"","sources":["../../../src/support/dom/create.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,UAAmB,EAAkB,EAAE;IAC/D,MAAM,GAAG,GAAG,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IAC1C,IAAI,UAAU,EAAE;QACd,GAAG,CAAC,YAAY,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;KACvC;IACD,OAAO,GAAG,CAAC;AACb,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,IAAY,EAAuB,EAAE;IAC7D,MAAM,UAAU,GAAG,SAAS,EAAE,CAAC;IAC/B,UAAU,CAAC,SAAS,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;IAEnC,OAAO,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,CAAC;AAClE,CAAC,CAAC"}
+33
View File
@@ -0,0 +1,33 @@
export interface WH<T = number> {
w: T;
h: T;
}
/**
* Returns the window inner- width and height.
*/
export declare const windowSize: () => WH;
/**
* Returns the scroll- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the scroll- width and height shall be returned.
*/
export declare const offsetSize: (elm: HTMLElement | null | undefined) => WH;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export declare const clientSize: (elm: HTMLElement | false | null | undefined) => WH;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export declare const scrollSize: (elm: HTMLElement | false | null | undefined) => WH;
/**
* Returns the BoundingClientRect of the passed element.
* @param elm The element of which the BoundingClientRect shall be returned.
*/
export declare const getBoundingClientRect: (elm: HTMLElement) => DOMRect;
/**
* Determines whether the passed element has any dimensions.
* @param elm The element.
*/
export declare const hasDimensions: (elm: HTMLElement | false | null | undefined) => boolean;
+53
View File
@@ -0,0 +1,53 @@
const elementHasDimensions = (elm) => !!(elm.offsetWidth || elm.offsetHeight || elm.getClientRects().length);
const zeroObj = {
w: 0,
h: 0,
};
/**
* Returns the window inner- width and height.
*/
export const windowSize = () => ({
w: window.innerWidth,
h: window.innerHeight,
});
/**
* Returns the scroll- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the scroll- width and height shall be returned.
*/
export const offsetSize = (elm) => elm
? {
w: elm.offsetWidth,
h: elm.offsetHeight,
}
: zeroObj;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export const clientSize = (elm) => elm
? {
w: elm.clientWidth,
h: elm.clientHeight,
}
: zeroObj;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export const scrollSize = (elm) => elm
? {
w: elm.scrollWidth,
h: elm.scrollHeight,
}
: zeroObj;
/**
* Returns the BoundingClientRect of the passed element.
* @param elm The element of which the BoundingClientRect shall be returned.
*/
export const getBoundingClientRect = (elm) => elm.getBoundingClientRect();
/**
* Determines whether the passed element has any dimensions.
* @param elm The element.
*/
export const hasDimensions = (elm) => elm ? elementHasDimensions(elm) : false;
//# sourceMappingURL=dimensions.js.map
@@ -0,0 +1 @@
{"version":3,"file":"dimensions.js","sourceRoot":"","sources":["../../../src/support/dom/dimensions.ts"],"names":[],"mappings":"AAKA,MAAM,oBAAoB,GAAG,CAAC,GAAgB,EAAW,EAAE,CACzD,CAAC,CAAC,CAAC,GAAG,CAAC,WAAW,IAAI,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,cAAc,EAAE,CAAC,MAAM,CAAC,CAAC;AACzE,MAAM,OAAO,GAAO;IAClB,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,CAAC;CACL,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAO,EAAE,CAAC,CAAC;IACnC,CAAC,EAAE,MAAM,CAAC,UAAU;IACpB,CAAC,EAAE,MAAM,CAAC,WAAW;CACtB,CAAC,CAAC;AAEH;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAmC,EAAM,EAAE,CACpE,GAAG;IACD,CAAC,CAAC;QACE,CAAC,EAAE,GAAG,CAAC,WAAW;QAClB,CAAC,EAAE,GAAG,CAAC,YAAY;KACpB;IACH,CAAC,CAAC,OAAO,CAAC;AAEd;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAA2C,EAAM,EAAE,CAC5E,GAAG;IACD,CAAC,CAAC;QACE,CAAC,EAAE,GAAG,CAAC,WAAW;QAClB,CAAC,EAAE,GAAG,CAAC,YAAY;KACpB;IACH,CAAC,CAAC,OAAO,CAAC;AAEd;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAA2C,EAAM,EAAE,CAC5E,GAAG;IACD,CAAC,CAAC;QACE,CAAC,EAAE,GAAG,CAAC,WAAW;QAClB,CAAC,EAAE,GAAG,CAAC,YAAY;KACpB;IACH,CAAC,CAAC,OAAO,CAAC;AAEd;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,GAAgB,EAAW,EAAE,CAAC,GAAG,CAAC,qBAAqB,EAAE,CAAC;AAEhG;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAA2C,EAAW,EAAE,CACpF,GAAG,CAAC,CAAC,CAAC,oBAAoB,CAAC,GAAkB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC"}
+36
View File
@@ -0,0 +1,36 @@
export interface OnOptions {
_capture?: boolean;
_passive?: boolean;
_once?: boolean;
}
/**
* Removes the passed event listener for the passed events with the passed options.
* @param target The element from which the listener shall be removed.
* @param eventNames The eventsnames for which the listener shall be removed.
* @param listener The listener which shall be removed.
* @param capture The options of the removed listener.
*/
export declare const off: <T extends Event = Event>(target: EventTarget, eventNames: string, listener: (event: T) => any, capture?: boolean) => void;
/**
* Adds the passed event listener for the passed eventnames with the passed options.
* @param target The element to which the listener shall be added.
* @param eventNames The eventsnames for which the listener shall be called.
* @param listener The listener which is called on the eventnames.
* @param options The options of the added listener.
*/
export declare const on: <T extends Event = Event>(target: EventTarget, eventNames: string, listener: (event: T) => any, options?: OnOptions) => (() => void);
/**
* Shorthand for the stopPropagation event Method.
* @param evt The event of which the stopPropagation method shall be called.
*/
export declare const stopPropagation: (evt: Event) => void;
/**
* Shorthand for the preventDefault event Method.
* @param evt The event of which the preventDefault method shall be called.
*/
export declare const preventDefault: (evt: Event) => void;
/**
* Shorthand for the stopPropagation and preventDefault event Method.
* @param evt The event of which the stopPropagation and preventDefault methods shall be called.
*/
export declare const stopAndPrevent: (evt: Event) => void;
+80
View File
@@ -0,0 +1,80 @@
import { isUndefined } from '../utils/types';
import { each, push, runEachAndClear } from '../utils/array';
let passiveEventsSupport;
const supportPassiveEvents = () => {
if (isUndefined(passiveEventsSupport)) {
passiveEventsSupport = false;
try {
/* eslint-disable */
// @ts-ignore
window.addEventListener('test', null, Object.defineProperty({}, 'passive', {
get() {
passiveEventsSupport = true;
},
}));
/* eslint-enable */
}
catch (e) { }
}
return passiveEventsSupport;
};
const splitEventNames = (eventNames) => eventNames.split(' ');
/**
* Removes the passed event listener for the passed events with the passed options.
* @param target The element from which the listener shall be removed.
* @param eventNames The eventsnames for which the listener shall be removed.
* @param listener The listener which shall be removed.
* @param capture The options of the removed listener.
*/
export const off = (target, eventNames, listener, capture) => {
each(splitEventNames(eventNames), (eventName) => {
target.removeEventListener(eventName, listener, capture);
});
};
/**
* Adds the passed event listener for the passed eventnames with the passed options.
* @param target The element to which the listener shall be added.
* @param eventNames The eventsnames for which the listener shall be called.
* @param listener The listener which is called on the eventnames.
* @param options The options of the added listener.
*/
export const on = (target, eventNames, listener, options) => {
const doSupportPassiveEvents = supportPassiveEvents();
const passive = (doSupportPassiveEvents && options && options._passive) ?? doSupportPassiveEvents;
const capture = (options && options._capture) || false;
const once = (options && options._once) || false;
const offListeners = [];
const nativeOptions = doSupportPassiveEvents
? {
passive,
capture,
}
: capture;
each(splitEventNames(eventNames), (eventName) => {
const finalListener = (once
? (evt) => {
target.removeEventListener(eventName, finalListener, capture);
listener && listener(evt);
}
: listener);
push(offListeners, off.bind(null, target, eventName, finalListener, capture));
target.addEventListener(eventName, finalListener, nativeOptions);
});
return runEachAndClear.bind(0, offListeners);
};
/**
* Shorthand for the stopPropagation event Method.
* @param evt The event of which the stopPropagation method shall be called.
*/
export const stopPropagation = (evt) => evt.stopPropagation();
/**
* Shorthand for the preventDefault event Method.
* @param evt The event of which the preventDefault method shall be called.
*/
export const preventDefault = (evt) => evt.preventDefault();
/**
* Shorthand for the stopPropagation and preventDefault event Method.
* @param evt The event of which the stopPropagation and preventDefault methods shall be called.
*/
export const stopAndPrevent = (evt) => stopPropagation(evt) || preventDefault(evt);
//# sourceMappingURL=events.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/support/dom/events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAE7D,IAAI,oBAA6B,CAAC;AAClC,MAAM,oBAAoB,GAAG,GAAY,EAAE;IACzC,IAAI,WAAW,CAAC,oBAAoB,CAAC,EAAE;QACrC,oBAAoB,GAAG,KAAK,CAAC;QAC7B,IAAI;YACF,oBAAoB;YACpB,aAAa;YACb,MAAM,CAAC,gBAAgB,CACrB,MAAM,EACN,IAAI,EACJ,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,SAAS,EAAE;gBACnC,GAAG;oBACD,oBAAoB,GAAG,IAAI,CAAC;gBAC9B,CAAC;aACF,CAAC,CACH,CAAC;YACF,mBAAmB;SACpB;QAAC,OAAO,CAAC,EAAE,GAAE;KACf;IACD,OAAO,oBAAoB,CAAC;AAC9B,CAAC,CAAC;AACF,MAAM,eAAe,GAAG,C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AAC,CAAC;YAC5B,CAAC;YACH,CAAC,CAAC,QAAQ,CACI,CAAC;QAEnB,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,OAAO,CAAC,CAAC,CAAC;QAC9E,MAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC;IACnE,CAAC,CAAC,CAAC;IAEH,OAAO,eAAe,CAAC,IAAI,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC;AAC/C,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAU,EAAQ,EAAE,CAAC,GAAG,CAAC,eAAe,EAAE,CAAC;AAE3E;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAU,EAAQ,EAAE,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;AAEzE;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAU,EAAQ,EAAE,CAChD,eAAe,CAAC,GAAG,CAAe,IAAK,cAAc,CAAC,GAAG,CAAe,CAAC"}
+8
View File
@@ -0,0 +1,8 @@
export * from './class';
export * from './create';
export * from './dimensions';
export * from './events';
export * from './style';
export * from './manipulation';
export * from './offset';
export * from './traversal';
+9
View File
@@ -0,0 +1,9 @@
export * from './class';
export * from './create';
export * from './dimensions';
export * from './events';
export * from './style';
export * from './manipulation';
export * from './offset';
export * from './traversal';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/support/dom/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC"}
@@ -0,0 +1,31 @@
declare type NodeCollection = ArrayLike<Node> | Node | false | null | undefined;
/**
* Appends the given children at the end of the given Node.
* @param node The Node to which the children shall be appended.
* @param children The Nodes which shall be appended.
*/
export declare const appendChildren: (node: Node | false | null | undefined, children: NodeCollection) => void;
/**
* Prepends the given children at the start of the given Node.
* @param node The Node to which the children shall be prepended.
* @param children The Nodes which shall be prepended.
*/
export declare const prependChildren: (node: Node | false | null | undefined, children: NodeCollection) => void;
/**
* Inserts the given Nodes before the given Node.
* @param node The Node before which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export declare const insertBefore: (node: Node | false | null | undefined, insertedNodes: NodeCollection) => void;
/**
* Inserts the given Nodes after the given Node.
* @param node The Node after which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export declare const insertAfter: (node: Node | false | null | undefined, insertedNodes: NodeCollection) => void;
/**
* Removes the given Nodes from their parent.
* @param nodes The Nodes which shall be removed.
*/
export declare const removeElements: (nodes: NodeCollection) => void;
export {};
+86
View File
@@ -0,0 +1,86 @@
import { isArrayLike } from '../utils/types';
import { each, from } from '../utils/array';
import { parent } from './traversal';
/**
* Inserts Nodes before the given preferredAnchor element.
* @param parentElm The parent of the preferredAnchor element or the element which shall be the parent of the inserted Nodes.
* @param preferredAnchor The element before which the Nodes shall be inserted or null if the elements shall be appended at the end.
* @param insertedElms The Nodes which shall be inserted.
*/
const before = (parentElm, preferredAnchor, insertedElms) => {
if (insertedElms && parentElm) {
let anchor = preferredAnchor;
let fragment;
if (isArrayLike(insertedElms)) {
fragment = document.createDocumentFragment();
// append all insertedElms to the fragment and if one of these is the anchor, change the anchor
each(insertedElms, (insertedElm) => {
if (insertedElm === anchor) {
anchor = insertedElm.previousSibling;
}
fragment.appendChild(insertedElm);
});
}
else {
fragment = insertedElms;
}
// if the preferred anchor isn't null set it to a valid anchor
if (preferredAnchor) {
if (!anchor) {
anchor = parentElm.firstChild;
}
else if (anchor !== preferredAnchor) {
anchor = anchor.nextSibling;
}
}
parentElm.insertBefore(fragment, anchor || null);
}
};
/**
* Appends the given children at the end of the given Node.
* @param node The Node to which the children shall be appended.
* @param children The Nodes which shall be appended.
*/
export const appendChildren = (node, children) => {
before(node, null, children);
};
/**
* Prepends the given children at the start of the given Node.
* @param node The Node to which the children shall be prepended.
* @param children The Nodes which shall be prepended.
*/
export const prependChildren = (node, children) => {
before(node, node && node.firstChild, children);
};
/**
* Inserts the given Nodes before the given Node.
* @param node The Node before which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export const insertBefore = (node, insertedNodes) => {
before(parent(node), node, insertedNodes);
};
/**
* Inserts the given Nodes after the given Node.
* @param node The Node after which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export const insertAfter = (node, insertedNodes) => {
before(parent(node), node && node.nextSibling, insertedNodes);
};
/**
* Removes the given Nodes from their parent.
* @param nodes The Nodes which shall be removed.
*/
export const removeElements = (nodes) => {
if (isArrayLike(nodes)) {
each(from(nodes), (e) => removeElements(e));
}
else if (nodes) {
const parentElm = parent(nodes);
if (parentElm) {
parentElm.removeChild(nodes);
}
}
};
//# sourceMappingURL=manipulation.js.map
@@ -0,0 +1 @@
{"version":3,"file":"manipulation.js","sourceRoot":"","sources":["../../../src/support/dom/manipulation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAIrC;;;;;GAKG;AACH,MAAM,MAAM,GAAG,CACb,SAA0C,EAC1C,eAAgD,EAChD,YAA4B,EACtB,EAAE;IACR,IAAI,YAAY,IAAI,SAAS,EAAE;QAC7B,IAAI,MAAM,GAAoC,eAAe,CAAC;QAC9D,IAAI,QAAoD,CAAC;QAEzD,IAAI,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G;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CACzB,IAAqC,EACrC,aAA6B,EACvB,EAAE;IACR,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,IAAI,IAAI,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;AAChE,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAqB,EAAQ,EAAE;IAC5D,IAAI,WAAW,CAAC,KAAK,CAAC,EAAE;QACtB,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAC;KAC7C;SAAM,IAAI,KAAK,EAAE;QAChB,MAAM,SAAS,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAChC,IAAI,SAAS,EAAE;YACb,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;SAC9B;KACF;AACH,CAAC,CAAC"}
+14
View File
@@ -0,0 +1,14 @@
export interface XY<T = number> {
x: T;
y: T;
}
/**
* Returns the offset- left and top coordinates of the passed element relative to the document. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export declare const absoluteCoordinates: (elm: HTMLElement | null | undefined) => XY;
/**
* Returns the offset- left and top coordinates of the passed element. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export declare const offsetCoordinates: (elm: HTMLElement | null | undefined) => XY;
+29
View File
@@ -0,0 +1,29 @@
import { getBoundingClientRect } from './dimensions';
const zeroObj = {
x: 0,
y: 0,
};
/**
* Returns the offset- left and top coordinates of the passed element relative to the document. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export const absoluteCoordinates = (elm) => {
const rect = elm ? getBoundingClientRect(elm) : 0;
return rect
? {
x: rect.left + window.pageYOffset,
y: rect.top + window.pageXOffset,
}
: zeroObj;
};
/**
* Returns the offset- left and top coordinates of the passed element. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export const offsetCoordinates = (elm) => elm
? {
x: elm.offsetLeft,
y: elm.offsetTop,
}
: zeroObj;
//# sourceMappingURL=offset.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"offset.js","sourceRoot":"","sources":["../../../src/support/dom/offset.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAOrD,MAAM,OAAO,GAAO;IAClB,CAAC,EAAE,CAAC;IACJ,CAAC,EAAE,CAAC;CACL,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,GAAmC,EAAM,EAAE;IAC7E,MAAM,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAClD,OAAO,IAAI;QACT,CAAC,CAAC;YACE,CAAC,EAAE,IAAI,CAAC,IAAI,GAAG,MAAM,CAAC,WAAW;YACjC,CAAC,EAAE,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC,WAAW;SACjC;QACH,CAAC,CAAC,OAAO,CAAC;AACd,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAAmC,EAAM,EAAE,CAC3E,GAAG;IACD,CAAC,CAAC;QACE,CAAC,EAAE,GAAG,CAAC,UAAU;QACjB,CAAC,EAAE,GAAG,CAAC,SAAS;KACjB;IACH,CAAC,CAAC,OAAO,CAAC"}
+37
View File
@@ -0,0 +1,37 @@
export interface TRBL {
t: number;
r: number;
b: number;
l: number;
}
declare type StyleObject<CustomCssProps = ''> = {
[Key in keyof CSSStyleDeclaration | (CustomCssProps extends string ? CustomCssProps : '')]?: string | number;
};
/**
* Gets or sets the passed styles to the passed element.
* @param elm The element to which the styles shall be applied to / be read from.
* @param styles The styles which shall be set or read.
*/
export declare function style<CustomCssProps>(elm: HTMLElement | false | null | undefined, styles: StyleObject<CustomCssProps>): void;
export declare function style<CustomCssProps>(elm: HTMLElement | false | null | undefined, styles: string): string;
export declare function style<CustomCssProps>(elm: HTMLElement | false | null | undefined, styles: Array<string> | string): {
[key: string]: string;
};
/**
* Hides the passed element (display: none).
* @param elm The element which shall be hidden.
*/
export declare const hide: (elm: HTMLElement | false | null | undefined) => void;
/**
* Shows the passed element (display: block).
* @param elm The element which shall be shown.
*/
export declare const show: (elm: HTMLElement | false | null | undefined) => void;
/**
* Returns the top right bottom left values of the passed css property.
* @param elm The element of which the values shall be returned.
* @param propertyPrefix The css property prefix. (e.g. "border")
* @param propertySuffix The css property suffix. (e.g. "width")
*/
export declare const topRightBottomLeft: (elm?: HTMLElement | false | null | undefined, propertyPrefix?: string, propertySuffix?: string) => TRBL;
export {};
+96
View File
@@ -0,0 +1,96 @@
import { each, keys } from '../utils';
import { isString, isNumber, isArray, isUndefined } from '../utils/types';
const cssNumber = {
// animationiterationcount: 1,
// columncount: 1,
// fillopacity: 1,
// flexgrow: 1,
// flexshrink: 1,
// fontweight: 1,
// lineheight: 1,
// order: 1,
// orphans: 1,
// widows: 1,
// zoom: 1,
opacity: 1,
zindex: 1,
};
const parseToZeroOrNumber = (value, toFloat) => {
/* istanbul ignore next */
const num = toFloat ? parseFloat(value) : parseInt(value, 10);
// num === num means num is not NaN
/* istanbul ignore next */
return num === num ? num : 0; // eslint-disable-line no-self-compare
};
const adaptCSSVal = (prop, val) => !cssNumber[prop.toLowerCase()] && isNumber(val) ? `${val}px` : val;
const getCSSVal = (elm, computedStyle, prop) =>
/* istanbul ignore next */
computedStyle != null
? computedStyle[prop] || computedStyle.getPropertyValue(prop)
: elm.style[prop];
const setCSSVal = (elm, prop, val) => {
try {
const { style: elmStyle } = elm;
if (!isUndefined(elmStyle[prop])) {
elmStyle[prop] = adaptCSSVal(prop, val);
}
else {
elmStyle.setProperty(prop, val);
}
}
catch (e) { }
};
export function style(elm, styles) {
const getSingleStyle = isString(styles);
const getStyles = isArray(styles) || getSingleStyle;
if (getStyles) {
let getStylesResult = getSingleStyle ? '' : {};
if (elm) {
const computedStyle = window.getComputedStyle(elm, null);
getStylesResult = getSingleStyle
? getCSSVal(elm, computedStyle, styles)
: styles.reduce((result, key) => {
result[key] = getCSSVal(elm, computedStyle, key);
return result;
}, getStylesResult);
}
return getStylesResult;
}
elm && each(keys(styles), (key) => setCSSVal(elm, key, styles[key]));
}
/**
* Hides the passed element (display: none).
* @param elm The element which shall be hidden.
*/
export const hide = (elm) => {
style(elm, { display: 'none' });
};
/**
* Shows the passed element (display: block).
* @param elm The element which shall be shown.
*/
export const show = (elm) => {
style(elm, { display: 'block' });
};
/**
* Returns the top right bottom left values of the passed css property.
* @param elm The element of which the values shall be returned.
* @param propertyPrefix The css property prefix. (e.g. "border")
* @param propertySuffix The css property suffix. (e.g. "width")
*/
export const topRightBottomLeft = (elm, propertyPrefix, propertySuffix) => {
const finalPrefix = propertyPrefix ? `${propertyPrefix}-` : '';
const finalSuffix = propertySuffix ? `-${propertySuffix}` : '';
const top = `${finalPrefix}top${finalSuffix}`;
const right = `${finalPrefix}right${finalSuffix}`;
const bottom = `${finalPrefix}bottom${finalSuffix}`;
const left = `${finalPrefix}left${finalSuffix}`;
const result = style(elm, [top, right, bottom, left]);
return {
t: parseToZeroOrNumber(result[top]),
r: parseToZeroOrNumber(result[right]),
b: parseToZeroOrNumber(result[bottom]),
l: parseToZeroOrNumber(result[left]),
};
};
//# sourceMappingURL=style.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"style.js","sourceRoot":"","sources":["../../../src/support/dom/style.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAe1E,MAAM,SAAS,GAAG;IAChB,8BAA8B;IAC9B,kBAAkB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Type = Node | Element | Node | false | null | undefined;
declare type OutputElementType = Node | Element | null;
/**
* Find all elements with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
declare const find: (selector: string, elm?: InputElementType) => Element[];
/**
* Find the first element with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
declare const findFirst: (selector: string, elm?: InputElementType) => OutputElementType;
/**
* Determines whether the passed element is matching with the passed selector.
* @param elm The element which has to be compared with the passed selector.
* @param selector The selector which has to be compared with the passed element. Additional selectors: ':visible' and ':hidden'.
*/
declare const is: (elm: InputElementType, selector: string) => boolean;
/**
* Returns the children (no text-nodes or comments) of the passed element which are matching the passed selector. An empty array is returned if the passed element is null.
* @param elm The element of which the children shall be returned.
* @param selector The selector which must match with the children elements.
*/
declare const children: (elm: InputElementType, selector?: string) => ReadonlyArray<Element>;
/**
* Returns the childNodes (incl. text-nodes or comments etc.) of the passed element. An empty array is returned if the passed element is null.
* @param elm The element of which the childNodes shall be returned.
*/
declare const contents: (elm: InputElementType) => ReadonlyArray<ChildNode>;
/**
* Returns the parent element of the passed element, or null if the passed element is null.
* @param elm The element of which the parent element shall be returned.
*/
declare const parent: (elm: InputElementType) => OutputElementType;
declare const closest: (elm: InputElementType, selector: string) => OutputElementType;
/**
* Determines whether the given element lies between two selectors in the DOM.
* @param elm The element.
* @param highBoundarySelector The high boundary selector.
* @param deepBoundarySelector The deep boundary selector.
*/
declare const liesBetween: (elm: InputElementType, highBoundarySelector: string, deepBoundarySelector: string) => boolean;
export { find, findFirst, is, children, contents, parent, liesBetween, closest };
+93
View File
@@ -0,0 +1,93 @@
import { isElement } from '../utils/types';
import { push, from } from '../utils/array';
const elmPrototype = Element.prototype;
/**
* Find all elements with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
const find = (selector, elm) => {
const arr = [];
const rootElm = elm ? (isElement(elm) ? elm : null) : document;
return rootElm ? push(arr, rootElm.querySelectorAll(selector)) : arr;
};
/**
* Find the first element with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
const findFirst = (selector, elm) => {
const rootElm = elm ? (isElement(elm) ? elm : null) : document;
return rootElm ? rootElm.querySelector(selector) : null;
};
/**
* Determines whether the passed element is matching with the passed selector.
* @param elm The element which has to be compared with the passed selector.
* @param selector The selector which has to be compared with the passed element. Additional selectors: ':visible' and ':hidden'.
*/
const is = (elm, selector) => {
if (isElement(elm)) {
/* istanbul ignore next */
// eslint-disable-next-line
// @ts-ignore
const fn = elmPrototype.matches || elmPrototype.msMatchesSelector;
return fn.call(elm, selector);
}
return false;
};
/**
* Returns the children (no text-nodes or comments) of the passed element which are matching the passed selector. An empty array is returned if the passed element is null.
* @param elm The element of which the children shall be returned.
* @param selector The selector which must match with the children elements.
*/
const children = (elm, selector) => {
const childs = [];
return isElement(elm)
? push(childs, from(elm.children).filter((child) => (selector ? is(child, selector) : child)))
: childs;
};
/**
* Returns the childNodes (incl. text-nodes or comments etc.) of the passed element. An empty array is returned if the passed element is null.
* @param elm The element of which the childNodes shall be returned.
*/
const contents = (elm) => elm ? from(elm.childNodes) : [];
/**
* Returns the parent element of the passed element, or null if the passed element is null.
* @param elm The element of which the parent element shall be returned.
*/
const parent = (elm) => (elm ? elm.parentElement : null);
const closest = (elm, selector) => {
if (isElement(elm)) {
const closestFn = elmPrototype.closest;
if (closestFn) {
return closestFn.call(elm, selector);
}
do {
if (is(elm, selector)) {
return elm;
}
elm = parent(elm);
} while (elm);
}
return null;
};
/**
* Determines whether the given element lies between two selectors in the DOM.
* @param elm The element.
* @param highBoundarySelector The high boundary selector.
* @param deepBoundarySelector The deep boundary selector.
*/
const liesBetween = (elm, highBoundarySelector, deepBoundarySelector) => {
const closestHighBoundaryElm = elm && closest(elm, highBoundarySelector);
const closestDeepBoundaryElm = elm && findFirst(deepBoundarySelector, closestHighBoundaryElm);
const deepBoundaryIsValid = closest(closestDeepBoundaryElm, highBoundarySelector) === closestHighBoundaryElm;
return closestHighBoundaryElm && closestDeepBoundaryElm
? closestHighBoundaryElm === elm ||
closestDeepBoundaryElm === elm ||
(deepBoundaryIsValid &&
closest(closest(elm, deepBoundarySelector), highBoundarySelector) !==
closestHighBoundaryElm)
: false;
};
export { find, findFirst, is, children, contents, parent, liesBetween, closest };
//# sourceMappingURL=traversal.js.map
@@ -0,0 +1 @@
{"version":3,"file":"traversal.js","sourceRoot":"","sources":["../../../src/support/dom/traversal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAC;AAK5C,MAAM,YAAY,GAAG,OAAO,CAAC,SAAS,CAAC;AAEvC;;;;GAIG;AACH,MAAM,IAAI,GAAG,CAAC,QAAgB,EAAE,GAAsB,EAAa,EAAE;IACnE,MAAM,GAAG,GAAmB,EAAE,CAAC;IAC/B,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;IAE/D,OAAO,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACvE,CAAC,CAAC;AAEF;;;;GAIG;AACH,MAAM,SAAS,GAAG,CAAC,QAAgB,EAAE,GAAsB,EAAqB,EAAE;IAChF,MAAM,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC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AAC"}
+2
View File
@@ -0,0 +1,2 @@
export * from './dom';
export * from './utils';
+3
View File
@@ -0,0 +1,3 @@
export * from './dom';
export * from './utils';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/support/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,SAAS,CAAC"}
+46
View File
@@ -0,0 +1,46 @@
declare type PlainObject = Record<string, any>;
declare type RunEachItem = ((...args: any) => any | any[]) | null | undefined;
/**
* Iterates through a array or object
* @param arrayLikeOrObject The array or object through which shall be iterated.
* @param callback The function which is responsible for the iteration.
* If the function returns true its treated like a "continue" statement.
* If the function returns false its treated like a "break" statement.
*/
export declare function each<T>(array: Array<T> | ReadonlyArray<T>, callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | unknown): Array<T> | ReadonlyArray<T>;
export declare function each<T>(array: Array<T> | ReadonlyArray<T> | false | null | undefined, callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | unknown): Array<T> | ReadonlyArray<T> | false | null | undefined;
export declare function each<T>(arrayLikeObject: ArrayLike<T>, callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | unknown): ArrayLike<T>;
export declare function each<T>(arrayLikeObject: ArrayLike<T> | false | null | undefined, callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | unknown): ArrayLike<T> | false | null | undefined;
export declare function each(obj: PlainObject, callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | unknown): PlainObject;
export declare function each(obj: PlainObject | false | null | undefined, callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | unknown): PlainObject | false | null | undefined;
/**
* Returns the index of the given inside the given array or -1 if the given item isn't part of the given array.
* @param arr The array.
* @param item The item.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
*/
export declare const indexOf: <T = any>(arr: T[], item: T, fromIndex?: number) => number;
/**
* Pushesh all given items into the given array and returns it.
* @param array The array the items shall be pushed into.
* @param items The items which shall be pushed into the array.
*/
export declare const push: <T>(array: T[], items: T | ArrayLike<T>, arrayIsSingleItem?: boolean) => T[];
/**
* Creates a shallow-copied Array instance from an array-like or iterable object.
* @param arr The object from which the array instance shall be created.
*/
export declare const from: <T = any>(arr?: ArrayLike<T> | Set<T> | undefined) => T[];
/**
* Check whether the passed array is empty.
* @param array The array which shall be checked.
*/
export declare const isEmptyArray: (array: any[] | null | undefined) => boolean;
/**
* Calls all functions in the passed array/set of functions.
* @param arr The array filled with function which shall be called.
* @param args The args with which each function is called.
* @param keep True when the Set / array should not be cleared afterwards, false otherwise.
*/
export declare const runEachAndClear: (arr: RunEachItem[], args?: any[], keep?: boolean) => void;
export {};
+72
View File
@@ -0,0 +1,72 @@
import { isArrayLike, isString } from './types';
export function each(source, callback) {
if (isArrayLike(source)) {
for (let i = 0; i < source.length; i++) {
if (callback(source[i], i, source) === false) {
break;
}
}
}
else if (source) {
each(Object.keys(source), (key) => callback(source[key], key, source));
}
return source;
}
/**
* Returns the index of the given inside the given array or -1 if the given item isn't part of the given array.
* @param arr The array.
* @param item The item.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
*/
export const indexOf = (arr, item, fromIndex) => arr.indexOf(item, fromIndex);
/**
* Pushesh all given items into the given array and returns it.
* @param array The array the items shall be pushed into.
* @param items The items which shall be pushed into the array.
*/
export const push = (array, items, arrayIsSingleItem) => {
!arrayIsSingleItem && !isString(items) && isArrayLike(items)
? Array.prototype.push.apply(array, items)
: array.push(items);
return array;
};
/**
* Creates a shallow-copied Array instance from an array-like or iterable object.
* @param arr The object from which the array instance shall be created.
*/
export const from = (arr) => {
const original = Array.from;
const result = [];
if (original && arr) {
return original(arr);
}
if (arr instanceof Set) {
arr.forEach((value) => {
push(result, value);
});
}
else {
each(arr, (elm) => {
push(result, elm);
});
}
return result;
};
/**
* Check whether the passed array is empty.
* @param array The array which shall be checked.
*/
export const isEmptyArray = (array) => !!array && array.length === 0;
/**
* Calls all functions in the passed array/set of functions.
* @param arr The array filled with function which shall be called.
* @param args The args with which each function is called.
* @param keep True when the Set / array should not be cleared afterwards, false otherwise.
*/
export const runEachAndClear = (arr, args, keep) => {
// eslint-disable-next-line prefer-spread
const runFn = (fn) => fn && fn.apply(undefined, args || []);
each(arr, runFn);
!keep && (arr.length = 0);
};
//# sourceMappingURL=array.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"array.js","sourceRoot":"","sources":["../../../src/support/utils/array.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAqChD,MAAM,UAAU,IAAI,CAClB,MAA2F,EAC3F,QAAuE;IAEvE,IAAI,WAAW,CAAC,MAAM,CAAC,EAAE;QACvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,KAAK,KAAK,EAAE;gBAC5C,MAAM;aACP;SACF;KACF;SAAM,IAAI,MAAM,EAAE;QACjB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC;KACxE;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAU,GAAQ,EAAE,IAAO,EAAE,SAAkB,EAAU,EAAE,CAChF,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAAI,KAAU,EAAE,KAAuB,EAAE,iBAA2B,EAAO,EAAE;IAC/F,CAAC,iBAAiB,IA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E,CAAC,CAAC;IACzE,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACjB,CAAC,IAAI,IAAI,CAAE,GAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACvC,CAAC,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
export * from './array';
export * from './object';
export * from './types';
+4
View File
@@ -0,0 +1,4 @@
export * from './array';
export * from './object';
export * from './types';
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/support/utils/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC"}
+26
View File
@@ -0,0 +1,26 @@
/**
* Determines whether the passed object has a property with the passed name.
* @param obj The object.
* @param prop The name of the property.
*/
export declare const hasOwnProperty: (obj: any, prop: string | number | symbol) => boolean;
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param obj The object of which the properties shall be returned.
*/
export declare const keys: (obj: any) => Array<string>;
declare type AssignDeep = {
<T, U>(target: T, object1: U): T & U;
<T, U, V>(target: T, object1: U, object2: V): T & U & V;
<T, U, V, W>(target: T, object1: U, object2: V, object3: W): T & U & V & W;
<T, U, V, W, X>(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X;
<T, U, V, W, X, Y>(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y;
<T, U, V, W, X, Y, Z>(target: T, object1?: U, object2?: V, object3?: W, object4?: X, object5?: Y, object6?: Z): T & U & V & W & X & Y & Z;
};
export declare const assignDeep: AssignDeep;
/**
* Returns true if the given object is empty, false otherwise.
* @param obj The Object.
*/
export declare const isEmptyObject: (obj: any) => boolean;
export {};
+64
View File
@@ -0,0 +1,64 @@
import { isArray, isFunction, isPlainObject, isNull } from './types';
import { each } from './array';
/**
* Determines whether the passed object has a property with the passed name.
* @param obj The object.
* @param prop The name of the property.
*/
export const hasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param obj The object of which the properties shall be returned.
*/
export const keys = (obj) => (obj ? Object.keys(obj) : []);
// https://github.com/jquery/jquery/blob/master/src/core.js#L116
export const assignDeep = (target, object1, object2, object3, object4, object5, object6) => {
const sources = [object1, object2, object3, object4, object5, object6];
// Handle case when target is a string or something (possible in deep copy)
if ((typeof target !== 'object' || isNull(target)) && !isFunction(target)) {
target = {};
}
each(sources, (source) => {
// Extend the base object
each(keys(source), (key) => {
const copy = source[key];
// Prevent Object.prototype pollution
// Prevent never-ending loop
if (target === copy) {
return true;
}
const copyIsArray = isArray(copy);
// Recurse if we're merging plain objects or arrays
if (copy && (isPlainObject(copy) || copyIsArray)) {
const src = target[key];
let clone = src;
// Ensure proper type for the source value
if (copyIsArray && !isArray(src)) {
clone = [];
}
else if (!copyIsArray && !isPlainObject(src)) {
clone = {};
}
// Never move original objects, clone them
target[key] = assignDeep(clone, copy);
}
else {
target[key] = copy;
}
});
});
// Return the modified object
return target;
};
/**
* Returns true if the given object is empty, false otherwise.
* @param obj The Object.
*/
export const isEmptyObject = (obj) => {
/* eslint-disable no-restricted-syntax, guard-for-in */
for (const name in obj)
return false;
return true;
/* eslint-enable */
};
//# sourceMappingURL=object.js.map
@@ -0,0 +1 @@
{"version":3,"file":"object.js","sourceRoot":"","sources":["../../../src/support/utils/object.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACrE,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAQ,EAAE,IAA8B,EAAW,EAAE,CAClF,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAElD;;;GAGG;AACH,MAAM,CAA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AAM,IAAI,CAAC,WAAW,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,EAAE;oBAC9C,KAAK,GAAG,EAAE,CAAC;iBACZ;gBAED,0CAA0C;gBAC1C,MAAM,CAAC,GAAG,CAAC,GAAG,UAAU,CAAC,KAAK,EAAE,IAAI,CAAQ,CAAC;aAC9C;iBAAM;gBACL,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;aACpB;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,6BAA6B;IAC7B,OAAO,MAAa,CAAC;AACvB,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAAQ,EAAW,EAAE;IACjD,uDAAuD;IACvD,KAAK,MAAM,IAAI,IAAI,GAAG;QAAE,OAAO,KAAK,CAAC;IACrC,OAAO,IAAI,CAAC;IACZ,mBAAmB;AACrB,CAAC,CAAC"}
+31
View File
@@ -0,0 +1,31 @@
declare type PlainObject<T = any> = Record<string, T>;
export declare const isUndefined: (obj: any) => obj is undefined;
export declare const isNull: (obj: any) => obj is null;
export declare const type: (obj: any) => string;
export declare const isNumber: (obj: any) => obj is number;
export declare const isString: (obj: any) => obj is string;
export declare const isBoolean: (obj: any) => obj is boolean;
export declare const isFunction: (obj: any) => obj is (...args: any[]) => any;
export declare const isArray: <T = any>(obj: any) => obj is T[];
export declare const isObject: (obj: any) => boolean;
/**
* Returns true if the given object is array like, false otherwise.
* @param obj The Object
*/
export declare const isArrayLike: <T extends PlainObject<any> = any>(obj: any) => obj is ArrayLike<T>;
/**
* Returns true if the given object is a "plain" (e.g. { key: value }) object, false otherwise.
* @param obj The Object.
*/
export declare const isPlainObject: <T = any>(obj: any) => obj is PlainObject<T>;
/**
* Checks whether the given object is a HTMLElement.
* @param obj The object which shall be checked.
*/
export declare const isHTMLElement: (obj: any) => obj is HTMLElement;
/**
* Checks whether the given object is a Element.
* @param obj The object which shall be checked.
*/
export declare const isElement: (obj: any) => obj is Element;
export {};
+77
View File
@@ -0,0 +1,77 @@
const ElementNodeType = Node.ELEMENT_NODE;
const { toString, hasOwnProperty } = Object.prototype;
export const isUndefined = (obj) => obj === undefined;
export const isNull = (obj) => obj === null;
export const type = (obj) => isUndefined(obj) || isNull(obj)
? `${obj}`
: toString
.call(obj)
.replace(/^\[object (.+)\]$/, '$1')
.toLowerCase();
export const isNumber = (obj) => typeof obj === 'number';
export const isString = (obj) => typeof obj === 'string';
export const isBoolean = (obj) => typeof obj === 'boolean';
export const isFunction = (obj) => typeof obj === 'function';
export const isArray = (obj) => Array.isArray(obj);
export const isObject = (obj) => typeof obj === 'object' && !isArray(obj) && !isNull(obj);
/**
* Returns true if the given object is array like, false otherwise.
* @param obj The Object
*/
export const isArrayLike = (obj) => {
const length = !!obj && obj.length;
const lengthCorrectFormat = isNumber(length) && length > -1 && length % 1 == 0; // eslint-disable-line eqeqeq
return isArray(obj) || (!isFunction(obj) && lengthCorrectFormat)
? length > 0 && isObject(obj)
? length - 1 in obj
: true
: false;
};
/**
* Returns true if the given object is a "plain" (e.g. { key: value }) object, false otherwise.
* @param obj The Object.
*/
export const isPlainObject = (obj) => {
if (!obj || !isObject(obj) || type(obj) !== 'object')
return false;
let key;
const cstr = 'constructor';
const ctor = obj[cstr];
const ctorProto = ctor && ctor.prototype;
const hasOwnConstructor = hasOwnProperty.call(obj, cstr);
const hasIsPrototypeOf = ctorProto && hasOwnProperty.call(ctorProto, 'isPrototypeOf');
if (ctor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
/* eslint-disable no-restricted-syntax */
for (key in obj) {
/**/
}
/* eslint-enable */
return isUndefined(key) || hasOwnProperty.call(obj, key);
};
/**
* Checks whether the given object is a HTMLElement.
* @param obj The object which shall be checked.
*/
export const isHTMLElement = (obj) => {
const instanceofObj = HTMLElement;
return obj
? instanceofObj
? obj instanceof instanceofObj
: obj.nodeType === ElementNodeType
: false;
};
/**
* Checks whether the given object is a Element.
* @param obj The object which shall be checked.
*/
export const isElement = (obj) => {
const instanceofObj = Element;
return obj
? instanceofObj
? obj instanceof instanceofObj
: obj.nodeType === ElementNodeType
: false;
};
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/support/utils/types.ts"],"names":[],"mappings":"AAEA,MAAM,eAAe,GAAG,IAAI,CAAC,YAAY,CAAC;AAC1C,MAAM,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC;AAEtD,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,GAAQ,EAAoB,EAAE,CAAC,GAAG,KAAK,SAAS,CAAC;AAE7E,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,GAAQ,EAAe,EAAE,CAAC,GAAG,KAAK,IAAI,CAAC;AAE9D,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,GAAQ,EAAU,EAAE,CACvC,WAAW,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC;IAC7B,CAAC,CAAC,GAAG,GAAG,EAAE;IACV,CAAC,CAAC,QAAQ;SACL,IAAI,CAAC,GAAG,CAAC;SACT,OAAO,CAAC,mBAAmB,EAAE,IAAI,CAAC;SAClC,WAAW,EAAE,CAAC;AAEvB,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAQ,EAAiB,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC;AAE7E,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAQ,EAAiB,EAAE,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC;AAE7E,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,GAAQ,EAAkB,EAAE,CAAC,OAAO,GAAG,KAAK,SAAS,CAAC;AAEhF,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,GAAQ,EAAkC,EAAE,CAAC,OAAO,GAAG,KAAK,UAAU,CAAC;AAElG,MAAM,CAAC,MAAM,OAAO,GAAG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,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACzD,MAAM,gBAAgB,GAAG,SAAS,IAAI,cAAc,CAAC,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;IAEtF,IAAI,IAAI,IAAI,CAAC,iBAAiB,IAAI,CAAC,gBAAgB,EAAE;QACnD,OAAO,KAAK,CAAC;KACd;IAED,yCAAyC;IACzC,KAAK,GAAG,IAAI,GAAG,EAAE;QACf,IAAI;KACL;IACD,mBAAmB;IAEnB,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC3D,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,GAAQ,EAAsB,EAAE;IAC5D,MAAM,aAAa,GAAG,WAAW,CAAC;IAClC,OAAO,GAAG;QACR,CAAC,CAAC,aAAa;YACb,CAAC,CAAC,GAAG,YAAY,aAAa;YAC9B,CAAC,CAAC,GAAG,CAAC,QAAQ,KAAK,eAAe;QACpC,CAAC,CAAC,KAAK,CAAC;AACZ,CAAC,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,GAAQ,EAAkB,EAAE;IACpD,MAAM,aAAa,GAAG,OAAO,CAAC;IAC9B,OAAO,GAAG;QACR,CAAC,CAAC,aAAa;YACb,CAAC,CAAC,GAAG,YAAY,aAAa;YAC9B,CAAC,CAAC,GAAG,CAAC,QAAQ,KAAK,eAAe;QACpC,CAAC,CAAC,KAAK,CAAC;AACZ,CAAC,CAAC"}
+8
View File
@@ -0,0 +1,8 @@
{
"private": true,
"name": "browser-testing",
"version": "0.0.0",
"scripts": {
"postinstall": "tsc --project ./tsconfig.json"
}
}
+107
View File
@@ -0,0 +1,107 @@
// @ts-ignore
import {
createDiv,
appendChildren,
parent,
style,
on,
off,
addClass,
WH,
XY,
clientSize,
each,
} from './support';
type ResizeListener = (width: number, height: number) => void;
export const resize = (element: HTMLElement) => {
const resizeListeners: ResizeListener[] = [];
const strMouseTouchDownEvent = 'mousedown touchstart';
const strMouseTouchUpEvent = 'mouseup touchend';
const strMouseTouchMoveEvent = 'mousemove touchmove';
const strSelectStartEvent = 'selectstart';
const dragStartSize: WH<number> = { w: 0, h: 0 };
const dragStartPosition: XY<number> = { x: 0, y: 0 };
const resizeBtn = createDiv('resizeBtn');
appendChildren(element, resizeBtn);
addClass(element, 'resizer');
let dragResizeBtn: HTMLElement | undefined;
let dragResizer: HTMLElement | undefined;
const onSelectStart = (event: Event) => {
event.preventDefault();
return false;
};
const resizerResize = (event: MouseEvent | TouchEvent) => {
const isTouchEvent = (event as TouchEvent).touches !== undefined;
const mouseOffsetHolder = isTouchEvent
? (event as TouchEvent).touches[0]
: (event as MouseEvent);
const sizeStyle = {
width: dragStartSize.w + mouseOffsetHolder.pageX - dragStartPosition.x,
height: dragStartSize.h + mouseOffsetHolder.pageY - dragStartPosition.y,
};
style(dragResizer, sizeStyle);
each(resizeListeners, (listener: ResizeListener) => {
if (listener) {
listener(sizeStyle.width, sizeStyle.height);
}
});
event.stopPropagation();
};
const resizerResized = () => {
off(document, strSelectStartEvent, onSelectStart);
off(document, strMouseTouchMoveEvent, resizerResize);
off(document, strMouseTouchUpEvent, resizerResized);
dragResizer = undefined;
dragResizeBtn = undefined;
};
on(
resizeBtn,
strMouseTouchDownEvent,
(event: MouseEvent | TouchEvent) => {
const { currentTarget } = event;
const correctButton = (event as MouseEvent).buttons === 1 || event.which === 1;
const isTouchEvent = (event as TouchEvent).touches !== undefined;
const mouseOffsetHolder = isTouchEvent
? (event as TouchEvent).touches[0]
: (event as MouseEvent);
if (correctButton || isTouchEvent) {
dragStartPosition.x = mouseOffsetHolder.pageX;
dragStartPosition.y = mouseOffsetHolder.pageY;
dragResizeBtn = currentTarget as HTMLElement;
dragResizer = parent(currentTarget as HTMLElement) as HTMLElement;
const cSize = clientSize(element);
dragStartSize.w = cSize.w;
dragStartSize.h = cSize.h;
on(document, strSelectStartEvent, onSelectStart, { _passive: false });
on(document, strMouseTouchMoveEvent, resizerResize, { _passive: false });
on(document, strMouseTouchUpEvent, resizerResized, { _passive: false });
event.preventDefault();
event.stopPropagation();
}
},
{ _passive: false }
);
return {
addResizeListener(listener: ResizeListener) {
resizeListeners.push(listener);
},
};
};
+110
View File
@@ -0,0 +1,110 @@
function isEvent(obj: any): obj is Event {
return obj instanceof Event || !!obj.target;
}
// eslint-disable-next-line
const noop = <T>(): T => {
return {} as T;
};
const getSelectOptions = (selectElement: HTMLSelectElement) =>
Array.from(selectElement.options).map((option) => option.value);
export const generateSelectCallback =
(
targetElms: HTMLElement[] | HTMLElement | null,
callback: (
targetAffectedElm: HTMLElement,
possibleValues: string[],
selectedValue: string
) => any
) =>
(event: Event | HTMLSelectElement | null) => {
const target: HTMLSelectElement | null = isEvent(event)
? (event.target as HTMLSelectElement)
: event;
if (target) {
const selectedOption = target.value;
const selectOptions = getSelectOptions(target);
const elmsArr = Array.isArray(targetElms) ? targetElms : [targetElms];
elmsArr.forEach((elm) => {
if (elm) {
callback(elm, selectOptions, selectedOption);
}
});
}
};
export const generateClassChangeSelectCallback = (targetElms: HTMLElement[] | HTMLElement | null) =>
generateSelectCallback(targetElms, (targetAffectedElm, possibleValues, selectedValue) => {
possibleValues.forEach((clazz) => targetAffectedElm.classList.remove(clazz));
targetAffectedElm.classList.add(selectedValue);
});
export const selectOption = (
select: HTMLSelectElement | null,
selectedOption: string | number
): boolean => {
if (!select) {
return false;
}
const options = getSelectOptions(select);
const currValue = select.value;
if (selectedOption === currValue) {
return false;
}
if (typeof selectedOption === 'string' && options.includes(selectedOption)) {
select.value = selectedOption;
} else if (
typeof selectedOption === 'number' &&
options.length < selectedOption &&
selectedOption > -1
) {
select.selectedIndex = selectedOption;
}
let event;
if (typeof Event === 'function') {
event = new Event('change');
} else {
event = document.createEvent('Event');
event.initEvent('change', true, true);
}
select.dispatchEvent(event);
return true;
};
export const iterateSelect = async <T>(
select: HTMLSelectElement | null,
options?: {
filter?: (value: string, index: number, array: string[]) => boolean;
beforeEach?: () => T | Promise<T>;
check?: (input: T, selectedOptions: string) => void | Promise<void>;
afterEach?: () => void | Promise<void>;
}
) => {
if (select) {
const { beforeEach = noop, check = noop, afterEach = noop, filter } = options || {};
const selectOptions = getSelectOptions(select);
const selectOptionsReversed = getSelectOptions(select).reverse();
const iterateOptions = [...selectOptions, ...selectOptionsReversed].filter(
filter || (() => true)
);
for (let i = 0; i < iterateOptions.length; i++) {
const option = iterateOptions[i];
// eslint-disable-next-line
const beforeEachObj: T = await beforeEach();
if (selectOption(select, option)) {
// eslint-disable-next-line
await check(beforeEachObj, option);
// eslint-disable-next-line
await afterEach();
}
}
}
};
+33
View File
@@ -0,0 +1,33 @@
import { waitFor, waitForOptions } from '@testing-library/dom';
const getTestResultElm = () => document.getElementById('testResult');
export const setTestResult = (result: boolean | null) => {
const elm = getTestResultElm();
if (elm) {
if (typeof result === 'boolean') {
if (result) {
if (elm.getAttribute('class') === 'failed') {
return;
}
}
elm.setAttribute('class', result ? 'passed' : 'failed');
} else {
elm.removeAttribute('class');
}
}
};
export const testPassed = (): boolean => {
const elm = getTestResultElm();
return elm ? elm.getAttribute('class') === 'passed' : false;
};
export const waitForOrFailTest = <T>(callback: () => T | Promise<T>, options?: waitForOptions) =>
waitFor(callback, {
...options,
onTimeout(error: Error): Error {
setTestResult(false);
return error;
},
});
+1
View File
@@ -0,0 +1 @@
export const timeout = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+3
View File
@@ -0,0 +1,3 @@
export * from './Select';
export * from './TestResult';
export * from './Timeout';
@@ -0,0 +1,79 @@
import { isString } from '../utils/types';
import { each } from '../utils/array';
import { keys } from '../utils/object';
type ClassContainingElement = Node | Element | false | null | undefined;
type ClassName = string | false | null | undefined;
const rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
const classListAction = (
elm: ClassContainingElement,
className: ClassName,
action: (elmClassList: DOMTokenList, clazz: string) => boolean | void
): boolean => {
const classList = elm && (elm as Element).classList;
let clazz: string;
let i = 0;
let result = false;
if (classList && className && isString(className)) {
const classes: Array<string> = className.match(rnothtmlwhite) || [];
result = classes.length > 0;
while ((clazz = classes[i++])) {
result = !!action(classList, clazz) && result;
}
}
return result;
};
/**
* Check whether the given element has the given class name(s).
* @param elm The element.
* @param className The class name(s).
*/
export const hasClass = (elm: ClassContainingElement, className: ClassName): boolean =>
classListAction(elm, className, (classList, clazz) => classList.contains(clazz));
/**
* Removes the given class name(s) from the given element.
* @param elm The element.
* @param className The class name(s) which shall be removed. (separated by spaces)
*/
export const removeClass = (elm: ClassContainingElement, className: ClassName): void => {
classListAction(elm, className, (classList, clazz) => classList.remove(clazz));
};
/**
* Adds the given class name(s) to the given element.
* @param elm The element.
* @param className The class name(s) which shall be added. (separated by spaces)
* @returns A function which removes the added class name(s).
*/
export const addClass = (elm: ClassContainingElement, className: ClassName): (() => void) => {
classListAction(elm, className, (classList, clazz) => classList.add(clazz));
return removeClass.bind(0, elm, className);
};
/**
* Takes two className strings, compares them and returns the difference as array.
* @param classNameA ClassName A.
* @param classNameB ClassName B.
*/
export const diffClass = (classNameA: ClassName, classNameB: ClassName) => {
const classNameASplit = classNameA && classNameA.split(' ');
const classNameBSplit = classNameB && classNameB.split(' ');
const tempObj = {};
each(classNameASplit, (className) => {
tempObj[className] = 1;
});
each(classNameBSplit, (className) => {
if (tempObj[className]) {
delete tempObj[className];
} else {
tempObj[className] = 1;
}
});
return keys(tempObj);
};
@@ -0,0 +1,25 @@
import { each } from '../utils/array';
import { contents } from './traversal';
import { removeElements } from './manipulation';
/**
* Creates a div DOM node.
*/
export const createDiv = (classNames?: string): HTMLDivElement => {
const div = document.createElement('div');
if (classNames) {
div.setAttribute('class', classNames);
}
return div;
};
/**
* Creates DOM nodes modeled after the passed html string and returns the root dom nodes as a array.
* @param html The html string after which the DOM nodes shall be created.
*/
export const createDOM = (html: string): ReadonlyArray<Node> => {
const createdDiv = createDiv();
createdDiv.innerHTML = html.trim();
return each(contents(createdDiv), (elm) => removeElements(elm));
};
@@ -0,0 +1,68 @@
export interface WH<T = number> {
w: T;
h: T;
}
const elementHasDimensions = (elm: HTMLElement): boolean =>
!!(elm.offsetWidth || elm.offsetHeight || elm.getClientRects().length);
const zeroObj: WH = {
w: 0,
h: 0,
};
/**
* Returns the window inner- width and height.
*/
export const windowSize = (): WH => ({
w: window.innerWidth,
h: window.innerHeight,
});
/**
* Returns the scroll- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the scroll- width and height shall be returned.
*/
export const offsetSize = (elm: HTMLElement | null | undefined): WH =>
elm
? {
w: elm.offsetWidth,
h: elm.offsetHeight,
}
: zeroObj;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export const clientSize = (elm: HTMLElement | false | null | undefined): WH =>
elm
? {
w: elm.clientWidth,
h: elm.clientHeight,
}
: zeroObj;
/**
* Returns the client- width and height of the passed element. If the element is null the width and height values are 0.
* @param elm The element of which the client- width and height shall be returned.
*/
export const scrollSize = (elm: HTMLElement | false | null | undefined): WH =>
elm
? {
w: elm.scrollWidth,
h: elm.scrollHeight,
}
: zeroObj;
/**
* Returns the BoundingClientRect of the passed element.
* @param elm The element of which the BoundingClientRect shall be returned.
*/
export const getBoundingClientRect = (elm: HTMLElement): DOMRect => elm.getBoundingClientRect();
/**
* Determines whether the passed element has any dimensions.
* @param elm The element.
*/
export const hasDimensions = (elm: HTMLElement | false | null | undefined): boolean =>
elm ? elementHasDimensions(elm as HTMLElement) : false;
@@ -0,0 +1,110 @@
import { isUndefined } from '../utils/types';
import { each, push, runEachAndClear } from '../utils/array';
let passiveEventsSupport: boolean;
const supportPassiveEvents = (): boolean => {
if (isUndefined(passiveEventsSupport)) {
passiveEventsSupport = false;
try {
/* eslint-disable */
// @ts-ignore
window.addEventListener(
'test',
null,
Object.defineProperty({}, 'passive', {
get() {
passiveEventsSupport = true;
},
})
);
/* eslint-enable */
} catch (e) {}
}
return passiveEventsSupport;
};
const splitEventNames = (eventNames: string) => eventNames.split(' ');
export interface OnOptions {
_capture?: boolean;
_passive?: boolean;
_once?: boolean;
}
/**
* Removes the passed event listener for the passed events with the passed options.
* @param target The element from which the listener shall be removed.
* @param eventNames The eventsnames for which the listener shall be removed.
* @param listener The listener which shall be removed.
* @param capture The options of the removed listener.
*/
export const off = <T extends Event = Event>(
target: EventTarget,
eventNames: string,
listener: (event: T) => any,
capture?: boolean
): void => {
each(splitEventNames(eventNames), (eventName) => {
target.removeEventListener(eventName, listener as EventListener, capture);
});
};
/**
* Adds the passed event listener for the passed eventnames with the passed options.
* @param target The element to which the listener shall be added.
* @param eventNames The eventsnames for which the listener shall be called.
* @param listener The listener which is called on the eventnames.
* @param options The options of the added listener.
*/
export const on = <T extends Event = Event>(
target: EventTarget,
eventNames: string,
listener: (event: T) => any,
options?: OnOptions
): (() => void) => {
const doSupportPassiveEvents = supportPassiveEvents();
const passive = (doSupportPassiveEvents && options && options._passive) ?? doSupportPassiveEvents;
const capture = (options && options._capture) || false;
const once = (options && options._once) || false;
const offListeners: (() => void)[] = [];
const nativeOptions: AddEventListenerOptions | boolean = doSupportPassiveEvents
? {
passive,
capture,
}
: capture;
each(splitEventNames(eventNames), (eventName) => {
const finalListener = (
once
? (evt: T) => {
target.removeEventListener(eventName, finalListener, capture);
listener && listener(evt);
}
: listener
) as EventListener;
push(offListeners, off.bind(null, target, eventName, finalListener, capture));
target.addEventListener(eventName, finalListener, nativeOptions);
});
return runEachAndClear.bind(0, offListeners);
};
/**
* Shorthand for the stopPropagation event Method.
* @param evt The event of which the stopPropagation method shall be called.
*/
export const stopPropagation = (evt: Event): void => evt.stopPropagation();
/**
* Shorthand for the preventDefault event Method.
* @param evt The event of which the preventDefault method shall be called.
*/
export const preventDefault = (evt: Event): void => evt.preventDefault();
/**
* Shorthand for the stopPropagation and preventDefault event Method.
* @param evt The event of which the stopPropagation and preventDefault methods shall be called.
*/
export const stopAndPrevent = (evt: Event): void =>
(stopPropagation(evt) as undefined) || (preventDefault(evt) as undefined);
@@ -0,0 +1,8 @@
export * from './class';
export * from './create';
export * from './dimensions';
export * from './events';
export * from './style';
export * from './manipulation';
export * from './offset';
export * from './traversal';
@@ -0,0 +1,110 @@
import { isArrayLike } from '../utils/types';
import { each, from } from '../utils/array';
import { parent } from './traversal';
type NodeCollection = ArrayLike<Node> | Node | false | null | undefined;
/**
* Inserts Nodes before the given preferredAnchor element.
* @param parentElm The parent of the preferredAnchor element or the element which shall be the parent of the inserted Nodes.
* @param preferredAnchor The element before which the Nodes shall be inserted or null if the elements shall be appended at the end.
* @param insertedElms The Nodes which shall be inserted.
*/
const before = (
parentElm: Node | false | null | undefined,
preferredAnchor: Node | false | null | undefined,
insertedElms: NodeCollection
): void => {
if (insertedElms && parentElm) {
let anchor: Node | false | null | undefined = preferredAnchor;
let fragment: DocumentFragment | Node | null | undefined;
if (isArrayLike(insertedElms)) {
fragment = document.createDocumentFragment();
// append all insertedElms to the fragment and if one of these is the anchor, change the anchor
each(insertedElms, (insertedElm) => {
if (insertedElm === anchor) {
anchor = insertedElm.previousSibling;
}
fragment!.appendChild(insertedElm);
});
} else {
fragment = insertedElms;
}
// if the preferred anchor isn't null set it to a valid anchor
if (preferredAnchor) {
if (!anchor) {
anchor = parentElm.firstChild;
} else if (anchor !== preferredAnchor) {
anchor = anchor.nextSibling;
}
}
parentElm.insertBefore(fragment, anchor || null);
}
};
/**
* Appends the given children at the end of the given Node.
* @param node The Node to which the children shall be appended.
* @param children The Nodes which shall be appended.
*/
export const appendChildren = (
node: Node | false | null | undefined,
children: NodeCollection
): void => {
before(node, null, children);
};
/**
* Prepends the given children at the start of the given Node.
* @param node The Node to which the children shall be prepended.
* @param children The Nodes which shall be prepended.
*/
export const prependChildren = (
node: Node | false | null | undefined,
children: NodeCollection
): void => {
before(node, node && node.firstChild, children);
};
/**
* Inserts the given Nodes before the given Node.
* @param node The Node before which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export const insertBefore = (
node: Node | false | null | undefined,
insertedNodes: NodeCollection
): void => {
before(parent(node), node, insertedNodes);
};
/**
* Inserts the given Nodes after the given Node.
* @param node The Node after which the given Nodes shall be inserted.
* @param insertedNodes The Nodes which shall be inserted.
*/
export const insertAfter = (
node: Node | false | null | undefined,
insertedNodes: NodeCollection
): void => {
before(parent(node), node && node.nextSibling, insertedNodes);
};
/**
* Removes the given Nodes from their parent.
* @param nodes The Nodes which shall be removed.
*/
export const removeElements = (nodes: NodeCollection): void => {
if (isArrayLike(nodes)) {
each(from(nodes), (e) => removeElements(e));
} else if (nodes) {
const parentElm = parent(nodes);
if (parentElm) {
parentElm.removeChild(nodes);
}
}
};
@@ -0,0 +1,37 @@
import { getBoundingClientRect } from './dimensions';
export interface XY<T = number> {
x: T;
y: T;
}
const zeroObj: XY = {
x: 0,
y: 0,
};
/**
* Returns the offset- left and top coordinates of the passed element relative to the document. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export const absoluteCoordinates = (elm: HTMLElement | null | undefined): XY => {
const rect = elm ? getBoundingClientRect(elm) : 0;
return rect
? {
x: rect.left + window.pageYOffset,
y: rect.top + window.pageXOffset,
}
: zeroObj;
};
/**
* Returns the offset- left and top coordinates of the passed element. If the element is null the top and left values are 0.
* @param elm The element of which the offset- top and left coordinates shall be returned.
*/
export const offsetCoordinates = (elm: HTMLElement | null | undefined): XY =>
elm
? {
x: elm.offsetLeft,
y: elm.offsetTop,
}
: zeroObj;
@@ -0,0 +1,141 @@
import { each, keys } from '../utils';
import { isString, isNumber, isArray, isUndefined } from '../utils/types';
export interface TRBL {
t: number;
r: number;
b: number;
l: number;
}
type StyleObject<CustomCssProps = ''> = {
[Key in keyof CSSStyleDeclaration | (CustomCssProps extends string ? CustomCssProps : '')]?:
| string
| number;
};
const cssNumber = {
// animationiterationcount: 1,
// columncount: 1,
// fillopacity: 1,
// flexgrow: 1,
// flexshrink: 1,
// fontweight: 1,
// lineheight: 1,
// order: 1,
// orphans: 1,
// widows: 1,
// zoom: 1,
opacity: 1,
zindex: 1,
};
const parseToZeroOrNumber = (value: string, toFloat?: boolean): number => {
/* istanbul ignore next */
const num = toFloat ? parseFloat(value) : parseInt(value, 10);
// num === num means num is not NaN
/* istanbul ignore next */
return num === num ? num : 0; // eslint-disable-line no-self-compare
};
const adaptCSSVal = (prop: string, val: string | number): string | number =>
!cssNumber[prop.toLowerCase()] && isNumber(val) ? `${val}px` : val;
const getCSSVal = (elm: HTMLElement, computedStyle: CSSStyleDeclaration, prop: string): string =>
/* istanbul ignore next */
computedStyle != null
? computedStyle[prop] || computedStyle.getPropertyValue(prop)
: elm.style[prop];
const setCSSVal = (elm: HTMLElement, prop: string, val: string | number): void => {
try {
const { style: elmStyle } = elm;
if (!isUndefined(elmStyle[prop])) {
elmStyle[prop] = adaptCSSVal(prop, val);
} else {
elmStyle.setProperty(prop, val as string);
}
} catch (e) {}
};
/**
* Gets or sets the passed styles to the passed element.
* @param elm The element to which the styles shall be applied to / be read from.
* @param styles The styles which shall be set or read.
*/
export function style<CustomCssProps>(
elm: HTMLElement | false | null | undefined,
styles: StyleObject<CustomCssProps>
): void;
export function style<CustomCssProps>(
elm: HTMLElement | false | null | undefined,
styles: string
): string;
export function style<CustomCssProps>(
elm: HTMLElement | false | null | undefined,
styles: Array<string> | string
): { [key: string]: string };
export function style<CustomCssProps>(
elm: HTMLElement | false | null | undefined,
styles: StyleObject<CustomCssProps> | Array<string> | string
): { [key: string]: string } | string | void {
const getSingleStyle = isString(styles);
const getStyles = isArray(styles) || getSingleStyle;
if (getStyles) {
let getStylesResult: string | Record<string, any> = getSingleStyle ? '' : {};
if (elm) {
const computedStyle: CSSStyleDeclaration = window.getComputedStyle(elm, null);
getStylesResult = getSingleStyle
? getCSSVal(elm, computedStyle, styles as string)
: (styles as Array<string>).reduce((result, key) => {
result[key] = getCSSVal(elm, computedStyle, key as string);
return result;
}, getStylesResult);
}
return getStylesResult;
}
elm && each(keys(styles), (key) => setCSSVal(elm, key, styles[key]));
}
/**
* Hides the passed element (display: none).
* @param elm The element which shall be hidden.
*/
export const hide = (elm: HTMLElement | false | null | undefined): void => {
style(elm, { display: 'none' });
};
/**
* Shows the passed element (display: block).
* @param elm The element which shall be shown.
*/
export const show = (elm: HTMLElement | false | null | undefined): void => {
style(elm, { display: 'block' });
};
/**
* Returns the top right bottom left values of the passed css property.
* @param elm The element of which the values shall be returned.
* @param propertyPrefix The css property prefix. (e.g. "border")
* @param propertySuffix The css property suffix. (e.g. "width")
*/
export const topRightBottomLeft = (
elm?: HTMLElement | false | null | undefined,
propertyPrefix?: string,
propertySuffix?: string
): TRBL => {
const finalPrefix = propertyPrefix ? `${propertyPrefix}-` : '';
const finalSuffix = propertySuffix ? `-${propertySuffix}` : '';
const top = `${finalPrefix}top${finalSuffix}`;
const right = `${finalPrefix}right${finalSuffix}`;
const bottom = `${finalPrefix}bottom${finalSuffix}`;
const left = `${finalPrefix}left${finalSuffix}`;
const result = style(elm, [top, right, bottom, left]);
return {
t: parseToZeroOrNumber(result[top]),
r: parseToZeroOrNumber(result[right]),
b: parseToZeroOrNumber(result[bottom]),
l: parseToZeroOrNumber(result[left]),
};
};
@@ -0,0 +1,120 @@
import { isElement } from '../utils/types';
import { push, from } from '../utils/array';
type InputElementType = Node | Element | Node | false | null | undefined;
type OutputElementType = Node | Element | null;
const elmPrototype = Element.prototype;
/**
* Find all elements with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
const find = (selector: string, elm?: InputElementType): Element[] => {
const arr: Array<Element> = [];
const rootElm = elm ? (isElement(elm) ? elm : null) : document;
return rootElm ? push(arr, rootElm.querySelectorAll(selector)) : arr;
};
/**
* Find the first element with the passed selector, outgoing (and including) the passed element or the document if no element was provided.
* @param selector The selector which has to be searched by.
* @param elm The element from which the search shall be outgoing.
*/
const findFirst = (selector: string, elm?: InputElementType): OutputElementType => {
const rootElm = elm ? (isElement(elm) ? elm : null) : document;
return rootElm ? rootElm.querySelector(selector) : null;
};
/**
* Determines whether the passed element is matching with the passed selector.
* @param elm The element which has to be compared with the passed selector.
* @param selector The selector which has to be compared with the passed element. Additional selectors: ':visible' and ':hidden'.
*/
const is = (elm: InputElementType, selector: string): boolean => {
if (isElement(elm)) {
/* istanbul ignore next */
// eslint-disable-next-line
// @ts-ignore
const fn: (...args: any) => boolean = elmPrototype.matches || elmPrototype.msMatchesSelector;
return fn.call(elm, selector);
}
return false;
};
/**
* Returns the children (no text-nodes or comments) of the passed element which are matching the passed selector. An empty array is returned if the passed element is null.
* @param elm The element of which the children shall be returned.
* @param selector The selector which must match with the children elements.
*/
const children = (elm: InputElementType, selector?: string): ReadonlyArray<Element> => {
const childs: Array<Element> = [];
return isElement(elm)
? push(
childs,
from(elm.children).filter((child) => (selector ? is(child, selector) : child))
)
: childs;
};
/**
* Returns the childNodes (incl. text-nodes or comments etc.) of the passed element. An empty array is returned if the passed element is null.
* @param elm The element of which the childNodes shall be returned.
*/
const contents = (elm: InputElementType): ReadonlyArray<ChildNode> =>
elm ? from(elm.childNodes) : [];
/**
* Returns the parent element of the passed element, or null if the passed element is null.
* @param elm The element of which the parent element shall be returned.
*/
const parent = (elm: InputElementType): OutputElementType => (elm ? elm.parentElement : null);
const closest = (elm: InputElementType, selector: string): OutputElementType => {
if (isElement(elm)) {
const closestFn = elmPrototype.closest;
if (closestFn) {
return closestFn.call(elm, selector);
}
do {
if (is(elm, selector)) {
return elm as Element;
}
elm = parent(elm);
} while (elm);
}
return null;
};
/**
* Determines whether the given element lies between two selectors in the DOM.
* @param elm The element.
* @param highBoundarySelector The high boundary selector.
* @param deepBoundarySelector The deep boundary selector.
*/
const liesBetween = (
elm: InputElementType,
highBoundarySelector: string,
deepBoundarySelector: string
): boolean => {
const closestHighBoundaryElm = elm && closest(elm, highBoundarySelector);
const closestDeepBoundaryElm = elm && findFirst(deepBoundarySelector, closestHighBoundaryElm);
const deepBoundaryIsValid =
closest(closestDeepBoundaryElm, highBoundarySelector) === closestHighBoundaryElm;
return closestHighBoundaryElm && closestDeepBoundaryElm
? closestHighBoundaryElm === elm ||
closestDeepBoundaryElm === elm ||
(deepBoundaryIsValid &&
closest(closest(elm, deepBoundarySelector), highBoundarySelector) !==
closestHighBoundaryElm)
: false;
};
export { find, findFirst, is, children, contents, parent, liesBetween, closest };
@@ -0,0 +1,2 @@
export * from './dom';
export * from './utils';
@@ -0,0 +1,118 @@
import { isArrayLike, isString } from './types';
type PlainObject = Record<string, any>;
type RunEachItem = ((...args: any) => any | any[]) | null | undefined;
/**
* Iterates through a array or object
* @param arrayLikeOrObject The array or object through which shall be iterated.
* @param callback The function which is responsible for the iteration.
* If the function returns true its treated like a "continue" statement.
* If the function returns false its treated like a "break" statement.
*/
export function each<T>(
array: Array<T> | ReadonlyArray<T>,
callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | unknown
): Array<T> | ReadonlyArray<T>;
export function each<T>(
array: Array<T> | ReadonlyArray<T> | false | null | undefined,
callback: (value: T, indexOrKey: number, source: Array<T>) => boolean | unknown
): Array<T> | ReadonlyArray<T> | false | null | undefined;
export function each<T>(
arrayLikeObject: ArrayLike<T>,
callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | unknown
): ArrayLike<T>;
export function each<T>(
arrayLikeObject: ArrayLike<T> | false | null | undefined,
callback: (value: T, indexOrKey: number, source: ArrayLike<T>) => boolean | unknown
): ArrayLike<T> | false | null | undefined;
export function each(
obj: PlainObject,
callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | unknown
): PlainObject;
export function each(
obj: PlainObject | false | null | undefined,
callback: (value: any, indexOrKey: string, source: PlainObject) => boolean | unknown
): PlainObject | false | null | undefined;
export function each<T>(
source: Array<T> | ArrayLike<T> | ReadonlyArray<T> | PlainObject | false | null | undefined,
callback: (value: T, indexOrKey: any, source: any) => boolean | unknown
): Array<T> | ArrayLike<T> | ReadonlyArray<T> | PlainObject | false | null | undefined {
if (isArrayLike(source)) {
for (let i = 0; i < source.length; i++) {
if (callback(source[i], i, source) === false) {
break;
}
}
} else if (source) {
each(Object.keys(source), (key) => callback(source[key], key, source));
}
return source;
}
/**
* Returns the index of the given inside the given array or -1 if the given item isn't part of the given array.
* @param arr The array.
* @param item The item.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
*/
export const indexOf = <T = any>(arr: T[], item: T, fromIndex?: number): number =>
arr.indexOf(item, fromIndex);
/**
* Pushesh all given items into the given array and returns it.
* @param array The array the items shall be pushed into.
* @param items The items which shall be pushed into the array.
*/
export const push = <T>(array: T[], items: T | ArrayLike<T>, arrayIsSingleItem?: boolean): T[] => {
!arrayIsSingleItem && !isString(items) && isArrayLike(items)
? Array.prototype.push.apply(array, items as T[])
: array.push(items as T);
return array;
};
/**
* Creates a shallow-copied Array instance from an array-like or iterable object.
* @param arr The object from which the array instance shall be created.
*/
export const from = <T = any>(arr?: ArrayLike<T> | Set<T>) => {
const original = Array.from;
const result: T[] = [];
if (original && arr) {
return original(arr);
}
if (arr instanceof Set) {
arr.forEach((value) => {
push(result, value);
});
} else {
each(arr, (elm) => {
push(result, elm);
});
}
return result;
};
/**
* Check whether the passed array is empty.
* @param array The array which shall be checked.
*/
export const isEmptyArray = (array: any[] | null | undefined): boolean =>
!!array && array.length === 0;
/**
* Calls all functions in the passed array/set of functions.
* @param arr The array filled with function which shall be called.
* @param args The args with which each function is called.
* @param keep True when the Set / array should not be cleared afterwards, false otherwise.
*/
export const runEachAndClear = (arr: RunEachItem[], args?: any[], keep?: boolean): void => {
// eslint-disable-next-line prefer-spread
const runFn = (fn: RunEachItem) => fn && fn.apply(undefined, args || []);
each(arr, runFn);
!keep && ((arr as any[]).length = 0);
};
@@ -0,0 +1,3 @@
export * from './array';
export * from './object';
export * from './types';
@@ -0,0 +1,103 @@
import { isArray, isFunction, isPlainObject, isNull } from './types';
import { each } from './array';
/**
* Determines whether the passed object has a property with the passed name.
* @param obj The object.
* @param prop The name of the property.
*/
export const hasOwnProperty = (obj: any, prop: string | number | symbol): boolean =>
Object.prototype.hasOwnProperty.call(obj, prop);
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param obj The object of which the properties shall be returned.
*/
export const keys = (obj: any): Array<string> => (obj ? Object.keys(obj) : []);
type AssignDeep = {
<T, U>(target: T, object1: U): T & U;
<T, U, V>(target: T, object1: U, object2: V): T & U & V;
<T, U, V, W>(target: T, object1: U, object2: V, object3: W): T & U & V & W;
<T, U, V, W, X>(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X;
<T, U, V, W, X, Y>(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T &
U &
V &
W &
X &
Y;
<T, U, V, W, X, Y, Z>(
target: T,
object1?: U,
object2?: V,
object3?: W,
object4?: X,
object5?: Y,
object6?: Z
): T & U & V & W & X & Y & Z;
};
// https://github.com/jquery/jquery/blob/master/src/core.js#L116
export const assignDeep: AssignDeep = <T, U, V, W, X, Y, Z>(
target: T,
object1?: U,
object2?: V,
object3?: W,
object4?: X,
object5?: Y,
object6?: Z
): T & U & V & W & X & Y & Z => {
const sources: Array<any> = [object1, object2, object3, object4, object5, object6];
// Handle case when target is a string or something (possible in deep copy)
if ((typeof target !== 'object' || isNull(target)) && !isFunction(target)) {
target = {} as T;
}
each(sources, (source) => {
// Extend the base object
each(keys(source), (key) => {
const copy: any = source[key];
// Prevent Object.prototype pollution
// Prevent never-ending loop
if (target === copy) {
return true;
}
const copyIsArray = isArray(copy);
// Recurse if we're merging plain objects or arrays
if (copy && (isPlainObject(copy) || copyIsArray)) {
const src = target[key];
let clone: any = src;
// Ensure proper type for the source value
if (copyIsArray && !isArray(src)) {
clone = [];
} else if (!copyIsArray && !isPlainObject(src)) {
clone = {};
}
// Never move original objects, clone them
target[key] = assignDeep(clone, copy) as any;
} else {
target[key] = copy;
}
});
});
// Return the modified object
return target as any;
};
/**
* Returns true if the given object is empty, false otherwise.
* @param obj The Object.
*/
export const isEmptyObject = (obj: any): boolean => {
/* eslint-disable no-restricted-syntax, guard-for-in */
for (const name in obj) return false;
return true;
/* eslint-enable */
};
@@ -0,0 +1,97 @@
type PlainObject<T = any> = Record<string, T>;
const ElementNodeType = Node.ELEMENT_NODE;
const { toString, hasOwnProperty } = Object.prototype;
export const isUndefined = (obj: any): obj is undefined => obj === undefined;
export const isNull = (obj: any): obj is null => obj === null;
export const type = (obj: any): string =>
isUndefined(obj) || isNull(obj)
? `${obj}`
: toString
.call(obj)
.replace(/^\[object (.+)\]$/, '$1')
.toLowerCase();
export const isNumber = (obj: any): obj is number => typeof obj === 'number';
export const isString = (obj: any): obj is string => typeof obj === 'string';
export const isBoolean = (obj: any): obj is boolean => typeof obj === 'boolean';
export const isFunction = (obj: any): obj is (...args: any[]) => any => typeof obj === 'function';
export const isArray = <T = any>(obj: any): obj is Array<T> => Array.isArray(obj);
export const isObject = (obj: any): boolean =>
typeof obj === 'object' && !isArray(obj) && !isNull(obj);
/**
* Returns true if the given object is array like, false otherwise.
* @param obj The Object
*/
export const isArrayLike = <T extends PlainObject = any>(obj: any): obj is ArrayLike<T> => {
const length = !!obj && obj.length;
const lengthCorrectFormat = isNumber(length) && length > -1 && length % 1 == 0; // eslint-disable-line eqeqeq
return isArray(obj) || (!isFunction(obj) && lengthCorrectFormat)
? length > 0 && isObject(obj)
? length - 1 in obj
: true
: false;
};
/**
* Returns true if the given object is a "plain" (e.g. { key: value }) object, false otherwise.
* @param obj The Object.
*/
export const isPlainObject = <T = any>(obj: any): obj is PlainObject<T> => {
if (!obj || !isObject(obj) || type(obj) !== 'object') return false;
let key;
const cstr = 'constructor';
const ctor = obj[cstr];
const ctorProto = ctor && ctor.prototype;
const hasOwnConstructor = hasOwnProperty.call(obj, cstr);
const hasIsPrototypeOf = ctorProto && hasOwnProperty.call(ctorProto, 'isPrototypeOf');
if (ctor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
/* eslint-disable no-restricted-syntax */
for (key in obj) {
/**/
}
/* eslint-enable */
return isUndefined(key) || hasOwnProperty.call(obj, key);
};
/**
* Checks whether the given object is a HTMLElement.
* @param obj The object which shall be checked.
*/
export const isHTMLElement = (obj: any): obj is HTMLElement => {
const instanceofObj = HTMLElement;
return obj
? instanceofObj
? obj instanceof instanceofObj
: obj.nodeType === ElementNodeType
: false;
};
/**
* Checks whether the given object is a Element.
* @param obj The object which shall be checked.
*/
export const isElement = (obj: any): obj is Element => {
const instanceofObj = Element;
return obj
? instanceofObj
? obj instanceof instanceofObj
: obj.nodeType === ElementNodeType
: false;
};
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "@local/tsconfig",
"compilerOptions": {
"outDir": "./dist/",
"baseUrl": "./src/",
"paths": {
"@/overlayscrollbars*": ["../../../packages/overlayscrollbars/src*"]
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"private": true,
"name": "@local/config",
"exports": {
"./resolve": "./src/resolve.json",
"./playwright": "./src/playwright.js",
"./jest": "./src/jest.js",
"./babel": "./src/babel.js"
},
"version": "0.0.0"
}
@@ -1,5 +1,5 @@
const path = require('path');
const resolve = require('./resolve.config');
const resolve = require('./resolve');
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
@@ -12,6 +12,6 @@ module.exports = {
moduleFileExtensions: resolve.extensions.map((ext) => ext.replace(/\./, '')),
testPathIgnorePatterns: ['\\\\node_modules\\\\'],
displayName: 'jest',
setupFilesAfterEnv: [path.resolve(__dirname, './config/jest/jest.setup.js')],
setupFilesAfterEnv: [path.resolve(__dirname, './jest.setup.js')],
testMatch: ['**/tests/jest/**/*.test.[jt]s?(x)'],
};
+4
View File
@@ -0,0 +1,4 @@
declare module '@local/playwright-tooling' {
export function playwrightRollup(): void;
export function expectSuccess(page: any): void;
}
+7
View File
@@ -0,0 +1,7 @@
{
"private": true,
"name": "@local/playwright-tooling",
"main": "./src/index.js",
"types": "index.d.ts",
"version": "0.0.0"
}
@@ -6,7 +6,6 @@ const v8toIstanbul = require('v8-to-istanbul');
const tmpCoveragePath = './.coverage/.nycPlaywright';
const reportDir = './.coverage/playwright';
module.exports = {
collectCoverage: async (coverageOutputDir, sourceDir, coverage, testfile) => {
// eslint-disable-next-line no-restricted-syntax
@@ -37,7 +36,7 @@ module.exports = {
}
});
execSync(`nyc report --reporter=lcov --reporter=text --report-dir=${reportDir} --temp-dir=${tmpCoveragePath}`, {stdio:'inherit' });
execSync(`nyc report --reporter=lcov --reporter=text --reporter=clover --reporter=json --report-dir=${reportDir} --temp-dir=${tmpCoveragePath}`, {stdio:'inherit' });
fs.rmSync(tmpCoveragePath, { recursive: true });
}
}
@@ -0,0 +1,8 @@
const { expect } = require('@playwright/test');
const resultSelector = '#testResult';
module.exports = async (page) => {
await page.locator(resultSelector).waitFor({ state: 'visible', timeout: 10 * 60 * 1000 }); // 10mins
await expect(page.locator(resultSelector)).toHaveClass('passed', { timeout: 500 });
}
+7
View File
@@ -0,0 +1,7 @@
const playwrightRollup = require('./playwrightRollup');
const expectSuccess = require('./expectSuccess');
module.exports = {
playwrightRollup,
expectSuccess,
};
@@ -0,0 +1,82 @@
const { dirname } = require('path');
const { rollup, watch: rollupWatch } = require('rollup');
const { test } = require('@playwright/test');
const createPlaywrightRollupConfig = require('@local/rollup/playwright');
const { collectCoverage } = require('./coverage');
const createRollupBundle = async (testDir, watch = false) => {
let server;
const onListening = (srv) => {
server = srv;
};
const config = await createPlaywrightRollupConfig(testDir, 'dev', onListening);
if (watch) {
const watcher = rollupWatch(config);
let outputPath = '';
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
watcher.on('event', ({ code, error, result, output }) => {
if (code === 'ERROR') {
console.log('Error:', error); // eslint-disable-line
}
if (code === 'BUNDLE_END') {
outputPath = output[0];
if (result && result.close) {
result.close();
}
}
if (code === 'END') {
/*
console.log('Watching for changes, press ENTER to continue.'); // eslint-disable-line
console.log(''); // eslint-disable-line
*/
resolve();
}
});
});
const { address, port } = server.address();
return {
url: `${address}:${port}`,
output: outputPath,
close: () => {
server.close();
watcher.close();
},
};
}
const bundle = await rollup(config);
await bundle.write(config.output);
};
module.exports = () => {
const originalCwd = process.cwd();
let url;
let close;
let output;
// eslint-disable-next-line no-empty-pattern
test.beforeAll(async ({}, { file }) => {
({ close, url, output } = await createRollupBundle(dirname(file), true));
});
test.beforeEach(async ({ page, browserName }) => {
await page.goto(url);
if (browserName === 'chromium') {
await page.coverage.startJSCoverage();
}
});
test.afterEach(async ({ page, browserName }, { file }) => {
if (browserName === 'chromium') {
const coverage = await page.coverage.stopJSCoverage();
await collectCoverage(originalCwd, dirname(output), coverage, file);
}
});
test.afterAll(() => {
close();
});
};
+9
View File
@@ -0,0 +1,9 @@
{
"private": true,
"name": "@local/rollup",
"exports": {
".": "./src/createRollupConfig.js",
"./playwright": "./src/playwright/createPlaywrightRollupConfig.js"
},
"version": "0.0.0"
}
@@ -1,14 +1,16 @@
/* eslint-disable no-console */
/* eslint-disable import/no-dynamic-require */
const { execSync } = require("child_process");
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const resolve = require('../../resolve.config.json');
const pkg = require('../../package.json');
const resolve = require('@local/config/resolve');
const defaultOptions = require('./defaultOptions');
const pipelineBuild = require('./pipeline.build');
const pipelineDev = require('./pipeline.dev');
const repoRoot = path.resolve(__dirname, '../../');
const workspaceRoot = path.dirname(execSync('npm root').toString());
const pkg = require(`${workspaceRoot}/package.json`);
const appendExtension = (file) =>
path.extname(file) === ''
@@ -29,13 +31,14 @@ const resolvePath = (basePath, pathToResolve, appendExt) => {
const getWorkspaceAliases = () =>
pkg.workspaces
.map((pattern) => glob.sync(pattern, { cwd: repoRoot }))
.map((pattern) => glob.sync(pattern, { cwd: workspaceRoot }))
.flat()
.reduce((obj, resolvedPath) => {
let projTsConfig;
const absolutePath = path.resolve(repoRoot, resolvedPath);
const absolutePath = path.resolve(workspaceRoot, resolvedPath);
try {
projTsConfig = require(`${path.resolve(repoRoot, resolvedPath)}/tsconfig.json`);
// eslint-disable-next-line import/no-dynamic-require, global-require
projTsConfig = require(`${path.resolve(workspaceRoot, resolvedPath)}/tsconfig.json`);
} catch {}
obj[`@/${path.basename(absolutePath)}`] = `${normalizePath(
@@ -69,7 +72,7 @@ const mergeAndResolveOptions = (userOptions) => {
const mergedOptions = {
project: project || path.basename(projectPath),
mode: rawMode || defaultMode,
repoRoot,
repoRoot: workspaceRoot,
extractStyle: rawExtractStyle ?? defaultExtractStyle,
paths: {
...defaultPaths,
@@ -120,13 +123,13 @@ const createConfig = (userOptions = {}) => {
console.log('PROJECT : ', project);
console.log('OPTIONS : ', options);
const umd = pipelineBuild(false, options, { declarationFiles: true, outputStyle: true });
const esm = buildModuleVersion ? pipelineBuild(true, options) : null;
const umd = pipelineBuild(resolve, false, options, { declarationFiles: true, outputStyle: true });
const esm = buildModuleVersion ? pipelineBuild(resolve, true, options) : null;
return [umd, esm].filter((build) => !!build);
}
return [pipelineDev(options)];
return [pipelineDev(resolve, options)];
};
module.exports = createConfig;
@@ -12,7 +12,6 @@ const {
rollupAlias,
rollupScss,
} = require('./pipeline.common.plugins');
const { extensions } = require('../../resolve.config.json');
const createOutputWithMinifiedVersion = (output, esm, buildMinifiedVersion) =>
[output].concat(
@@ -40,7 +39,7 @@ const createOutputWithMinifiedVersion = (output, esm, buildMinifiedVersion) =>
: []
);
module.exports = (esm, options, { declarationFiles = false, outputStyle = false } = {}) => {
module.exports = (resolve, esm, options, { declarationFiles = false, outputStyle = false } = {}) => {
const { rollup, paths, versions, alias, extractStyle } = options;
const { output: rollupOutput, input, plugins = [], ...rollupOptions } = rollup;
const { name, file, globals, exports, sourcemap: rawSourcemap, ...outputConfig } = rollupOutput;
@@ -94,8 +93,8 @@ module.exports = (esm, options, { declarationFiles = false, outputStyle = false
include: ['*.ts+(|x)', '**/*.ts+(|x)'],
exclude: ['node_modules', '**/node_modules/*'],
}),
rollupResolve(srcPath),
rollupCommonjs(sourcemap),
rollupResolve(srcPath, resolve),
rollupCommonjs(sourcemap, resolve),
rollupBabelInputPlugin({
...(esm ? babelConfigEsm : babelConfigUmd),
assumptions: {
@@ -122,7 +121,7 @@ module.exports = (esm, options, { declarationFiles = false, outputStyle = false
caller: {
name: 'babel-rollup-build',
},
extensions,
extensions: resolve.extensions,
}),
...plugins,
].filter(Boolean),
@@ -5,24 +5,23 @@ const rollupPluginScss = require('rollup-plugin-scss');
const rollupPluginIgnoreImport = require('rollup-plugin-ignore-import');
const rollupPluginCommonjs = require('@rollup/plugin-commonjs');
const rollupPluginAlias = require('@rollup/plugin-alias');
const { extensions, directories } = require('../../resolve.config.json');
module.exports = {
rollupAlias: (aliasEntries) =>
rollupPluginAlias({
entries: aliasEntries,
}),
rollupCommonjs: (sourcemap) =>
rollupCommonjs: (sourcemap, resolve) =>
rollupPluginCommonjs({
sourceMap: sourcemap,
extensions,
extensions: resolve.extensions,
}),
rollupResolve: (srcPath) =>
rollupResolve: (srcPath, resolve) =>
rollupPluginResolve({
mainFields: ['browser', 'umd:main', 'module', 'main'],
rootDir: srcPath,
moduleDirectories: directories,
extensions,
moduleDirectories: resolve.directories,
extensions: resolve.extensions,
}),
rollupScss: (extractStyleOption, output) => {
if (extractStyleOption) {
@@ -7,7 +7,7 @@ const {
rollupScss,
} = require('./pipeline.common.plugins');
module.exports = (options) => {
module.exports = (resolve, options) => {
const { rollup, paths, alias, extractStyle } = options;
const { output: rollupOutput, input, plugins = [], ...rollupOptions } = rollup;
const { file, sourcemap: rawSourcemap, ...outputConfig } = rollupOutput;
@@ -35,8 +35,8 @@ module.exports = (options) => {
target: 'es6',
tsconfig: './tsconfig.json',
}),
rollupResolve(srcPath),
rollupCommonjs(sourcemap),
rollupResolve(srcPath, resolve),
rollupCommonjs(sourcemap, resolve),
...plugins,
].filter(Boolean),
};
@@ -4,8 +4,8 @@ const rollupPluginStyles = require('rollup-plugin-styles');
const rollupPluginServe = require('rollup-plugin-serve');
// const rollupPluginLivereload = require('rollup-plugin-livereload');
const createRollupConfig = require('../rollup/rollup.config');
const rollupPluginHtml = require('./rollup.pluginHtml');
const createRollupConfig = require('../createRollupConfig');
// const rollupAdditionalWatchFiles = require('./rollup.pluginAdditionalWatchFiles');
const portRange = {
@@ -19,7 +19,7 @@ const meta = {
input: './index.browser',
};
module.exports = (testDir, onListening = null) => {
module.exports = (testDir, mode = 'dev', onListening = null) => {
const name = path.basename(testDir);
const htmlFilePath = path.resolve(testDir, meta.html);
const dist = path.resolve(testDir, meta.dist);
@@ -29,7 +29,7 @@ module.exports = (testDir, onListening = null) => {
return createRollupConfig({
project: name,
mode: 'dev',
mode,
paths: {
dist,
src: path.resolve(testDir, './'),

Some files were not shown because too many files have changed in this diff Show More