-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.js
1293 lines (1097 loc) · 30.7 KB
/
test.js
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
export const jsx = (type, props = {}, key = null) => ({
key,
type,
props,
});
export const Fragment = (props) => props.children;
const noop = () => {};
const isArray = (val) => Array.isArray(val);
const isString = (val) => typeof val === "string";
const isFunction = (val) => typeof val === "function";
export const objectEqual = (object1, object2, isDeep) => {
if (object1 === object2) {
return true;
}
if (
object1 === null ||
object2 === null ||
typeof object1 !== "object" ||
typeof object2 !== "object"
) {
return false;
}
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const o1 = object1[key];
const o2 = object2[key];
if (isDeep) {
if (!objectEqual(o1, o2, true)) {
return false;
}
} else {
if (o1 !== o2) {
return false;
}
}
}
return true;
};
const isSpecialBooleanAttr = (val) =>
val === "allowfullscreen" ||
val === "formnovalidate" ||
val === "novalidate" ||
val === "itemscope" ||
val === "nomodule" ||
val === "readonly" ||
val === "ismap";
const includeBooleanAttr = (value) => value === "" || !!value;
const genQueueMacrotask = (macrotaskName) => {
const frameYieldMs = 10;
const scheduledQueue = [];
const channel = new MessageChannel();
let isLoopRunning = false;
channel.port1.onmessage = () => {
if (!scheduledQueue.length) {
isLoopRunning = false;
return;
}
const startTime = Date.now();
const timeoutTime = startTime + frameYieldMs;
const didTimeout = () => Date.now() > timeoutTime;
try {
while (scheduledQueue.length > 0 && !didTimeout()) {
const work = scheduledQueue[scheduledQueue.length - 1];
const next = work();
if (isFunction(next)) {
scheduledQueue[scheduledQueue.length - 1] = next;
} else {
scheduledQueue.length -= 1;
}
}
} finally {
if (scheduledQueue.length > 0) {
schedulePerform();
} else {
isLoopRunning = false;
}
}
};
const schedulePerform = () => channel.port2.postMessage(null);
return (task) => {
if (!scheduledQueue.includes(task)) {
scheduledQueue.unshift(task);
if (!isLoopRunning) {
isLoopRunning = true;
schedulePerform();
}
}
};
};
const mainQueueMacrotask = genQueueMacrotask("main-macro-task");
const effectQueueMacrotask = genQueueMacrotask("effect-macro-task");
const elementPropsKey = "__fiber";
/* #region 事件相关 */
const eventTypeMap = {
click: ["onClickCapture", "onClick"],
dblclick: ["onDblclickCapture", "onDblclick"],
mousedown: ["onMousedownCapture", "onMousedown"],
mouseup: ["onMouseupCapture", "onMouseup"],
mousemove: ["onMousemoveCapture", "onMousemove"],
keydown: ["onKeydownCapture", "onKeydown"],
keyup: ["onKeyupCapture", "onKeyup"],
keypress: ["onKeypressCapture", "onKeypress"],
submit: ["onSubmitCapture", "onSubmit"],
touchstart: ["onTouchstartCapture", "onTouchstart"],
touchend: ["onTouchendCapture", "onTouchend"],
touchmove: ["onTouchmoveCapture", "onTouchmove"],
};
const collectPaths = (targetElement, container, eventType) => {
const paths = {
capture: [],
bubble: [],
};
while (targetElement && targetElement !== container) {
const callbackNameList = eventTypeMap[eventType];
const elementProps = targetElement[elementPropsKey]
? targetElement[elementPropsKey].memoizedProps
: null;
if (elementProps && callbackNameList) {
const [captureName, bubbleName] = callbackNameList;
if (elementProps[captureName]) {
paths.capture.unshift(elementProps[captureName]);
}
if (elementProps[bubbleName]) {
paths.bubble.push(elementProps[bubbleName]);
}
}
targetElement = targetElement.parentNode;
}
return paths;
};
const createSyntheticEvent = (e) => {
const syntheticEvent = e;
const originStopPropagation = e.stopPropagation;
syntheticEvent.__stopPropagation = false;
syntheticEvent.stopPropagation = () => {
syntheticEvent.__stopPropagation = true;
if (originStopPropagation) {
originStopPropagation();
}
};
return syntheticEvent;
};
const triggerEventFlow = (paths, se) => {
for (let i = 0; i < paths.length; i++) {
const callback = paths[i];
callback.call(null, se);
if (se.__stopPropagation) {
return;
}
}
};
const dispatchEvent = (container, eventType, e) => {
const targetElement = e.target;
if (!targetElement) {
return console.warn("事件不存在target", e);
}
const { bubble, capture } = collectPaths(targetElement, container, eventType);
const syntheticEvent = createSyntheticEvent(e);
triggerEventFlow(capture, syntheticEvent);
if (!syntheticEvent.__stopPropagation) {
triggerEventFlow(bubble, syntheticEvent);
}
};
const initEvent = (container, eventType) => {
container.addEventListener(eventType, (e) => {
dispatchEvent(container, eventType, e);
});
};
const testHostSpecialAttr = (name) => /^on[A-Z]/.test(name);
const hostSpecialAttrSet = new Set([
"onLoad",
"onBeforeunload",
"onUnload",
"onScroll",
"onFocus",
"onBlur",
"onPointerenter",
"onPointerleave",
"onInput",
]);
const onCompositionStart = (e) => {
e.target.composing = true;
};
const onCompositionEnd = (e) => {
const target = e.target;
if (target.composing) {
target.composing = false;
target.dispatchEvent(new Event("input"));
}
};
const onInputFixed = (e) => {
if (!e.target.composing) {
const elementProps = e.target[elementPropsKey].memoizedProps;
elementProps["onInput"](e);
}
};
const eventCallback = (e) => {
const pKey = "on" + e.type[0].toUpperCase() + e.type.slice(1);
const elementProps = e.target[elementPropsKey]
? e.target[elementPropsKey].memoizedProps
: null;
if (elementProps && elementProps[pKey]) {
elementProps[pKey](e);
}
};
const camelizePlacer = (_, c) => (c ? c.toUpperCase() : "");
const camelize = (str) => {
return str.replace(/-(\w)/g, camelizePlacer);
};
const setStyle = (style, name, val) => {
if (isArray(val)) {
val.forEach((v) => setStyle(style, name, v));
} else {
if (val == null) {
val = "";
}
if (name.startsWith("--")) {
style.setProperty(name, val);
} else {
style[camelize(name)] = val;
}
}
};
const domHostConfig = {
attrMap: {
className: "class",
htmlFor: "for",
},
fixAttrName(key) {
return domHostConfig.attrMap[key] || key;
},
createInstance(type) {
return document.createElement(type);
},
createTextInstance(content) {
return document.createTextNode(content);
},
toLast(child, container) {
container.appendChild(child);
},
toFirst(child, container) {
container.insertBefore(child, container.firstChild);
},
toBefore(child, container, reference) {
container.insertBefore(child, reference);
},
toAfter(child, container, reference) {
container.insertBefore(child, reference.nextSibling);
},
removeChild(child) {
child.parentNode.removeChild(child);
child[elementPropsKey] = null;
},
commitTextUpdate(node, content) {
node.nodeValue = content;
},
commitInstanceUpdate(node, attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const pKey = attrs[i];
const pValue = attrs[i + 1];
if (hostSpecialAttrSet.has(pKey)) {
domHostConfig.fixHostSpecial(node, pKey, pValue);
} else {
const attrName = domHostConfig.fixAttrName(pKey);
if (pValue === void 0) {
node.removeAttribute(attrName);
} else if (attrName === "style") {
const styleValue = pValue;
if (isString(styleValue)) {
node.style.cssText = styleValue;
} else {
for (const key in styleValue) {
setStyle(node.style, key, styleValue[key]);
}
}
} else {
node.setAttribute(attrName, pValue);
}
}
}
},
fixHostSpecial(node, fullEventName, callback) {
const eventName = fullEventName.slice(2).toLowerCase();
const method =
callback === void 0 ? "removeEventListener" : "addEventListener";
if (eventName === "input") {
node[method]("compositionstart", onCompositionStart);
node[method]("compositionend", onCompositionEnd);
node[method]("change", onCompositionEnd);
node[method]("input", onInputFixed);
} else {
node[method](eventName, eventCallback);
}
},
updateInstanceProps(node, fiber) {
node[elementPropsKey] = fiber;
},
genRestoreDataFn() {
const focusedElement = document.activeElement;
const start = focusedElement.selectionStart;
const end = focusedElement.selectionEnd;
// 重新定位焦点, 恢复选择位置
return () => {
focusedElement.focus();
focusedElement.selectionStart = start;
focusedElement.selectionEnd = end;
};
},
};
/* #region-end 事件相关 */
const hostConfig = domHostConfig;
let workInProgress = null;
export const useFiber = (isInitHook) => {
if (isInitHook && !workInProgress.hookQueue) {
workInProgress.hookQueue = [];
}
return workInProgress;
};
const genComponentInnerElement = (fiber) => {
let result = null;
const preFiber = workInProgress;
try {
fiber.__StateIndex = 0;
workInProgress = fiber;
result = fiber.type(fiber.pendingProps);
} finally {
workInProgress = preFiber;
}
return result;
};
export const useReducer = (reducer, initialState) => {
const fiber = useFiber(true);
const innerIndex = fiber.__StateIndex++;
const { hookQueue } = fiber;
if (hookQueue.length <= innerIndex) {
const state = isFunction(initialState) ? initialState() : initialState;
// 协调阶段,其他事件修改了state,需要排队到下一个时间循环
const dispatch = (action) => {
fiber.updateQueue ||= [];
fiber.updateQueue.push(() => {
const newState = reducer(hookQueue[innerIndex].state, action);
hookQueue[innerIndex].state = newState;
});
fiber.rerender();
};
hookQueue[innerIndex] = { state, dispatch };
}
return [hookQueue[innerIndex].state, hookQueue[innerIndex].dispatch];
};
export const useRef = (initialValue) => {
const fiber = useFiber(true);
const innerIndex = fiber.__StateIndex++;
const { hookQueue } = fiber;
if (hookQueue.length <= innerIndex) {
hookQueue[innerIndex] = { current: initialValue };
}
return hookQueue[innerIndex];
};
export const useState = (initialState) => {
return useReducer((state, action) => {
return isFunction(action) ? action(state) : action;
}, initialState);
};
export const createContext = (initialState) => {
return {
Provider: (props) => {
const fiber = useFiber();
const { value, children } = props;
if (value === void 0) {
fiber.pendingProps.value = initialState;
}
fiber.memoizedState ||= new Set();
fiber.memoizedState.forEach((f) => {
f.preStateFlag |= SelfStateChange;
findParentFiber(f, (item) => {
item.preStateFlag |= ChildStateChange;
return item === fiber;
});
});
fiber.memoizedState.clear();
return children;
},
};
};
export const useContext = (context) => {
const fiber = useFiber();
const checkProvider = (f) => f.type === context.Provider;
const providerFiber = findParentFiber(fiber, checkProvider);
providerFiber.memoizedState.add(fiber);
return providerFiber.pendingProps.value;
};
export const useEffect = (func, dep) => {
const fiber = useFiber(true);
const innerIndex = fiber.__StateIndex++;
const { hookQueue } = fiber;
if (hookQueue.length <= innerIndex) {
if (!fiber.onMounted) {
Fiber.initLifecycle(fiber);
}
if (isArray(dep)) {
if (!dep.length) {
fiber.onMounted.add(func);
} else {
fiber.onUpdated.add(func);
}
} else if (Number.isNaN(dep)) {
fiber.onBeforeMove.add(func);
} else {
fiber.onUpdated.add(func);
}
hookQueue[innerIndex] = { func, dep };
} else {
const { dep: oldDep, func: oldFunc } = hookQueue[innerIndex];
if (isArray(dep) && isArray(oldDep) && dep.length && oldDep.length) {
fiber.onUpdated.delete(oldFunc);
if (!objectEqual(oldDep, dep)) {
hookQueue[innerIndex] = { func, dep };
fiber.onUpdated.add(func);
}
}
}
};
const checkIfSnapshotChanged = ({ value, getSnapshot }) => {
try {
return value !== getSnapshot();
} catch {
return true;
}
};
export const useSyncExternalStore = (subscribe, getSnapshot) => {
const value = getSnapshot();
const [{ inst }, forceUpdate] = useState({
inst: { value, getSnapshot },
});
useEffect(() => {
if (checkIfSnapshotChanged(inst)) {
forceUpdate({ inst });
}
return subscribe(() => {
if (checkIfSnapshotChanged(inst)) {
forceUpdate({ inst });
}
});
}, [subscribe]);
return value;
};
const nextHookMap = {
onBeforeMove: "onMoved",
onMounted: "onUnMounted",
onUpdated: "onBeforeUpdate",
};
const runner = (fiber, hookName) => {
for (const hook of fiber[hookName]) {
const destroy = hook(fiber);
if (isFunction(destroy) && hookName in nextHookMap) {
const cleanName = nextHookMap[hookName];
if (fiber[cleanName]) {
const destroyOnce = () => {
destroy();
fiber[cleanName].delete(destroyOnce);
};
fiber[cleanName].add(destroyOnce);
}
}
}
};
const dispatchHook = (fiber, hookName, async) => {
if (fiber[hookName] && fiber[hookName].size) {
if (async) {
effectQueueMacrotask(() => runner(fiber, hookName));
} else {
runner(fiber, hookName);
}
}
};
const toElement = (item) => {
const itemType = typeof item;
if (item && itemType === "object" && item.type) {
return item;
} else if (itemType === "string" || itemType === "number") {
return jsx("text", { content: item });
} else if (isArray(item)) {
return jsx(Fragment, { children: item });
} else {
return jsx("text", { content: "" });
}
};
const NoFlags = 0 << 0;
const MarkMount = 1 << 0;
const MarkMoved = 1 << 1;
const ChildDeletion = 1 << 2;
const MarkUpdate = 1 << 3;
const MarkRef = 1 << 4;
const markUpdate = (fiber) => {
fiber.flags |= MarkUpdate;
};
const markMount = (fiber) => {
fiber.flags |= MarkMount;
};
const markMoved = (fiber) => {
fiber.flags |= MarkMoved;
};
const markRef = (fiber) => {
fiber.flags |= MarkRef;
};
const markChildDeletion = (fiber) => {
fiber.flags |= ChildDeletion;
};
const HostText = Symbol("HostText");
const HostComponent = Symbol("HostComponent");
const FunctionComponent = Symbol("FunctionComponent");
const NoPortal = 0 << 0;
const SelfPortal = 1 << 0;
const ReturnPortal = 1 << 1;
const NoStateChange = 0 << 0;
const SelfStateChange = 1 << 0;
const ChildStateChange = 1 << 1;
class Fiber {
key = null;
ref = null;
type = null;
tagType = null;
nodeKey = "";
pendingProps = {};
memoizedProps = {};
memoizedState = null;
__StateIndex = 0;
updateQueue = null;
index = -1;
oldIndex = -1;
__refer = null;
__deletion = null;
stateNode = null;
child = null;
return = null;
sibling = null;
flags = MarkMount;
portalFlag = NoPortal;
preStateFlag = SelfStateChange;
get normalChildren() {
if (this.tagType === HostText) {
return null;
}
const tempChildren =
this.tagType === HostComponent
? this.pendingProps.children
: genComponentInnerElement(this);
if (tempChildren === void 0) {
return null;
} else {
return isArray(tempChildren)
? tempChildren.map(toElement)
: [toElement(tempChildren)];
}
}
constructor(element, key, nodeKey) {
this.key = key;
this.nodeKey = nodeKey;
this.type = element.type;
this.pendingProps = element.props;
if (this.type === "text") {
this.tagType = HostText;
this.memoizedProps = this.pendingProps;
this.stateNode = hostConfig.createTextInstance(this.pendingProps.content);
} else if (isString(this.type)) {
this.tagType = HostComponent;
this.stateNode = hostConfig.createInstance(this.type);
hostConfig.updateInstanceProps(this.stateNode, this);
} else {
this.tagType = FunctionComponent;
}
}
rerender() {
if (Fiber.scheduler) {
return;
}
if (!isContainerFiber(this)) {
Fiber.RerenderSet.add(this);
mainQueueMacrotask(batchRerender);
} else {
Fiber.scheduler = {
preHostFiber: null,
MutationQueue: [],
gen: genFiberTree(this),
restoreDataFn: hostConfig.genRestoreDataFn(),
};
mainQueueMacrotask(innerRender);
}
}
}
Fiber.RerenderSet = new Set();
Fiber.genNodeKey = (key, pNodeKey = "") => pNodeKey + "^" + key;
Fiber.initLifecycle = (fiber) => {
fiber.onMounted = new Set();
fiber.onUnMounted = new Set();
fiber.onUpdated = new Set();
fiber.onBeforeUpdate = new Set();
fiber.onBeforeMove = new Set();
fiber.onMoved = new Set();
};
const isPortal = (f) => f.portalFlag & SelfPortal;
const isHostFiber = (f) => f.tagType === HostComponent;
const isContainerFiber = (f) => isHostFiber(f) || isPortal(f);
const isDescendantOf = (fiber, returnFiber) =>
findParentFiber(fiber, (f) => f === returnFiber);
const runUpdate = (fn) => fn();
const batchRerender = () => {
const mapFiberCount = new Map();
let commonReturnHost = null;
let fiber = null;
label: for (const current of Fiber.RerenderSet) {
current.updateQueue.forEach(runUpdate);
current.updateQueue.length = 0;
current.preStateFlag |= SelfStateChange;
fiber = current;
while (fiber) {
if (isContainerFiber(fiber)) {
const preCount = mapFiberCount.get(fiber) || 0;
if (preCount + 1 >= Fiber.RerenderSet.size) {
commonReturnHost = fiber;
break label;
} else {
mapFiberCount.set(fiber, preCount + 1);
}
}
fiber = fiber.return;
if (fiber) {
fiber.preStateFlag |= ChildStateChange;
}
}
}
Fiber.RerenderSet.clear();
if (commonReturnHost) {
findParentFiber(commonReturnHost, (f) => {
f.preStateFlag &= ~ChildStateChange;
});
commonReturnHost.rerender();
}
};
function* walkChildFiber(returnFiber) {
let fiber = returnFiber.child;
while (fiber) {
yield fiber;
fiber = fiber.sibling;
}
}
function* walkFiberTree(returnFiber, fn = noop) {
let fiber = returnFiber.child;
while (fiber) {
fn(fiber, returnFiber);
yield* walkFiberTree(fiber);
fiber = fiber.sibling;
}
yield returnFiber;
}
const createFiber = (element, key, nodeKey, deletionMap) => {
let fiber = deletionMap.size ? deletionMap.get(nodeKey) : null;
if (fiber) {
fiber.pendingProps = element.props;
fiber.sibling = null;
fiber.return = null;
if (
!(fiber.preStateFlag & SelfStateChange) &&
!objectEqual(fiber.pendingProps, fiber.memoizedProps, true)
) {
fiber.preStateFlag |= SelfStateChange;
}
} else {
fiber = new Fiber(element, key, nodeKey);
}
return fiber;
};
const findParentFiber = (fiber, checker) => {
let current = fiber.return;
while (current) {
if (checker(current)) {
return current;
}
current = current.return;
}
};
const findIndex = (nodeKeyArr, fiber, fiberMap) => {
let i = 0;
let j = nodeKeyArr.length;
while (i !== j) {
const mid = Math.floor((i + j) / 2);
const tempFiber = fiberMap.get(nodeKeyArr[mid]);
if (tempFiber.oldIndex < fiber.oldIndex) {
i = mid + 1;
} else {
j = mid;
}
}
return i;
};
const beginWork = (returnFiber) => {
if (!(returnFiber.preStateFlag & SelfStateChange)) {
return;
}
const deletionMap = new Map();
for (const oldFiber of walkChildFiber(returnFiber)) {
deletionMap.set(oldFiber.nodeKey, oldFiber);
}
returnFiber.child = null;
const increasing = deletionMap.size ? [] : null;
const deletionKey = deletionMap.size ? [] : null;
let indexCount = [];
let j = 0;
const children = returnFiber.normalChildren;
if (children !== null) {
let preFiber = null;
for (let index = 0; index < children.length; index++) {
const element = children[index];
const key =
(isString(element.type) ? element.type : element.type.name) +
"#" +
(element.key != null ? element.key : index);
const nodeKey = Fiber.genNodeKey(key, returnFiber.nodeKey);
const fiber = createFiber(element, key, nodeKey, deletionMap);
fiber.index = index;
fiber.return = returnFiber;
if (fiber.oldIndex === -1) {
markMount(fiber);
} else {
if (!fiber.memoizedProps.__target && !fiber.pendingProps.__target) {
markMoved(fiber);
deletionKey.push(nodeKey);
const i = findIndex(increasing, fiber, deletionMap);
if (i + 1 > increasing.length) {
increasing.push(nodeKey);
indexCount[j++] = increasing.length;
} else {
increasing[i] = nodeKey;
indexCount[j++] = i + 1;
}
} else {
if (fiber.memoizedProps.__target !== fiber.pendingProps.__target) {
markMoved(fiber);
}
deletionMap.delete(nodeKey);
}
}
if (index === 0) {
returnFiber.child = fiber;
} else {
preFiber.sibling = fiber;
}
preFiber = fiber;
}
}
if (deletionMap.size || (increasing && increasing.length)) {
// increasing 不一定是正确的最长递增序列,中间有些数有可能被替换了
// 所以需要再走一遍构建 increasing 的逻辑
let max = Math.max(...indexCount);
for (let i = deletionKey.length - 1; max > 0; i--) {
if (indexCount[i] === max) {
increasing[max - 1] = deletionKey[i];
max--;
}
}
if (increasing) {
for (const anchor of increasing) {
deletionMap.get(anchor).flags &= ~MarkMoved;
}
}
for (const k of deletionKey) {
deletionMap.delete(k);
}
if (deletionMap.size) {
returnFiber.__deletion = deletionMap;
markChildDeletion(returnFiber);
}
}
};
const finishedWork = (fiber) => {
if (!fiber.flags && !fiber.preStateFlag) {
fiber.memoizedProps = fiber.pendingProps;
} else {
const oldProps = fiber.memoizedProps || {};
const newProps = fiber.pendingProps || {};
let isMarkUpdate = false;
if (oldProps.ref !== newProps.ref) {
const oldRef = oldProps.ref;
const newRef = newProps.ref;
isMarkUpdate = true;
fiber.ref = (instance) => {
if (isFunction(oldRef)) {
oldRef(null);
} else if (oldRef && "current" in oldRef) {
oldRef.current = null;
}
if (isFunction(newRef)) {
newRef(instance);
} else if (newRef && "current" in newRef) {
newRef.current = instance;
}
};
markRef(fiber);
}
if (fiber.tagType === HostText) {
if (!oldProps || newProps.content !== oldProps.content) {
fiber.memoizedState = newProps.content;
isMarkUpdate = true;
}
} else if (fiber.tagType === HostComponent) {
const attrs = [];
const skip = Object.create(null);
for (const pKey in newProps) {
const pValue = newProps[pKey];
let oldPValue = void 0;
if (pKey in oldProps) {
oldPValue = oldProps[pKey];
skip[pKey] = true;
}
if (
pKey === "children" ||
pKey === "ref" ||
pKey[0] === "_" ||
pValue === oldPValue
) {
continue;
}
if (testHostSpecialAttr(pKey)) {
if (hostSpecialAttrSet.has(pKey)) {
attrs.push(pKey, pValue);
}
} else {
const isBoolean = isSpecialBooleanAttr(pKey);
if (pValue == null || (isBoolean && !includeBooleanAttr(pValue))) {
attrs.push(pKey, void 0);
} else {
attrs.push(pKey, isBoolean ? "" : pValue);
}
}
}
for (const pKey in oldProps) {
if (
pKey === "children" ||
pKey === "ref" ||
pKey[0] === "_" ||
skip[pKey]
) {
continue;
}
if (testHostSpecialAttr(pKey)) {
if (hostSpecialAttrSet.has(pKey)) {
attrs.push(pKey, void 0);
}
} else {
attrs.push(pKey, void 0);