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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
|
// 入口
export const createApp = ((...args) => {
/**
* patchProp 更新 props 方法集合
* forcePatchProp = (_, key) => key === 'value'
* nodeOps DOM 操作方法集合
*/
const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
const { render } = baseCreateRenderer(rendererOptions);
const createApp = createAppAPI(render);
const app = createApp(...args);
const { mount } = app;
// 根组件挂载节点,ShadowRoot 接口是一个 DOM 子树的根节点,它与文档的主 DOM 树分开渲染
app.mount = (containerOrSelector: Element | ShadowRoot | string): any => {
const container = normalizeContainer(containerOrSelector); // HTMLElement || null
if (!container) return;
const component = app._component;
if (!isFunction(component) && !component.render && !component.template) {
component.template = container.innerHTML;
}
// 挂载之前清空 container
container.innerHTML = '';
const proxy = mount(container);
if (container instanceof Element) {
container.removeAttribute('v-cloak');
container.setAttribute('data-v-app', '');
}
return proxy;
};
return app;
}) as CreateAppFunction<Element>;
export function createAppAPI<HostElement>(
render: RootRenderFunction
): CreateAppFunction<HostElement> {
return function createApp(rootComponent, rootProps = null) {
if (rootProps != null && !isObject(rootProps)) {
rootProps = null;
}
const context = createAppContext();
const installedPlugins = new Set();
let isMounted = false;
const app: App = (context.app = {
_uid: uid++,
_component: rootComponent as ConcreteComponent,
_props: rootProps,
_container: null,
_context: context,
get config() {
return context.config;
},
set config(v) {
warn('app.config 不能被覆盖');
},
use(plugin: Plugin, ...options: any[]) {
if (installedPlugins.has(plugin)) {
warn(`插件已安装`);
} else if (plugin && isFunction(plugin.install)) {
installedPlugins.add(plugin);
plugin.install(app, ...options);
} else if (isFunction(plugin)) {
installedPlugins.add(plugin);
plugin(app, ...options);
} else {
warn('插件应该是一个函数或者一个有 install 方法的对象');
}
return app;
},
mixin(mixin: ComponentOptions) {
if (!context.mixins.includes(mixin)) {
context.mixins.push(mixin);
if (mixin.props || mixin.emits) {
context.deopt = true;
}
} else {
warn('mixin 过了');
}
return app;
},
component(name: string, component?: Component): any {
if (!component) {
return context.components[name];
}
if (context.components[name]) {
warn('组件已经注册过了');
}
context.components[name] = component;
return app;
},
directive(name: string, directive?: Directive) {
if (!directive) {
return context.directives[name] as any;
}
if (context.directives[name]) {
warn('指令已经注册过了');
}
context.directives[name] = directive;
return app;
},
mount(rootContainer: HostElement): any {
if (!isMounted) {
const vnode = createVNode(
rootComponent as ConcreteComponent,
rootProps
);
// 在根节点上存储 app context,在第一次渲染的,会被设为根实例
vnode.appContext = context;
// 将 VNode 借助 patch 渲染到 container
render(vnode, rootContainer);
isMounted = true;
app._container = rootContainer;
return vnode.component!.proxy;
}
},
unmount() {
if (isMounted) {
// 直接渲染 null???
render(null, app._container);
} else {
warn(`没有挂载过,怎么卸载?`);
}
},
provide(key, value) {
if ((key as string | symbol) in context.provides) {
warn('App 已经 provides 这个属性了,小心被覆盖');
}
context.provides[key as string] = value;
return app;
}
});
return app;
};
}
function baseCreateRenderer(
options: RendererOptions,
createHydrationFns?: typeof createHydrationFunctions
): any {
// ...
const patch: PatchFn = (
n1, // 旧的 VNode
n2, // 新的 VNode
container, // DOM 容器(挂载到的地方)
anchor = null, // 锚点
parentComponent = null,
parentSuspense = null,
isSVG = false,
optimized = false
) => {
// 存在旧节点且新旧节点不是同种类型,先卸载旧的
if (n1 && !isSameVNodeType(n1, n2)) {
anchor = getNextHostNode(n1);
unmount(n1, parentComponent, parentSuspense, true);
n1 = null;
}
if (n2.patchFlag === PatchFlags.BAIL) {
optimized = false;
n2.dynamicChildren = null;
}
const { type, ref, shapeFlag } = n2;
switch (type) {
case Text: // 处理文本节点
processText(n1, n2, container, anchor);
break;
case Comment: // 处理注释节点
processCommentNode(n1, n2, container, anchor);
break;
case Static: // 处理静态节点
if (n1 == null) {
mountStaticNode(n2, container, anchor, isSVG);
} else {
patchStaticNode(n1, n2, container, isSVG);
}
break;
case Fragment: // 处理 Fragment
processFragment(
n1,
n2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
break;
default:
if (shapeFlag & ShapeFlags.ELEMENT) {
// 处理元素
processElement(
n1,
n2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
} else if (shapeFlag & ShapeFlags.COMPONENT) {
// 处理组件
processComponent(
n1,
n2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
} else if (shapeFlag & ShapeFlags.TELEPORT) {
// 处理 teleport
(type as typeof TeleportImpl).process(
n1 as TeleportVNode,
n2 as TeleportVNode,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized,
internals
);
} else if (__FEATURE_SUSPENSE__ && shapeFlag & ShapeFlags.SUSPENSE) {
// 处理 Suspense
(type as typeof SuspenseImpl).process(
n1,
n2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized,
internals
);
}
}
// 更新 ref
if (ref != null && parentComponent) {
setRef(ref, n1 && n1.ref, parentSuspense, n2);
}
};
// ...
const render: RootRenderFunction = (vnode, container) => {
if (vnode == null) {
if (container._vnode) {
unmount(container._vnode, null, null, true);
}
} else {
patch(container._vnode || null, vnode, container);
}
flushPostFlushCbs();
container._vnode = vnode;
};
// ...
}
/**
* 元素挂载 patch-processElement-mountElement
* mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized)
*/
const mountElement = (
vnode: VNode,
container: RendererElement,
anchor: RendererNode | null,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
isSVG: boolean,
optimized: boolean
) => {
let el: RendererElement;
let vnodeHook: VNodeHook | undefined | null;
const { type, props, shapeFlag, transition, scopeId, patchFlag, dirs } =
vnode;
if (
vnode.el &&
hostCloneNode !== undefined &&
patchFlag === PatchFlags.HOISTED
) {
/**
* 如果 VNode 有非空的 el,则意味着它正在重复使用
* 只有静态节点可以重复使用,所以它挂载的 DOM 节点应该完全相同
* 可以在这里进行简单的克隆
*/
el = vnode.el = hostCloneNode(vnode.el);
} else {
el = vnode.el = hostCreateElement(
vnode.type as string,
isSVG,
props && props.is
);
// 首先挂载子节点,因为一些 props 可能依赖子内容的渲染,例如:<select value>
if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
hostSetElementText(el, vnode.children as string);
} else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
/**
* 内部会遍历 children 并递归调用 patch 挂载 child
* 调用 patch 而不是 mountElement 的原因是:
* 子节点可能有其他类型的 VNode,比如普通组件
*/
mountChildren(
vnode.children as VNodeArrayChildren,
el,
null,
parentComponent,
parentSuspense,
isSVG && type !== 'foreignObject',
optimized || !!vnode.dynamicChildren
);
}
// 触发节点上绑定的自定义指令的“created”钩子
if (dirs) {
invokeDirectiveHook(vnode, null, parentComponent, 'created');
}
// 处理 props,例如:class、style、event...
if (props) {
for (const key in props) {
if (!isReservedProp(key)) {
hostPatchProp(
el,
key,
null,
props[key],
isSVG,
vnode.children as VNode[],
parentComponent,
parentSuspense,
unmountChildren
);
}
}
if ((vnodeHook = props.onVnodeBeforeMount)) {
invokeVNodeHook(vnodeHook, parentComponent, vnode);
}
}
setScopeId(el, scopeId, vnode, parentComponent);
}
// 触发节点上绑定的自定义指令的“beforeMount”钩子
if (dirs) {
invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
}
// ...
/**
* 把创建的 DOM 挂载到 container 上
* anchor ? parent.insertBefore(child, anchor) : parent.appendChild(child)
*/
hostInsert(el, container, anchor);
// ...
};
/**
* 元素更新 patch-processElement-patchElement
* patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized)
*/
const patchElement = (
n1: VNode,
n2: VNode,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
isSVG: boolean,
optimized: boolean
) => {
const el = (n2.el = n1.el!);
let { patchFlag, dynamicChildren, dirs } = n2;
patchFlag |= n1.patchFlag & PatchFlags.FULL_PROPS;
const oldProps = n1.props || EMPTY_OBJ;
const newProps = n2.props || EMPTY_OBJ;
let vnodeHook: VNodeHook | undefined | null;
if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
}
if (dirs) {
// 触发节点上绑定的自定义指令的“beforeUpdate”钩子
invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
}
if (patchFlag > 0) {
/**
* patchFlag 的存在意味着该元素的 render 代码是由编译器生成的,可以走捷径
* 这种情况下,新旧节点有相同的形状???
*/
if (patchFlag & PatchFlags.FULL_PROPS) {
// 元素绑定了动态 key,需要 diff
patchProps(
el,
n2,
oldProps,
newProps,
parentComponent,
parentSuspense,
isSVG
);
} else {
// 元素绑定了动态 class
if (patchFlag & PatchFlags.CLASS) {
if (oldProps.class !== newProps.class) {
hostPatchProp(el, 'class', null, newProps.class, isSVG);
}
}
// 元素绑定了动态 style
if (patchFlag & PatchFlags.STYLE) {
hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
}
// 元素绑定了动态 prop/attr 而不是 class 和 style
if (patchFlag & PatchFlags.PROPS) {
const propsToUpdate = n2.dynamicProps!;
for (let i = 0; i < propsToUpdate.length; i++) {
const key = propsToUpdate[i];
const prev = oldProps[key];
const next = newProps[key];
if (
next !== prev ||
(hostForcePatchProp && hostForcePatchProp(el, key))
) {
hostPatchProp(
el,
key,
prev,
next,
isSVG,
n1.children as VNode[],
parentComponent,
parentSuspense,
unmountChildren
);
}
}
}
}
// 当前元素仅有动态文本子元素
if (patchFlag & PatchFlags.TEXT) {
if (n1.children !== n2.children) {
hostSetElementText(el, n2.children as string);
}
}
} else if (!optimized && dynamicChildren == null) {
// 没办法优化,全量 diff
patchProps(
el,
n2,
oldProps,
newProps,
parentComponent,
parentSuspense,
isSVG
);
}
const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
if (dynamicChildren) {
// 只需要对比 block 中的动态子节点
patchBlockChildren(
n1.dynamicChildren!,
dynamicChildren,
el,
parentComponent,
parentSuspense,
areChildrenSVG
);
} else if (!optimized) {
// 全量更新子节点
patchChildren(
n1,
n2,
el,
null,
parentComponent,
parentSuspense,
areChildrenSVG
);
}
if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
queuePostRenderEffect(() => {
vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
}, parentSuspense);
}
};
/**
* 更新子节点 patch-processElement-patchElement-patchChildren
* patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG)
*/
const patchChildren: PatchChildrenFn = (
n1,
n2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized = false
) => {
const c1 = n1 && n1.children;
const prevShapeFlag = n1 ? n1.shapeFlag : 0;
const c2 = n2.children;
const { patchFlag, shapeFlag } = n2;
if (patchFlag > 0) {
if (patchFlag & PatchFlags.KEYED_FRAGMENT) {
patchKeyedChildren(
c1 as VNode[],
c2 as VNodeArrayChildren,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
return;
} else if (patchFlag & PatchFlags.UNKEYED_FRAGMENT) {
patchUnkeyedChildren(
c1 as VNode[],
c2 as VNodeArrayChildren,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
return;
}
}
// 子节点有 3 种可能情况:文本、数组、空
if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
// 数组 -> 文本,则删除之前的子节点
if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
unmountChildren(c1 as VNode[], parentComponent, parentSuspense);
}
if (c2 !== c1) {
// 文本对比不同,则替换为新文本
hostSetElementText(container, c2 as string);
}
} else {
if (prevShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
// 之前的子节点是数组
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
// 新的子节点仍然是数组,则做完整地 diff
patchKeyedChildren(
c1 as VNode[],
c2 as VNodeArrayChildren,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
} else {
// 数组 -> 空,则仅仅删除之前的子节点
unmountChildren(c1 as VNode[], parentComponent, parentSuspense, true);
}
} else {
/**
* 之前的子节点是文本节点或者为空
* 新的子节点是数组或者为空
*/
if (prevShapeFlag & ShapeFlags.TEXT_CHILDREN) {
// 如果之前子节点是文本,则把它清空
hostSetElementText(container, '');
}
// 如果新的子节点是数组,则挂载新子节点
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren(
c2 as VNodeArrayChildren,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
);
}
}
}
};
// 完整 diff patch-processElement-patchElement-patchChildren-patchKeyedChildren
const patchKeyedChildren = (
c1: VNode[],
c2: VNodeArrayChildren,
container: RendererElement,
parentAnchor: RendererNode | null,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
isSVG: boolean,
optimized: boolean
) => {
const l2 = c2.length;
let i = 0; // 头部索引
let e1 = c1.length - 1; // 旧子节点列表尾部索引
let e2 = l2 - 1; // 新子节点列表尾部索引
/**
* 1. 同步头部节点(从头部开始,依次对比新旧节点)
* (a b) c
* (a b) d e
*/
while (i <= e1 && i <= e2) {
const n1 = c1[i];
const n2 = (c2[i] = optimized
? cloneIfMounted(c2[i] as VNode)
: normalizeVNode(c2[i]));
// n1.type === n2.type && n1.key === n2.key
if (isSameVNodeType(n1, n2)) {
// 相同节点,递归执行 patch 更新节点
patch(
n1,
n2,
container,
null,
parentComponent,
parentSuspense,
isSVG,
optimized
);
} else {
break;
}
i++;
}
/**
* 2. 同步尾部节点(从尾部开始,依次对比新旧节点)
* a (b c)
* d e (b c)
*/
while (i <= e1 && i <= e2) {
const n1 = c1[e1];
const n2 = (c2[e2] = optimized
? cloneIfMounted(c2[e2] as VNode)
: normalizeVNode(c2[e2]));
if (isSameVNodeType(n1, n2)) {
patch(
n1,
n2,
container,
null,
parentComponent,
parentSuspense,
isSVG,
optimized
);
} else {
break;
}
e1--;
e2--;
}
/**
* 经过“同步头部节点”和“同步尾部节点”,只剩下三种情况要处理:
* 1. 新节点有剩余,要添加剩余节点
* 2. 旧节点有剩余,要删除多余节点
* 3. 未知子序列
*/
if (i > e1) {
if (i <= e2) {
/**
* 3. “新节点有剩余,要添加剩余节点”
* (a b)
* (a b) c
* i = 2, e1 = 1, e2 = 2
* (a b)
* c (a b)
* i = 0, e1 = -1, e2 = 0
*/
const nextPos = e2 + 1;
const anchor = nextPos < l2 ? (c2[nextPos] as VNode).el : parentAnchor;
while (i <= e2) {
patch(
null,
(c2[i] = optimized
? cloneIfMounted(c2[i] as VNode)
: normalizeVNode(c2[i])),
container,
anchor,
parentComponent,
parentSuspense,
isSVG
);
i++;
}
}
} else if (i > e2) {
/**
* 4. “旧节点有剩余,要删除多余节点”
* (a b) c
* (a b)
* i = 2, e1 = 2, e2 = 1
* a (b c)
* (b c)
* i = 0, e1 = 0, e2 = -1
*/
while (i <= e1) {
unmount(c1[i], parentComponent, parentSuspense, true);
i++;
}
} else {
/**
* 5. “未知子序列,可能需要移动”
* [i ... e1 + 1]: a b [c d e] f g
* [i ... e2 + 1]: a b [e d c h] f g
* i = 2, e1 = 4, e2 = 5
*/
const s1 = i; // 旧子节点列表起始索引
const s2 = i; // 新子节点列表起始索引
// 5.1 根据 key 为新子节点构建索引图 {key: index}(空间换时间,O(n^2) 降到 O(n))
const keyToNewIndexMap: Map<string | number, number> = new Map();
for (i = s2; i <= e2; i++) {
const nextChild = (c2[i] = optimized
? cloneIfMounted(c2[i] as VNode)
: normalizeVNode(c2[i]));
if (nextChild.key != null) {
keyToNewIndexMap.set(nextChild.key, i);
}
}
// 5.2 循环剩下的旧子节点,更新匹配的节点,删除不再存在的节点
let j;
let patched = 0;
const toBePatched = e2 - s2 + 1;
let moved = false;
// 用来追踪是否有节点需要移动
let maxNewIndexSoFar = 0;
// 储存新子序列节点的索引和旧子序列节点的索引之间的映射关系,并确定是否有移动
const newIndexToOldIndexMap = new Array(toBePatched);
for (i = 0; i < toBePatched; i++) newIndexToOldIndexMap[i] = 0;
for (i = s1; i <= e1; i++) {
const prevChild = c1[i];
if (patched >= toBePatched) {
// 所有新的子节点都更新过了,所以剩下的删除掉就好
unmount(prevChild, parentComponent, parentSuspense, true);
continue;
}
let newIndex; // 得到旧节点在的新位置
if (prevChild.key != null) {
newIndex = keyToNewIndexMap.get(prevChild.key);
} else {
for (j = s2; j <= e2; j++) {
if (
newIndexToOldIndexMap[j - s2] === 0 &&
isSameVNodeType(prevChild, c2[j] as VNode)
) {
newIndex = j;
break;
}
}
}
if (newIndex === undefined) {
// 旧节点没用(在新节点里没有容身之处)
unmount(prevChild, parentComponent, parentSuspense, true);
} else {
newIndexToOldIndexMap[newIndex - s2] = i + 1;
if (newIndex >= maxNewIndexSoFar) {
maxNewIndexSoFar = newIndex;
} else {
moved = true;
}
patch(
prevChild,
c2[newIndex] as VNode,
container,
null,
parentComponent,
parentSuspense,
isSVG,
optimized
);
patched++;
}
}
// 5.3 移动和挂载,仅当节点已移动时才生成最长稳定递增子序列
const increasingNewIndexSequence = moved
? getSequence(newIndexToOldIndexMap)
: EMPTY_ARR;
j = increasingNewIndexSequence.length - 1;
// 向后循环,以便我们可以使用最后一个修补的节点作为锚点
for (i = toBePatched - 1; i >= 0; i--) {
const nextIndex = s2 + i;
const nextChild = c2[nextIndex] as VNode;
const anchor =
nextIndex + 1 < l2 ? (c2[nextIndex + 1] as VNode).el : parentAnchor;
if (newIndexToOldIndexMap[i] === 0) {
patch(
null,
nextChild,
container,
anchor,
parentComponent,
parentSuspense,
isSVG
);
} else if (moved) {
// 没有最长递增子序列(reverse 场景)或者当前的节点索引不在最长递增子序列中,需要移动
if (j < 0 || i !== increasingNewIndexSequence[j]) {
move(nextChild, container, anchor, MoveType.REORDER);
} else {
j--;
}
}
}
}
};
const patchUnkeyedChildren = (
c1: VNode[],
c2: VNodeArrayChildren,
container: RendererElement,
anchor: RendererNode | null,
parentComponent: ComponentInternalInstance | null,
parentSuspense: SuspenseBoundary | null,
isSVG: boolean,
optimized: boolean
) => {
c1 = c1 || EMPTY_ARR;
c2 = c2 || EMPTY_ARR;
const oldLength = c1.length;
const newLength = c2.length;
const commonLength = Math.min(oldLength, newLength);
let i;
for (i = 0; i < commonLength; i++) {
const nextChild = (c2[i] = optimized
? cloneIfMounted(c2[i] as VNode)
: normalizeVNode(c2[i]));
patch(
c1[i],
nextChild,
container,
null,
parentComponent,
parentSuspense,
isSVG,
optimized
);
}
if (oldLength > newLength) {
// 移除旧的
unmountChildren(
c1,
parentComponent,
parentSuspense,
true,
false,
commonLength
);
} else {
// 挂载新的
mountChildren(
c2,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized,
commonLength
);
}
};
/**
* 组件挂载 patch-processComponent-mountComponent
* mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized)
* 1. 创建组件实例
* 2. 设置组件实例
* 3. 设置组件渲染副作用
*/
const mountComponent: MountComponentFn = (
initialVNode,
container,
anchor,
parentComponent,
parentSuspense,
isSVG,
optimized
) => {
// 创建组件实例
const instance: ComponentInternalInstance = (initialVNode.component =
createComponentInstance(initialVNode, parentComponent, parentSuspense));
// 为 KeepAlive 注入渲染器内部
if (isKeepAlive(initialVNode)) {
(instance.ctx as KeepAliveContext).renderer = internals;
}
setupComponent(instance);
// setup() 是异步的,组件依赖待异步逻辑
setupRenderEffect(
instance,
initialVNode,
container,
anchor,
parentSuspense,
isSVG,
optimized
);
};
export function createComponentInstance(
vnode: VNode,
parent: ComponentInternalInstance | null,
suspense: SuspenseBoundary | null
) {
const type = vnode.type as ConcreteComponent;
// 继承父组件的 appContext;如果是根组件,则直接从根 vnode 中取
const appContext =
(parent ? parent.appContext : vnode.appContext) || emptyAppContext;
// 字面量的方式不同于 2.x 中的 new Vue
const instance: ComponentInternalInstance = {
uid: uid++, // 组件唯一 id
vnode, // 组件 vnode
type, // vnode 节点类型
parent, // 父组件实例
appContext, // 上下文
root: null!, // // 根组件实例,会被立即赋值
next: null, // 新的组件 vnode
subTree: null!, // 子节点/子树,创建后将同步设置
update: null!, // 带副作用更新函数,创建后将同步设置
render: null, // 渲染函数
proxy: null, // 渲染上下文代理
exposed: null,
withProxy: null, // 带有 with 的渲染上下文代理
effects: null, // 响应式相关对象
provides: parent ? parent.provides : Object.create(appContext.provides), // 从父级继承 provides
accessCache: null!, // 渲染代理的属性访问缓存
renderCache: [], // 渲染缓存
components: null, // 注册的组件
directives: null, // 注册的指令
propsOptions: normalizePropsOptions(type, appContext),
emitsOptions: normalizeEmitsOptions(type, appContext),
emit: null as any, // 会被立即赋值
emitted: null,
// 组件 state 相关
ctx: EMPTY_OBJ,
data: EMPTY_OBJ,
props: EMPTY_OBJ,
attrs: EMPTY_OBJ,
slots: EMPTY_OBJ,
refs: EMPTY_OBJ,
setupState: EMPTY_OBJ, // setup 返回的响应式状态
setupContext: null, // setup 上下文数据
// 组件 suspense 相关
suspense,
suspenseId: suspense ? suspense.pendingId : 0,
asyncDep: null, // suspense 异步依赖
asyncResolved: false, // suspense 异步依赖是否都已处理
// 生命周期钩子,不用枚举类型是因为会导致计算属性???
isMounted: false,
isUnmounted: false,
isDeactivated: false,
bc: null,
c: null,
bm: null,
m: null,
bu: null,
u: null,
um: null,
bum: null,
da: null,
a: null,
rtg: null,
rtc: null,
ec: null
};
instance.ctx = { _: instance }; // 实例上下文
instance.root = parent ? parent.root : instance; // 指向根组件的指针
instance.emit = emit.bind(null, instance); // emit 方法
return instance;
}
export function setupComponent(
instance: ComponentInternalInstance,
isSSR = false
) {
isInSSRComponentSetup = isSSR;
const { props, children, shapeFlag } = instance.vnode;
// 是否是一个有状态的组件
const isStateful = shapeFlag & ShapeFlags.STATEFUL_COMPONENT;
// 初始化 props/attrs
initProps(instance, props, isStateful, isSSR);
// 初始化 slots
initSlots(instance, children);
// 获取 setup 返回值
const setupResult = isStateful
? setupStatefulComponent(instance, isSSR)
: undefined;
isInSSRComponentSetup = false;
return setupResult;
}
function setupStatefulComponent(
instance: ComponentInternalInstance,
isSSR: boolean
) {
const Component = instance.type as ComponentOptions;
// 创建渲染代理的属性访问缓存
instance.accessCache = Object.create(null);
// 创建公共实例/渲染代理
instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
const { setup } = Component;
if (setup) {
// 创建 setup 上下文
const setupContext = (instance.setupContext =
// {attrs、slots、emit、expose}
setup.length > 1 ? createSetupContext(instance) : null);
currentInstance = instance;
pauseTracking();
// 调用 setup
const setupResult = callWithErrorHandling(
setup,
instance,
ErrorCodes.SETUP_FUNCTION,
[instance.props, setupContext]
);
resetTracking();
currentInstance = null;
// 处理 setup 结果
if (isPromise(setupResult)) {
// ...
} else {
/**
* 如果 setupResult 是 VNode,报错
* 如果 setupResult 是函数,instance.render = setupResult
* 如果 setupResult 是对象,instance.setupState = proxyRefs(setupResult)
*/
handleSetupResult(instance, setupResult, isSSR);
}
} else {
/**
* 设置 instance.render
* 创建 instance.withProxy
* 兼容 OptionsAPI
*/
finishComponentSetup(instance, isSSR);
}
}
/**
* patch-processComponent-mountComponent-setupRenderEffect
* 初次渲染组件的时候,会在组件实例上创建一个渲染副作用(包含了挂载副作用和更新副作用)
* 在 updateComponent 时会调用 instance.update
* setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized)
*/
const setupRenderEffect: SetupRenderEffectFn = (
instance,
initialVNode,
container,
anchor,
parentSuspense,
isSVG,
optimized
) => {
instance.update = effect(
// 组件 effect 的回调函数
function componentEffect() {
if (!instance.isMounted) {
let vnodeHook: VNodeHook | null | undefined;
const { el, props } = initialVNode;
const { bm, m, parent } = instance;
if (bm) {
invokeArrayFns(bm); // 触发 beforeMount
}
if ((vnodeHook = props && props.onVnodeBeforeMount)) {
invokeVNodeHook(vnodeHook, parent, initialVNode);
}
/**
* 渲染组件生成的子树
* subTree(_vnode):组件内部整个 DOM 节点对应的 VNode;
* initialVNode($vnode):组件 VNode。
* renderComponentRoot 执行组件 render 函数创建整个组件树内部的 VNode;
* 把这个 VNode 再经过内部一层标准化,就得到了该函数的返回结果:subTree。
*/
const subTree = (instance.subTree = renderComponentRoot(instance));
if (el && hydrateNode) {
hydrateNode(
initialVNode.el as Node,
subTree,
instance,
parentSuspense
);
} else {
// 把 subTree 挂载到 container 中
patch(
null,
subTree,
container,
anchor,
instance,
parentSuspense,
isSVG
);
initialVNode.el = subTree.el;
}
if (m) {
queuePostRenderEffect(m, parentSuspense); // 触发 mounted
}
if ((vnodeHook = props && props.onVnodeMounted)) {
const scopedInitialVNode = initialVNode;
queuePostRenderEffect(() => {
invokeVNodeHook(vnodeHook!, parent, scopedInitialVNode);
}, parentSuspense);
}
const { a } = instance;
if (
a &&
initialVNode.shapeFlag & ShapeFlags.COMPONENT_SHOULD_KEEP_ALIVE
) {
queuePostRenderEffect(a, parentSuspense);
}
instance.isMounted = true;
initialVNode = container = anchor = null as any;
} else {
// 更新组件,组件自身状态的改变触发或者父组件调用 processComponent
let { next, bu, u, parent, vnode } = instance;
let originNext = next;
let vnodeHook: VNodeHook | null | undefined;
if (next) {
// next 表示组件新的 VNode
next.el = vnode.el;
// 更新组件 vnode 节点信息
updateComponentPreRender(instance, next, optimized);
} else {
next = vnode;
}
if (bu) {
invokeArrayFns(bu); // 触发 beforeUpdate
}
if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
invokeVNodeHook(vnodeHook, parent, next, vnode);
}
const nextTree = renderComponentRoot(instance); // 渲染新的子树 VNode
const prevTree = instance.subTree; // 缓存旧的子树 VNode
instance.subTree = nextTree; // 根据新旧子树 VNode 做 patch
// 核心逻辑,根据新旧子树 vnode 做 patch
patch(
prevTree,
nextTree,
// 如果在 Teleport 中,父级可能改变
hostParentNode(prevTree.el!)!,
// 如果在 Fragment 中,锚点可能改变
getNextHostNode(prevTree),
instance,
parentSuspense,
isSVG
);
next.el = nextTree.el;
if (originNext === null) {
updateHOCHostEl(instance, nextTree.el);
}
if (u) {
queuePostRenderEffect(u, parentSuspense); // 触发 updated
}
// onVnodeUpdated
if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
queuePostRenderEffect(() => {
invokeVNodeHook(vnodeHook!, parent, next!, vnode);
}, parentSuspense);
}
}
},
{
// 递归的原因:在子组件修改(在非生命周期内)注入(inject)的 ref 值,没有响应式
allowRecurse: true,
scheduler: queueJob
}
);
};
/**
* 组件更新 patch-processComponent-updateComponent
* updateComponent(n1, n2, optimized)
*/
const updateComponent = (n1: VNode, n2: VNode, optimized: boolean) => {
const instance = (n2.component = n1.component)!;
// 是否应该更新
if (shouldUpdateComponent(n1, n2, optimized)) {
if (instance.asyncDep && !instance.asyncResolved) {
updateComponentPreRender(instance, n2, optimized);
return;
} else {
instance.next = n2;
// 子组件也可能因为数据变化被添加到更新队列里了,移除它们防止对一个子组件重复更新
invalidateJob(instance.update);
// instance.update 是副作用 runner
instance.update();
}
} else {
// 没啥需要更新,把属性拷贝过去
n2.component = n1.component;
n2.el = n1.el;
instance.vnode = n2;
}
};
// patch-processComponent-updateComponent-updateComponentPreRender
const updateComponentPreRender = (
instance: ComponentInternalInstance,
nextVNode: VNode,
optimized: boolean
) => {
// 新组件 vnode 的 component 属性指向组件实例
nextVNode.component = instance;
// 旧组件 vnode 的 props 属性
const prevProps = instance.vnode.props;
// 组件实例的 vnode 属性指向新的组件 vnode
instance.vnode = nextVNode;
// 清空 next 属性,为了下一次重新渲染准备
instance.next = null;
// 更新 props
updateProps(instance, nextVNode.props, prevProps, optimized);
// 更新插槽
updateSlots(instance, nextVNode.children);
flushPreFlushCbs(undefined, instance.update);
};
// 渲染代理 proxy 配置
export const PublicInstanceProxyHandlers: ProxyHandler<any> = {
get({ _: instance }: ComponentRenderContext, key: string) {
const { ctx, setupState, data, props, accessCache, type, appContext } =
instance;
// @vue/reactivity 永远不应该观察 Vue 公共实例
if (key === ReactiveFlags.SKIP) {
return true;
}
// 在渲染期间,对访问渲染上下文的任何属性的访问都会调用 getter
let normalizedProps;
// 如果 key 不以 $ 开头
if (key[0] !== '$') {
const n = accessCache![key]; // 缓存
if (n !== undefined) {
// setupState >> data >> ctx >> props
switch (n) {
case AccessTypes.SETUP:
// setupState 是 setup 返回的数据
return setupState[key];
case AccessTypes.DATA:
return data[key];
case AccessTypes.CONTEXT:
return ctx[key];
case AccessTypes.PROPS:
return props![key];
}
} else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
accessCache![key] = AccessTypes.SETUP;
return setupState[key];
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
accessCache![key] = AccessTypes.DATA;
return data[key];
} else if (
(normalizedProps = instance.propsOptions[0]) &&
hasOwn(normalizedProps, key)
) {
accessCache![key] = AccessTypes.PROPS;
return props![key];
} else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
accessCache![key] = AccessTypes.CONTEXT;
return ctx[key];
} else if (!__FEATURE_OPTIONS_API__ || !isInBeforeCreate) {
accessCache![key] = AccessTypes.OTHER;
}
}
const publicGetter = publicPropertiesMap[key];
let cssModule, globalProperties;
// $xxx 属性
if (publicGetter) {
if (key === '$attrs') {
track(instance, TrackOpTypes.GET, key);
}
return publicGetter(instance);
} else if (
(cssModule = type.__cssModules) &&
(cssModule = cssModule[key])
) {
return cssModule;
} else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
// 用户可能会在 this 上挂 $自定义属性
accessCache![key] = AccessTypes.CONTEXT;
return ctx[key];
} else if (
// 全局属性
((globalProperties = appContext.config.globalProperties),
hasOwn(globalProperties, key))
) {
return globalProperties[key];
}
},
set(
{ _: instance }: ComponentRenderContext,
key: string,
value: any
): boolean {
const { data, setupState, ctx } = instance;
if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
setupState[key] = value;
} else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
data[key] = value;
}
if (key[0] === '$' && key.slice(1) in instance) {
return false;
} else {
ctx[key] = value;
}
return true;
},
has(
{
_: { data, setupState, accessCache, ctx, appContext, propsOptions }
}: ComponentRenderContext,
key: string
) {
let normalizedProps;
return (
accessCache![key] !== undefined ||
(data !== EMPTY_OBJ && hasOwn(data, key)) ||
(setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
hasOwn(ctx, key) ||
hasOwn(publicPropertiesMap, key) ||
hasOwn(appContext.config.globalProperties, key)
);
}
};
|