UNPKG

1.23 kBJavaScriptView Raw
1import { createVNode, createTextVNode } from './vnode'
2import { ELEMENT_NODE } from './utils'
3
4/**
5 * Creates a virtual node representing a node or text node to be created.
6 * @typedef {import('./vnode').VNode} VNode
7 * @param {string | Function} type
8 * @param {Object.<string, any>} props
9 * @return {VNode}
10 */
11export function h(type, props, ...children) {
12 let node
13 const tempBox = []
14 const childNodes = []
15 let length = children.length
16 props = props || {}
17 const key = props.key
18
19 while (length-- > 0) tempBox.push(children[length])
20
21 if (props.children != null) {
22 if (tempBox.length <= 0) {
23 tempBox.push(props.children)
24 }
25 delete props.children
26 }
27
28 while (tempBox.length > 0) {
29 if (Array.isArray((node = tempBox.pop()))) {
30 for (length = node.length; length-- > 0; ) {
31 tempBox.push(node[length])
32 }
33 } else if (node === false || node === true || node == null) {
34 } else {
35 childNodes.push(typeof node === 'object' ? node : createTextVNode(node))
36 }
37 }
38 delete props.key
39
40 if (typeof type === 'function') {
41 return type(props, (props.children = childNodes))
42 } else {
43 return createVNode(type, props, childNodes, null, key, ELEMENT_NODE)
44 }
45}