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