aboutsummaryrefslogtreecommitdiff
path: root/frontend/helper.ts
blob: 6e7ca5c3be8afeb67389101254d1fffea2221eef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
interface Opts<E> {
    class?: string[] | string,
    id?: string,
    src?: string,
    for?: string,
    type?: string,
    href?: string,
    onclick?: (e: E) => void,
    onchange?: (e: E) => void,
}

function apply_opts<E extends HTMLElement>(e: E, o: Opts<E>) {
    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 (o.type && e instanceof HTMLInputElement) e.type = o.type
    if (o.href && e instanceof HTMLAnchorElement) e.href = o.href
    if (typeof o?.class == "string") e.classList.add(o.class)
    if (typeof o?.class == "object") e.classList.add(...o.class)
}

export function e<K extends keyof HTMLElementTagNameMap>(name: K, opts: Opts<HTMLElementTagNameMap[K]>, ...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
}