type Tags = keyof HTMLElementTagNameMap;
type SVGTags = keyof SVGElementTagNameMap;
type MathTags = keyof MathMLElementTagNameMap;
type NodeUpdate = Partial | ((node: T) => Partial | null);
type QueryAllResult = (
updates?: NodeUpdate,
) => NodeListOf;
export function queryAll(
selectors: K,
root?: HTMLElement | ShadowRoot,
): QueryAllResult;
export function queryAll(
selectors: K,
root?: HTMLElement | ShadowRoot,
): QueryAllResult;
export function queryAll(
selectors: K,
root?: HTMLElement | ShadowRoot,
): QueryAllResult;
export function queryAll(
selectors: string,
root?: HTMLElement | ShadowRoot,
): QueryAllResult;
export function queryAll(
query: K,
root?: HTMLElement | ShadowRoot,
): QueryAllResult {
let res: NodeListOf | null = null;
return function (
this: HTMLElementTagNameMap[K],
update?: NodeUpdate,
) {
if (res) {
return patchNodes(res, update);
}
if (root) {
res = root.querySelectorAll(query);
} else if (this.shadowRoot) {
res = this.shadowRoot.querySelectorAll(query);
} else {
res = this.querySelectorAll(query);
}
if (!res) {
throw new Error(`could not find ${query}`);
}
return patchNodes(res, update);
};
}
function patchNodes(
target: NodeListOf,
update?: NodeUpdate,
): NodeListOf {
if (!update) {
return target;
}
for (const node of target) {
const patch = typeof update === "function" ? update(node) : update;
if (patch) {
for (const update in patch) {
const newValue = patch[update];
const oldValue = node[update];
if (newValue !== oldValue) {
Reflect.set(node, update, newValue);
}
}
}
}
return target;
}