-
Notifications
You must be signed in to change notification settings - Fork 2
/
yet-another-js-framework.tsx
289 lines (250 loc) · 6.96 KB
/
yet-another-js-framework.tsx
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Yet another JS framework.
const call = (fn: () => void) => fn()
const callAll = (set: Set<() => void>) => set.forEach(call)
let currentEffect: (() => void) | undefined
export function effect(fn: () => void) {
const parentEffect = currentEffect
currentEffect = fn
try {
fn()
} finally {
currentEffect = parentEffect
}
}
export function untrack<T>(fn: () => T): T {
const parentEffect = currentEffect
currentEffect = undefined
try {
return fn()
} finally {
currentEffect = parentEffect
}
}
let currentBatch: Set<Set<() => void>> | undefined
export function event(): readonly [track: () => void, trigger: () => void] {
const tracking = new Set<() => void>()
return [
() => {
if (currentEffect) {
tracking.add(currentEffect)
}
},
() => {
if (currentBatch) {
currentBatch.add(tracking)
} else {
callAll(tracking)
}
},
]
}
export function batch(fn: () => void) {
const parentBatch = currentBatch
currentBatch = new Set()
fn()
currentBatch.forEach(callAll)
currentBatch.clear()
currentBatch = parentBatch
}
export function instant(fn: () => void) {
const parentBatch = currentBatch
currentBatch = undefined
fn()
currentBatch = parentBatch
}
export function signal<T>(
value: T,
): readonly [get: () => T, set: (value: T) => void] {
const [track, trigger] = event()
return [
() => {
track()
return value
},
(newValue) => {
value = newValue
trigger()
},
]
}
export function memo<T>(fn: () => T): () => T {
const [get, set] = signal<T>(null!)
effect(() => set(fn()))
return get
}
export function text(value: () => unknown): Text {
const node = document.createTextNode("")
effect(() => (node.data = String(value())))
return node
}
export type Renderable =
| string
| number
| bigint
| boolean
| ChildNode
| readonly Renderable[]
| (() => Renderable)
| null
| undefined
const remove = (node: ChildNode) => node.remove()
export function fragment(parent: {
append(node: ChildNode): void
}): (...nodes: readonly Renderable[]) => void {
const anchor = document.createComment("")
const children: ChildNode[] = []
parent.append(anchor)
return (...nodes) => {
children.forEach(remove)
children.length = 0
nodes.forEach((node) => {
render(node, {
append: (node) => (anchor.after(node), children.push(node)),
})
})
}
}
export function render(
node: Renderable,
parent: { append(node: ChildNode): void },
) {
if (node instanceof Node) {
parent.append(node)
} else if (typeof node == "function") {
const render = fragment(parent)
effect(() => render(node()))
} else if (Array.isArray<true>(node)) {
for (const child of node) {
render(child, parent)
}
} else if (node != null) {
parent.append(document.createTextNode(String(node)))
}
}
export function attr(element: Element, key: string, value: unknown) {
if (key in element) {
if (typeof value == "function") {
effect(() => {
;(element as any)[key] = value()
})
} else {
;(element as any)[key] = value
}
} else {
if (typeof value == "function") {
effect(() => {
element.setAttribute(key, String(value()))
})
} else {
element.setAttribute(key, String(value))
}
}
}
// https://stackoverflow.com/questions/52443276/how-to-exclude-getter-only-properties-from-type-in-typescript
type IfEquals<X, Y, A, B> = (<T>() => T extends X ? 1 : 2) extends <
T,
>() => T extends Y ? 1 : 2
? A
: B
type OmitFunctionsAndConstantsAndEventsAndReadonly<T> = {
[K in keyof T as T[K] extends (...args: readonly any[]) => any
? never
: K extends Uppercase<K & string>
? never
: K extends `on${string}`
? never
: IfEquals<{ [L in K]: T[L] }, { -readonly [L in K]: T[L] }, K, never>]:
| T[K]
| (() => T[K])
}
type EventMapToProps<T> = {
[K in keyof T & string as `on:${K}`]: (event: T[K]) => void
}
type MaybeEventMap<Source, Requirement, EventMap> = Source extends Requirement
? EventMapToProps<Omit<EventMap, keyof HTMLElementEventMap>>
: {}
type HTMLProps<T> = OmitFunctionsAndConstantsAndEventsAndReadonly<T> & {
children?: Renderable
use?: (el: T) => void
[x: `class:${string}`]: boolean | (() => boolean)
[x: `on:${string}`]: (event: Event) => void
[x: `style:${string}`]: string | number | (() => string | number)
} & EventMapToProps<HTMLElementEventMap> &
MaybeEventMap<T, HTMLBodyElement, HTMLBodyElementEventMap> &
MaybeEventMap<T, HTMLMediaElement, HTMLMediaElementEventMap> &
MaybeEventMap<T, HTMLVideoElement, HTMLVideoElementEventMap> &
MaybeEventMap<T, HTMLFrameSetElement, HTMLFrameSetElementEventMap>
export function h<K extends keyof HTMLElementTagNameMap>(
tag: K,
props?: Partial<HTMLProps<HTMLElementTagNameMap[K]>>,
...children: readonly Renderable[]
): HTMLElementTagNameMap[K]
export function h(
tag: (props: Record<string, unknown>) => Element,
props: Record<string, unknown>,
...children: readonly Renderable[]
): Element
export function h(
tag: string | ((props: Record<string, unknown>) => Element),
props: Record<string, unknown> = {},
...children: readonly Renderable[]
): Element {
props ??= {}
if (typeof tag == "function") {
let fnChildren: unknown = children
if ("children" in props) {
fnChildren = props.children
} else if (children.length == 0) {
fnChildren = undefined
} else if (children.length == 1) {
fnChildren = children[0]
}
return tag({ ...props, children: fnChildren })
} else {
const element = document.createElement(tag)
if ("children" in props) {
if (props.children == null) {
children = []
} else if (!Array.isArray(props.children)) {
children = [props.children as Renderable]
} else {
children = props.children
}
}
for (const key in props) {
if (key == "use") {
;(props.use as any)(element)
} else if (key.startsWith("class:")) {
const value = props[key]
if (typeof value == "function") {
effect(() => {
element.classList.toggle(key.slice(6), !!value())
})
} else {
element.classList.toggle(key.slice(6), !!value)
}
} else if (key.startsWith("on:")) {
element.addEventListener(key.slice(3), props[key] as any)
} else if (key.startsWith("style:")) {
const value = props[key]
if (typeof value == "function") {
effect(() => {
element.style[key.slice(6) as any] = value()
})
} else {
element.style[key.slice(6) as any] = value as any
}
} else if (!key.includes(":") && key != "children") {
attr(element, key, props[key])
}
}
render(children, element)
return element
}
}
declare global {
interface ArrayConstructor {
isArray<T extends true>(arg: any): arg is readonly any[]
isArray<T extends false>(arg: any): arg is any[]
}
}