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

export type Children = Child[]

export function h(tagName: string, attrs: object, ...children: Children): Element {
  let elem = document.createElement(tagName)
  elem = Object.assign(elem, attrs)
  appendChildren(elem, ...children)
  return elem
}

export function s(tagName: string, attrs: object, ...children: Children): Element {
  let elem = document.createElementNS('http://www.w3.org/2000/svg', tagName)
  Object.entries(attrs).forEach(([key, value]) => elem.setAttribute(key, value))
  appendChildren(elem, ...children)
  return elem
}

function appendChildren(elem: Element, ...children: Children) {
  for (const child of children) {
    if (typeof child === 'number')
      elem.append(child.toString())
    else
      elem.append(child)
  }
}

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