aboutsummaryrefslogtreecommitdiff
path: root/src/lib/h.ts
blob: 1e49f2f74b270de60b85065ffac5f6b080e35546 (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
35
36
37
38
39
40
41
type Child = Element | Text | string | number

export type Children = Child[]

export function h(
  tagName: string,
  attrs: object,
  ...children: Children
): 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)
    // if (Array.isArray(child))
    //   elem.append(...child)
    // else
    //   elem.append(child)
  }

  return elem
}

export function concatClassName(attrs: any, className: string): object {
  const existingClassName = 'className' in attrs ? attrs['className'] : undefined
  return { ...attrs, className: `${className} ${existingClassName}` }
}