UNPKG

1.29 kBJavaScriptView Raw
1/**
2 * @description Hyperscript function. Enables definition of HTML/SVG using functions.
3 * @param {string} type - The name of the HTML or SVG tag to create.
4 * @param {object} props - And object of property/value pairs.
5 * @param {string|number|boolean|any[]} args - Any child elements.
6 * @returns {object} A virtual node describing an element.
7 * @example Virtual node with string as content:
8 * const title = h('h1', {class: 'main-title'}, 'This is the Titel!')
9 * @example Virtual node with children:
10 * const list = h(
11 * 'ul',
12 * {class: 'list'},
13 * [
14 * h('li', {}, 'One'),
15 * h('li', {}, 'Two'),
16 * h('li', {}, 'Three')
17 * ]
18 * )
19 */
20export function h(type, props, ...children) {
21 const nodes = []
22 const childNodes = []
23 let length = children.length
24
25 while (length-- > 0) nodes.push(children[length])
26
27 while (nodes.length) {
28 const node = nodes.pop()
29 if (node && node.pop) {
30 for (length = node.length; length--; ) {
31 nodes.push(node[length])
32 }
33 } else if (node != null && node !== true && node !== false) {
34 childNodes.push(node)
35 }
36 }
37
38 if (typeof type === 'function') {
39 return type(props || {}, childNodes)
40 } else {
41 return {
42 type,
43 props: props || {},
44 children: childNodes
45 }
46 }
47}