-
Notifications
You must be signed in to change notification settings - Fork 0
/
tag.ts
74 lines (63 loc) · 1.71 KB
/
tag.ts
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import "./types.ts";
import { eventName, isEventName } from "./event.ts";
export function tag(
tag: string | ((props: JSX.ElementProps) => JSX.Element),
attributes: JSX.IntrinsicElements | null,
...children: JSX.Node[] | JSX.Node[][]
): JSX.Element {
const { ...props }: JSX.ElementProps = attributes || {};
const eventRefs: JSX.EventRef[] = [];
for (const prop in props) {
if (isEventName(prop)) {
eventRefs.push({
name: eventName(prop),
listener: <() => void> props[prop],
});
delete props[prop];
}
}
return {
tag,
props,
eventRefs,
children: collectTextNodes(flatten(children)),
};
}
function flatten(children: JSX.Node[] | JSX.Node[][]): JSX.Node[] {
const flatten: JSX.Node[] = [];
for (const child of children) {
if (Array.isArray(child)) {
flatten.push(...child);
} else {
flatten.push(child);
}
}
return flatten;
}
function collectTextNodes(nodes?: JSX.Node[]): JSX.Node[] {
return nodes
//Remove all undefined child nodes.
?.filter((node) => typeof node !== "undefined")
.filter(
(node, index, source) => {
if (typeof node === "undefined" || node === null) return false;
if (
typeof (<JSX.Element> node).tag === "string" ||
typeof (<JSX.Element> node).tag === "function"
) {
return true;
}
if (typeof source[index + 1] === "undefined") {
return true;
}
if (
typeof source[index + 1] !== "string" &&
typeof source[index + 1] !== "number"
) {
return true;
}
source[index + 1] = `${node}${source[index + 1]}`;
return false;
},
) || [];
}