diff options
| author | Josh Kingsley <josh@joshkingsley.me> | 2025-10-29 18:26:41 +0200 |
|---|---|---|
| committer | Josh Kingsley <josh@joshkingsley.me> | 2025-10-29 18:26:41 +0200 |
| commit | 7ef8366bfc43775bf26e71e77bddf31af829dfde (patch) | |
| tree | 38f2551d3676838df5e35c97e5678f89fd75a56f /web/src/html.ts | |
| parent | 986e65f9ab7122995ae1d647df23d817cecf6816 (diff) | |
refactor(web): add decorators
Diffstat (limited to 'web/src/html.ts')
| -rw-r--r-- | web/src/html.ts | 44 |
1 files changed, 28 insertions, 16 deletions
diff --git a/web/src/html.ts b/web/src/html.ts index 8802e50..a118849 100644 --- a/web/src/html.ts +++ b/web/src/html.ts @@ -1,3 +1,29 @@ +export function createElement<T extends HTMLElement>( + tag: string, + ...children: (Node | string)[] +): T; + +export function createElement<T extends HTMLElement>( + tag: string, + attrs: Partial<T>, + ...children: (Node | string)[] +): T; + +export function createElement(tag: string, ...args: any[]) { + const el = document.createElement(tag); + + if (args[0]?.constructor === Object) { + const { dataset, style, ...attrs } = args.shift(); + Object.assign(el, attrs); + if (dataset) Object.assign(el.dataset, dataset); + if (style) Object.assign(el.style, style); + } + + el.append(...args.flat()); + + return el; +} + export type CreateElement<T extends HTMLElement> = { (...children: (Node | string)[]): T; (attrs: Partial<T>, ...children: (Node | string)[]): T; @@ -9,23 +35,9 @@ type ElementCreator = { const h = new Proxy({} as ElementCreator, { get: - (_, tag: string) => + (_, tagName: string) => (...args: any[]) => { - const el = document.createElement(tag); - - if (args[0]?.constructor === Object) { - const { dataset, ...attrs } = args.shift(); - - Object.assign(el, attrs); - - if (dataset) { - Object.assign(el.dataset, dataset); - } - } - - el.append(...args.flat()); - - return el; + return createElement(tagName, ...args); }, }); |
