From 7b1cb4e58347758cab25b73dc6486f5f90efa6df Mon Sep 17 00:00:00 2001 From: metamuffin Date: Tue, 1 Aug 2023 17:25:45 +0200 Subject: refactor dom interaction with helper function --- frontend/helper.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 frontend/helper.ts (limited to 'frontend/helper.ts') diff --git a/frontend/helper.ts b/frontend/helper.ts new file mode 100644 index 0000000..f47d131 --- /dev/null +++ b/frontend/helper.ts @@ -0,0 +1,30 @@ + + +interface Opts { + class?: string[] | string, + id?: string, + src?: string, + for?: string, + onclick?: (e: E) => void, + onchange?: (e: E) => void, +} + +function apply_opts(e: E, o: Opts) { + if (o.id) e.id = o.id + if (o.onclick) e.onclick = () => o.onclick!(e) + if (o.onchange) e.onchange = () => o.onchange!(e) + if (o.for) (e as unknown as HTMLLabelElement).htmlFor = o.for + if (typeof o?.class == "string") e.classList.add(o.class) + if (typeof o?.class == "object") e.classList.add(...o.class) +} + +export function e(name: K, opts: Opts, ...children: (HTMLElement | string)[]): HTMLElementTagNameMap[K] { + const el = document.createElement(name) + apply_opts(el, opts) + for (const c of children) { + if (typeof c == "string") el.textContent += c; + else el.append(c) + } + return el +} + -- cgit v1.2.3-70-g09d2