-
Notifications
You must be signed in to change notification settings - Fork 19
/
mini-react.ts
472 lines (410 loc) · 11.5 KB
/
mini-react.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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// TODO Optimization Type Description
interface ComponentFunction {
new (props: Record<string, unknown>): Component;
(props: Record<string, unknown>): VirtualElement | string;
}
type VirtualElementType = ComponentFunction | string;
interface VirtualElementProps {
children?: VirtualElement[];
[propName: string]: unknown;
}
interface VirtualElement {
type: VirtualElementType;
props: VirtualElementProps;
}
type FiberNodeDOM = Element | Text | null | undefined;
interface FiberNode<S = any> extends VirtualElement {
alternate: FiberNode<S> | null;
dom?: FiberNodeDOM;
effectTag?: string;
child?: FiberNode;
return?: FiberNode;
sibling?: FiberNode;
hooks?: {
state: S;
queue: S[];
}[];
}
let wipRoot: FiberNode | null = null;
let nextUnitOfWork: FiberNode | null = null;
let currentRoot: FiberNode | null = null;
let deletions: FiberNode[] = [];
let wipFiber: FiberNode;
let hookIndex = 0;
// Support React.Fragment syntax.
const Fragment = Symbol.for('react.fragment');
// Enhanced requestIdleCallback.
((global: Window) => {
const id = 1;
const fps = 1e3 / 60;
let frameDeadline: number;
let pendingCallback: IdleRequestCallback;
const channel = new MessageChannel();
const timeRemaining = () => frameDeadline - window.performance.now();
const deadline = {
didTimeout: false,
timeRemaining,
};
channel.port2.onmessage = () => {
if (typeof pendingCallback === 'function') {
pendingCallback(deadline);
}
};
global.requestIdleCallback = (callback: IdleRequestCallback) => {
global.requestAnimationFrame((frameTime) => {
frameDeadline = frameTime + fps;
pendingCallback = callback;
channel.port1.postMessage(null);
});
return id;
};
})(window);
const isDef = <T>(param: T): param is NonNullable<T> =>
param !== void 0 && param !== null;
const isPlainObject = (val: unknown): val is Record<string, unknown> =>
Object.prototype.toString.call(val) === '[object Object]' &&
[Object.prototype, null].includes(Object.getPrototypeOf(val));
// Simple judgment of virtual elements.
const isVirtualElement = (e: unknown): e is VirtualElement =>
typeof e === 'object';
// Text elements require special handling.
const createTextElement = (text: string): VirtualElement => ({
type: 'TEXT',
props: {
nodeValue: text,
},
});
// Create custom JavaScript data structures.
const createElement = (
type: VirtualElementType,
props: Record<string, unknown> = {},
...child: (unknown | VirtualElement)[]
): VirtualElement => {
const children = child.map((c) =>
isVirtualElement(c) ? c : createTextElement(String(c)),
);
return {
type,
props: {
...props,
children,
},
};
};
// Update DOM properties.
// For simplicity, we remove all the previous properties and add next properties.
const updateDOM = (
DOM: NonNullable<FiberNodeDOM>,
prevProps: VirtualElementProps,
nextProps: VirtualElementProps,
) => {
const defaultPropKeys = 'children';
for (const [removePropKey, removePropValue] of Object.entries(prevProps)) {
if (removePropKey.startsWith('on')) {
DOM.removeEventListener(
removePropKey.slice(2).toLowerCase(),
removePropValue as EventListener,
);
} else if (removePropKey !== defaultPropKeys) {
// @ts-expect-error: Unreachable code error
DOM[removePropKey] = '';
}
}
for (const [addPropKey, addPropValue] of Object.entries(nextProps)) {
if (addPropKey.startsWith('on')) {
DOM.addEventListener(
addPropKey.slice(2).toLowerCase(),
addPropValue as EventListener,
);
} else if (addPropKey !== defaultPropKeys) {
// @ts-expect-error: Unreachable code error
DOM[addPropKey] = addPropValue;
}
}
};
// Create DOM based on node type.
const createDOM = (fiberNode: FiberNode): FiberNodeDOM => {
const { type, props } = fiberNode;
let DOM: FiberNodeDOM = null;
if (type === 'TEXT') {
DOM = document.createTextNode('');
} else if (typeof type === 'string') {
DOM = document.createElement(type);
}
// Update properties based on props after creation.
if (DOM !== null) {
updateDOM(DOM, {}, props);
}
return DOM;
};
// Change the DOM based on fiber node changes.
// Note that we must complete the comparison of all fiber nodes before commitRoot.
// The comparison of fiber nodes can be interrupted, but the commitRoot cannot be interrupted.
const commitRoot = () => {
const findParentFiber = (fiberNode?: FiberNode) => {
if (fiberNode) {
let parentFiber = fiberNode.return;
while (parentFiber && !parentFiber.dom) {
parentFiber = parentFiber.return;
}
return parentFiber;
}
return null;
};
const commitDeletion = (
parentDOM: FiberNodeDOM,
DOM: NonNullable<FiberNodeDOM>,
) => {
if (isDef(parentDOM)) {
parentDOM.removeChild(DOM);
}
};
const commitReplacement = (
parentDOM: FiberNodeDOM,
DOM: NonNullable<FiberNodeDOM>,
) => {
if (isDef(parentDOM)) {
parentDOM.appendChild(DOM);
}
};
const commitWork = (fiberNode?: FiberNode) => {
if (fiberNode) {
if (fiberNode.dom) {
const parentFiber = findParentFiber(fiberNode);
const parentDOM = parentFiber?.dom;
switch (fiberNode.effectTag) {
case 'REPLACEMENT':
commitReplacement(parentDOM, fiberNode.dom);
break;
case 'UPDATE':
updateDOM(
fiberNode.dom,
fiberNode.alternate ? fiberNode.alternate.props : {},
fiberNode.props,
);
break;
default:
break;
}
}
commitWork(fiberNode.child);
commitWork(fiberNode.sibling);
}
};
for (const deletion of deletions) {
if (deletion.dom) {
const parentFiber = findParentFiber(deletion);
commitDeletion(parentFiber?.dom, deletion.dom);
}
}
if (wipRoot !== null) {
commitWork(wipRoot.child);
currentRoot = wipRoot;
}
wipRoot = null;
};
// Reconcile the fiber nodes before and after, compare and record the differences.
const reconcileChildren = (
fiberNode: FiberNode,
elements: VirtualElement[] = [],
) => {
let index = 0;
let oldFiberNode: FiberNode | undefined = void 0;
let prevSibling: FiberNode | undefined = void 0;
const virtualElements = elements.flat(Infinity);
if (fiberNode.alternate?.child) {
oldFiberNode = fiberNode.alternate.child;
}
while (
index < virtualElements.length ||
typeof oldFiberNode !== 'undefined'
) {
const virtualElement = virtualElements[index];
let newFiber: FiberNode | undefined = void 0;
const isSameType = Boolean(
oldFiberNode &&
virtualElement &&
oldFiberNode.type === virtualElement.type,
);
if (isSameType && oldFiberNode) {
newFiber = {
type: oldFiberNode.type,
dom: oldFiberNode.dom,
alternate: oldFiberNode,
props: virtualElement.props,
return: fiberNode,
effectTag: 'UPDATE',
};
}
if (!isSameType && Boolean(virtualElement)) {
newFiber = {
type: virtualElement.type,
dom: null,
alternate: null,
props: virtualElement.props,
return: fiberNode,
effectTag: 'REPLACEMENT',
};
}
if (!isSameType && oldFiberNode) {
deletions.push(oldFiberNode);
}
if (oldFiberNode) {
oldFiberNode = oldFiberNode.sibling;
}
if (index === 0) {
fiberNode.child = newFiber;
} else if (typeof prevSibling !== 'undefined') {
prevSibling.sibling = newFiber;
}
prevSibling = newFiber;
index += 1;
}
};
// Execute each unit task and return to the next unit task.
// Different processing according to the type of fiber node.
const performUnitOfWork = (fiberNode: FiberNode): FiberNode | null => {
const { type } = fiberNode;
switch (typeof type) {
case 'function': {
wipFiber = fiberNode;
wipFiber.hooks = [];
hookIndex = 0;
let children: ReturnType<ComponentFunction>;
if (Object.getPrototypeOf(type).REACT_COMPONENT) {
const C = type;
const component = new C(fiberNode.props);
const [state, setState] = useState(component.state);
component.props = fiberNode.props;
component.state = state;
component.setState = setState;
children = component.render.bind(component)();
} else {
children = type(fiberNode.props);
}
reconcileChildren(fiberNode, [
isVirtualElement(children)
? children
: createTextElement(String(children)),
]);
break;
}
case 'number':
case 'string':
if (!fiberNode.dom) {
fiberNode.dom = createDOM(fiberNode);
}
reconcileChildren(fiberNode, fiberNode.props.children);
break;
case 'symbol':
if (type === Fragment) {
reconcileChildren(fiberNode, fiberNode.props.children);
}
break;
default:
if (typeof fiberNode.props !== 'undefined') {
reconcileChildren(fiberNode, fiberNode.props.children);
}
break;
}
if (fiberNode.child) {
return fiberNode.child;
}
let nextFiberNode: FiberNode | undefined = fiberNode;
while (typeof nextFiberNode !== 'undefined') {
if (nextFiberNode.sibling) {
return nextFiberNode.sibling;
}
nextFiberNode = nextFiberNode.return;
}
return null;
};
// Use requestIdleCallback to query whether there is currently a unit task
// and determine whether the DOM needs to be updated.
const workLoop: IdleRequestCallback = (deadline) => {
while (nextUnitOfWork && deadline.timeRemaining() > 1) {
nextUnitOfWork = performUnitOfWork(nextUnitOfWork);
}
if (!nextUnitOfWork && wipRoot) {
commitRoot();
}
window.requestIdleCallback(workLoop);
};
// Initial or reset.
const render = (element: VirtualElement, container: Element) => {
currentRoot = null;
wipRoot = {
type: 'div',
dom: container,
props: {
children: [{ ...element }],
},
alternate: currentRoot,
};
nextUnitOfWork = wipRoot;
deletions = [];
};
abstract class Component {
props: Record<string, unknown>;
abstract state: unknown;
abstract setState: (value: unknown) => void;
abstract render: () => VirtualElement;
constructor(props: Record<string, unknown>) {
this.props = props;
}
// Identify Component.
static REACT_COMPONENT = true;
}
// Associate the hook with the fiber node.
function useState<S>(initState: S): [S, (value: S) => void] {
const fiberNode: FiberNode<S> = wipFiber;
const hook: {
state: S;
queue: S[];
} = fiberNode?.alternate?.hooks
? fiberNode.alternate.hooks[hookIndex]
: {
state: initState,
queue: [],
};
while (hook.queue.length) {
let newState = hook.queue.shift();
if (isPlainObject(hook.state) && isPlainObject(newState)) {
newState = { ...hook.state, ...newState };
}
if (isDef(newState)) {
hook.state = newState;
}
}
if (typeof fiberNode.hooks === 'undefined') {
fiberNode.hooks = [];
}
fiberNode.hooks.push(hook);
hookIndex += 1;
const setState = (value: S) => {
hook.queue.push(value);
if (currentRoot) {
wipRoot = {
type: currentRoot.type,
dom: currentRoot.dom,
props: currentRoot.props,
alternate: currentRoot,
};
nextUnitOfWork = wipRoot;
deletions = [];
currentRoot = null;
}
};
return [hook.state, setState];
}
// Start the engine!
void (function main() {
window.requestIdleCallback(workLoop);
})();
export default {
createElement,
render,
useState,
Component,
Fragment,
};