allow stuff like style to be easily specified using the old fashioned way

This commit is contained in:
Hamcha 2024-10-12 23:29:48 +02:00
parent de82c0f0a5
commit f03c6475bc
Signed by: hamcha
GPG key ID: 1669C533B8CF6D89

View file

@ -2,11 +2,13 @@
// Licensed under AGPL-3.0, check `LICENSE` for the full text. // Licensed under AGPL-3.0, check `LICENSE` for the full text.
type ElementProperties<T extends keyof HTMLElementTagNameMap> = { type ElementProperties<T extends keyof HTMLElementTagNameMap> = {
[key in keyof HTMLElementTagNameMap[T]]: HTMLElementTagNameMap[T][key]; [key in keyof HTMLElementTagNameMap[T]]:
| HTMLElementTagNameMap[T][key]
| string;
} & { } & {
[key in keyof HTMLElementEventMap as `@${key}`]: ( [key in keyof HTMLElementEventMap as `@${key}`]: (
this: HTMLElement, this: HTMLElement,
ev: HTMLElementEventMap[key] ev: HTMLElementEventMap[key],
) => void; ) => void;
}; };
@ -45,15 +47,24 @@ export function $el<T extends keyof HTMLElementTagNameMap>(
const attributes = desc[0]; const attributes = desc[0];
if (typeof attributes === "object" && !(attributes instanceof Node)) { if (typeof attributes === "object" && !(attributes instanceof Node)) {
for (const attr in attributes) { for (const attr in attributes) {
const value = (attributes as Record<string, any>)[attr]; const value = (attributes as Record<string, unknown>)[attr];
if (attr.startsWith("@")) { if (attr.startsWith("@")) {
el.addEventListener(attr.substring(1), value); el.addEventListener(
attr.substring(1),
value as EventListenerOrEventListenerObject,
);
} else if (attr === "dataset") { } else if (attr === "dataset") {
for (const key in value) { for (const key in value as Record<string, unknown>) {
el.dataset[key] = value[key]; el.dataset[key] = (value as Record<string, string>)[key];
} }
} else { } else {
el[attr as keyof HTMLElementTagNameMap[T]] = value; // For some tricky attributes, set them the old fashioned way using strings
if (typeof value === "string") {
el.setAttribute(attr, value as string);
} else {
el[attr as keyof HTMLElementTagNameMap[T]] =
value as HTMLElementTagNameMap[T][keyof HTMLElementTagNameMap[T]];
}
} }
} }
desc.shift(); desc.shift();