-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsx.ts
193 lines (166 loc) · 5.57 KB
/
jsx.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/// <reference no-default-lib="true" />
/// <reference lib="DOM" />
/// <reference lib="ES2021" />
/// <reference path="./jsx.defs.ts" />
import { kebabize } from './util.ts'
// create
type ArrayComponent<T> = (props: T) => JSX.ArrayElement
type StatelessComponent<T> = (props: T) => JSX.StatelessElement
type StatefulComponent<T> = (props: T) => JSX.StatefulElement
type FutureComponent<T> = (props: T) => JSX.FutureElement
type SyntheticComponent<T> =
StatelessComponent<T>
| StatefulComponent<T>
| FutureComponent<T>
| ArrayComponent<T>
type IntrinsicComponent = keyof JSX.IntrinsicElements
export type Component<T> = IntrinsicComponent | SyntheticComponent<T>
export const createElement = <T extends Record<string, unknown> = Record<string, unknown>>(component: Component<T>, props: T, ...children: JSX.Element[]): JSX.Element => {
const isIntrinsicComponent = (component: Component<T>): component is IntrinsicComponent =>
typeof component === "string";
if (isIntrinsicComponent(component)) return {
name: component,
props,
children: children.length === 1 ? children[0] : children
};
if (Array.isArray(component)) // this appears to be the case if rendering <State/> ¯\_(ツ)_/¯
return component.map(subcomponent => createElement(subcomponent, props, ...children))
return component({ children, ...props }) // TODO: why this cast is required?
}
export const h = createElement
// render
function createSlot(value: JSX.Element): Slot {
if (value === null) return absentSlot
if (Array.isArray(value)) return createArraySlot(value)
if (typeof value === "object") {
if ("name" in value) return createStatelessSlot(value)
if ("next" in value) return createStatefulSlot(value)
if ("then" in value) return createFutureSlot(value)
} else if (typeof value === "string"
|| typeof value === "boolean"
|| typeof value === "number")
return createTextSlot(value)
throw new Error(`unknown element: type="${typeof value}", data="${value}"`)
}
type Renderer = (update: Node[]) => void
interface Slot {
mount(render: Renderer): void
unmount(): void
}
const absentSlot: Slot = {
mount(render) { render([]) },
unmount() { }
}
function createTextSlot(source: JSX.TextElement): Slot {
return {
mount(render) {
render([document.createTextNode(`${source}`)])
},
unmount() { }
}
}
function createStatelessSlot(source: JSX.NodeElement): Slot {
let children: Slot | undefined
return {
mount(render) {
const element = document.createElement(source.name)
function update(replacement: Node[]) {
element.replaceChildren(...replacement)
}
if (source.children) {
children = createSlot(source.children)
children.mount(update)
}
type StyleObject = Record<string, string | number | boolean>
function transformStyle(input: StyleObject) {
return Object.keys(input)
.map(key => `${kebabize(key)}: ${input[key]}`)
.join('; ')
}
if (source.props) Object.keys(source.props)
.map(name => [name, source.props[name]] as [string, unknown])
.forEach(([name, value]) => {
if (typeof value === "function" && name === "socket")
(value as JSX.Socket<EventTarget>)(element)
else if (Array.isArray(value) && name === "class")
element.setAttribute("class", value.join(' '))
else if (typeof value === "object" && value && name === "style")
element.setAttribute("style", transformStyle(value as StyleObject))
else if (typeof value === "function" && name.match(/on[A-Z].*/))
element.addEventListener(name.substring(2).toLowerCase(), value as EventListenerOrEventListenerObject)
else
element.setAttribute(name.toLowerCase(), `${value}`)
})
render([element]);
},
unmount() { children?.unmount() }
}
}
function createArraySlot(source: JSX.ArrayElement): Slot {
const allNodes: Node[][] = []
const slots: Slot[] = []
return {
mount(render) {
const updateSlot = (index: number, nodes: Node[]) => {
allNodes[index] = nodes
// TODO: can send more detailed info to render for efficiency
render(allNodes.flat())
}
source.map(createSlot)
.map((slot, index) => {
slots[index] = slot
slot.mount(nodes => updateSlot(index, nodes))
})
},
unmount() {
slots.forEach(slot => slot.unmount())
}
}
}
function createFutureSlot(source: JSX.FutureElement): Slot {
let live = true
let slot: Slot | undefined
return {
mount(update) {
source.then(element => {
if (live) {
slot = createSlot(element)
slot.mount(update)
}
})
},
unmount() {
live = false;
slot?.unmount()
}
}
}
function createStatefulSlot(source: JSX.StatefulElement): Slot {
let live = true
let slot: Slot = absentSlot
return {
mount(render) {
(async () => {
let result: IteratorResult<JSX.Element | void>
do {
result = await source.next(live)
slot.unmount()
if (result.value !== undefined)
slot = createSlot(result.value)
else
slot = absentSlot
slot.mount(render)
} while (live && !result.done)
if (!result.done) await source.next(false)
})()
},
unmount() {
live = false;
slot?.unmount()
}
}
}
export function render(parent: Element, ...element: JSX.Element[]) {
const update = (children: Node[]) => parent.replaceChildren(...children)
createSlot(element).mount(update)
}