UNPKG

2.7 kBPlain TextView Raw
1import { vnode, VNode, VNodeData } from "./vnode";
2import * as is from "./is";
3
4export type VNodes = VNode[];
5export type VNodeChildElement =
6 | VNode
7 | string
8 | number
9 | String
10 | Number
11 | undefined
12 | null;
13export type ArrayOrElement<T> = T | T[];
14export type VNodeChildren = ArrayOrElement<VNodeChildElement>;
15
16export function addNS(
17 data: any,
18 children: Array<VNode | string> | undefined,
19 sel: string | undefined
20): void {
21 data.ns = "http://www.w3.org/2000/svg";
22 if (sel !== "foreignObject" && children !== undefined) {
23 for (let i = 0; i < children.length; ++i) {
24 const child = children[i];
25 if (typeof child === "string") continue;
26 const childData = child.data;
27 if (childData !== undefined) {
28 addNS(childData, child.children as VNodes, child.sel);
29 }
30 }
31 }
32}
33
34export function h(sel: string): VNode;
35export function h(sel: string, data: VNodeData | null): VNode;
36export function h(sel: string, children: VNodeChildren): VNode;
37export function h(
38 sel: string,
39 data: VNodeData | null,
40 children: VNodeChildren
41): VNode;
42export function h(sel: any, b?: any, c?: any): VNode {
43 let data: VNodeData = {};
44 let children: any;
45 let text: any;
46 let i: number;
47 if (c !== undefined) {
48 if (b !== null) {
49 data = b;
50 }
51 if (is.array(c)) {
52 children = c;
53 } else if (is.primitive(c)) {
54 text = c.toString();
55 } else if (c && c.sel) {
56 children = [c];
57 }
58 } else if (b !== undefined && b !== null) {
59 if (is.array(b)) {
60 children = b;
61 } else if (is.primitive(b)) {
62 text = b.toString();
63 } else if (b && b.sel) {
64 children = [b];
65 } else {
66 data = b;
67 }
68 }
69 if (children !== undefined) {
70 for (i = 0; i < children.length; ++i) {
71 if (is.primitive(children[i]))
72 children[i] = vnode(
73 undefined,
74 undefined,
75 undefined,
76 children[i],
77 undefined
78 );
79 }
80 }
81 if (
82 sel[0] === "s" &&
83 sel[1] === "v" &&
84 sel[2] === "g" &&
85 (sel.length === 3 || sel[3] === "." || sel[3] === "#")
86 ) {
87 addNS(data, children, sel);
88 }
89 return vnode(sel, data, children, text, undefined);
90}
91
92/**
93 * @experimental
94 */
95export function fragment(children: VNodeChildren): VNode {
96 let c: any;
97 let text: any;
98
99 if (is.array(children)) {
100 c = children;
101 } else if (is.primitive(c)) {
102 text = children;
103 } else if (c && c.sel) {
104 c = [children];
105 }
106
107 if (c !== undefined) {
108 for (let i = 0; i < c.length; ++i) {
109 if (is.primitive(c[i]))
110 c[i] = vnode(undefined, undefined, undefined, c[i], undefined);
111 }
112 }
113
114 return vnode(undefined, {}, c, text, undefined);
115}