aboutsummaryrefslogtreecommitdiff
path: root/src/lib/h.ts
blob: 8b1abf33daf75f613e61e0c5a93f46bdfbd15f6e (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
type Child = Element | Text | string | number

export default function h(
  tagName: string,
  attrs: object,
  ...children: Child[]
): Element {
  const isSvg = tagName === 'svg' || tagName === 'path'

  let elem = isSvg
    ? document.createElementNS('http://www.w3.org/2000/svg', tagName)
    : document.createElement(tagName)

  if (isSvg) {
    Object.entries(attrs).forEach(([key, value]) => {
      elem.setAttribute(key, value)
    })
  } else {
    elem = Object.assign(elem, attrs)
  }

  for (const child of children) {
    if (typeof child === 'number')
      elem.append(child.toString())
    else
      elem.append(child)
  }

  return elem
}

export function classNames(obj: {[key: string]: boolean }): string {
  return Object.keys(obj).filter(k => obj[k]).join(' ')
}