| 1 |
/** Find an element by selector. */ |
| 2 |
export const query = (selector: string, context: Document | Element = document) => { |
| 3 |
return context.querySelector<HTMLElement>(selector); |
| 4 |
}; |
| 5 |
|
| 6 |
/** Find a set of elements by selector. */ |
| 7 |
export const queryAll = ( |
| 8 |
selector: string, |
| 9 |
context: Document | Element = document |
| 10 |
): HTMLElement[] => { |
| 11 |
return Array.from(context.querySelectorAll(selector)); |
| 12 |
}; |
| 13 |
|
| 14 |
/** Return a Promise that resolves after the next event loop. */ |
| 15 |
export const nextTick = (): Promise<void> => { |
| 16 |
return new Promise((resolve) => { |
| 17 |
requestAnimationFrame(() => { |
| 18 |
requestAnimationFrame(() => { |
| 19 |
resolve(); |
| 20 |
}); |
| 21 |
}); |
| 22 |
}); |
| 23 |
}; |
| 24 |
|
| 25 |
/** Check if an object is a Promise or a Thenable */ |
| 26 |
export function isPromise<T>(obj: unknown): obj is PromiseLike<T> { |
| 27 |
return ( |
| 28 |
!!obj && |
| 29 |
(typeof obj === 'object' || typeof obj === 'function') && |
| 30 |
typeof (obj as Record<string, unknown>).then === 'function' |
| 31 |
); |
| 32 |
} |
| 33 |
|
| 34 |
/** Call a function as a Promise. Resolves with the returned Promsise or immediately. */ |
| 35 |
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any |
| 36 |
export function runAsPromise(func: Function, args: unknown[] = []): Promise<unknown> { |
| 37 |
return new Promise((resolve, reject) => { |
| 38 |
const result: unknown = func(...args); |
| 39 |
if (isPromise(result)) { |
| 40 |
result.then(resolve, reject); |
| 41 |
} else { |
| 42 |
resolve(result); |
| 43 |
} |
| 44 |
}); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Force a layout reflow, e.g. after adding classnames |
| 49 |
* @see https://stackoverflow.com/a/21665117/3759615 |
| 50 |
*/ |
| 51 |
export function forceReflow(element?: HTMLElement): void { |
| 52 |
element = element || document.body; |
| 53 |
element?.getBoundingClientRect(); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Read data attribute from closest element with that attribute. |
| 58 |
* |
| 59 |
* Returns `undefined` if no element is found or attribute is missing. |
| 60 |
* Returns `true` if attribute is present without a value. |
| 61 |
*/ |
| 62 |
export function getContextualAttr( |
| 63 |
el: Element | undefined, |
| 64 |
attr: string |
| 65 |
): string | boolean | undefined { |
| 66 |
const target = el?.closest(`[${attr}]`); |
| 67 |
return target?.hasAttribute(attr) ? target?.getAttribute(attr) || true : undefined; |
| 68 |
} |