UNPKG

1.26 kBJavaScriptView Raw
1import { VNode } from './vnode';
2import options from './options';
3
4
5const stack = [];
6
7
8/** JSX/hyperscript reviver
9* Benchmarks: https://esbench.com/bench/57ee8f8e330ab09900a1a1a0
10 * @see http://jasonformat.com/wtf-is-jsx
11 * @public
12 * @example
13 * /** @jsx h *\/
14 * import { render, h } from 'preact';
15 * render(<span>foo</span>, document.body);
16 */
17export function h(nodeName, attributes) {
18 let children = [],
19 lastSimple, child, simple, i;
20 for (i=arguments.length; i-- > 2; ) {
21 stack.push(arguments[i]);
22 }
23 if (attributes && attributes.children) {
24 if (!stack.length) stack.push(attributes.children);
25 delete attributes.children;
26 }
27 while (stack.length) {
28 if ((child = stack.pop()) instanceof Array) {
29 for (i=child.length; i--; ) stack.push(child[i]);
30 }
31 else if (child!=null && child!==false) {
32 if (typeof child=='number' || child===true) child = String(child);
33 simple = typeof child=='string';
34 if (simple && lastSimple) {
35 children[children.length-1] += child;
36 }
37 else {
38 children.push(child);
39 lastSimple = simple;
40 }
41 }
42 }
43
44 let p = new VNode(nodeName, attributes || undefined, children);
45
46 // if a "vnode hook" is defined, pass every created VNode to it
47 if (options.vnode) options.vnode(p);
48
49 return p;
50}