runtime-core 实现

第一步

packages/runtime-core/package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"name": "@vue/runtime-core",
"version": "1.0.0",
"module": "dist/runtime-core.esm-bundler.js",
"unpkg": "dist/runtime-core.global.js",
"buildOptions": {
"name": "RuntimeCore",
"formats": [
"esm-bundler",
"esm-browser",
"cjs",
"global"
]
},
"dependencies": {
"@vue/reactivity": "workspace:^1.0.0",
"@vue/shared": "workspace:^1.0.0"
}
}

由于 runtime-dom 依赖了 runtime-core,因此需要在 runtime-dom 中安装一下,pnpm i @vue/runtime-core@workspace --filter @vue/runtime-dom

runtime-core 依赖了 reactivity,因此执行 pnpm i @vue/reactivity@workspace @vue/shared@workspace --filter @vue/runtime-core

第二步

实现 createRenderer 函数

packages/runtime-core/src/index.ts

1
export * from './renderer';

packages/runtime-core/src/renderer.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
import { ShapeFlags } from '@vue/shared';
import { Fragment, isSameVnode, Text } from './createVnode';
import getSequence from './seq';

export function createRenderer(renderOptions) {
const {
insert: hostInsert,
remove: hostRemove,
createElement: hostCreateElement,
createText: hostCreateText,
setText: hostSetText,
setElementText: hostSetElementText,
parentNode: hostParentNode,
nextSibling: hostNextSibling,
patchProp: hostPatchProp,
} = renderOptions;

const mountChildren = (children, container) => {
for (let i = 0; i < children.length; i++) {
patch(null, children[i], container);
}
};

const mountElement = (vnode, container, anchor) => {
const { type, children, props, shapeFlag } = vnode;
const el = vnode.el = hostCreateElement(type);
if (props) {
for (const key in props) {
hostPatchProp(el, key, null, props[key]);
}
}

if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
hostSetElementText(el, children);
} else if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren(children, el);
}

hostInsert(el, container, anchor);
};

const processElement = (n1, n2, container, anchor) => {
if (n1 === null) {
mountElement(n2, container, anchor);
} else {
patchElement(n1, n2, container);
}
};

const processText = (n1, n2, container) => {
if (n1 === null) {
hostInsert(n2.el = hostCreateText(n2.children), container);
} else {
const el = n2.el = n1.el;
if (n1.children !== n2.children) {
hostSetText(el, n2.children);
}
}
};

const processFragment = (n1, n2, container) => {
if (n1 === null) {
mountChildren(n2.children, container);
} else {
patchChildren(n1, n2, container);
}
};

const patchProps = (oldProps, newProps, el) => {
for (const key in newProps) {
hostPatchProp(el, key, oldProps[key], newProps[key]);
}

for (const key in oldProps) {
if (!(key in newProps)) {
hostPatchProp(el, key, oldProps[key], null);
}
}
};

const unmountChildren = (children) => {
for (let i = 0; i < children.length; i++) {
const child = children[i];
unmount(child);
}
};

const patchKeyChildren = (c1, c2, el) => {
let i = 0;
let e1 = c1.length - 1;
let e2 = c2.length - 1;

// 从头开始比较
while (i <= e1 && i <= e2) {
const n1 = c1[i];
const n2 = c2[i];

if (isSameVnode(n1, n2)) {
patch(n1, n2, el);
} else {
break;
}
i++;
}

// 从尾部比较
while (i <= e1 && i <= e2) {
const n1 = c1[e1];
const n2 = c2[e2];
if (isSameVnode(n1, n2)) {
patch(n1, n2, el);
} else {
break;
}
e1--;
e2--;
}

if (i > e1) {
// 新的多
if (i <= e2) {
// 查看当前元素的下一个元素是否存在
const nextPos = e2 + 1;
const anchor = c2[nextPos]?.el;
while (i <= e2) {
patch(null, c2[i], el, anchor);
i++;
}
}
} else if (i > e2) {
// 老的多
if (i <= e1) {
while (i <= e1) {
// 删除老的
unmount(c1[i]);
i++;
}
}
} else {
// 上面两个判断,是确认没有变化的节点,同时处理了插入和删除
// 上面比完了开头和结尾,下面是比较中间部分
// 比较中间部分的时候,是拿新的去老的里面找,如果找到的话,就用老的,没有找到的话,就新建
let s1 = i;
let s2 = i;

// 创建一个映射表,保存新的,用于查找老的在新的里面是否还有,如果有的话,就更新,没有的话,就删除
const keyToNewIndexMap = new Map();
// 要插入的个数
const toBePatched = e2 - s2 + 1;
let newIndexToOldMapIndex = new Array(toBePatched).fill(0);

for (let j = s2; j <= e2; j++) {
const vnode = c2[j];
keyToNewIndexMap.set(vnode.key, j);
}

for (let j = s1; j <= e1; j++) {
const vnode = c1[j];
const newIndex = keyToNewIndexMap.get(vnode.key);
if (newIndex === undefined) {
// 在新的里面找不到老的
unmount(vnode);
} else {
// 比较前后节点的差异,更新属性和儿子
newIndexToOldMapIndex[newIndex - s2] = j + 1;
patch(vnode, c2[newIndex], el);
}
}

const increasingSeq = getSequence(newIndexToOldMapIndex);

let j = increasingSeq.length - 1;

// 调整顺序,按照新的,使用 insertBefore 倒序插入
for (let i = toBePatched - 1; i >= 0; i--) {
const newIndex = s2 + i;
const anchor = c2[newIndex + 1]?.el;

const vnode = c2[newIndex];

// 如果是需要新建的,那么 el 这个属性的值是空的
if (!vnode.el) {
patch(null, vnode, el, anchor);
} else {
if (i === increasingSeq[j]) {
j--;
} else {
hostInsert(vnode.el, el, anchor);
}
}

}
}
};

const patchChildren = (n1, n2, el) => {
const c1 = n1.children;
const c2 = n2.children;

const preShapeFlag = n1.shapeFlag;
const shapeFlag = n2.shapeFlag;

if (shapeFlag & ShapeFlags.TEXT_CHILDREN) {
// 新的是文本,老的是数组,移除老的
if (preShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
unmountChildren(c1);
}

// 新的是文本,老的也是文本,替换内容
if (c1 !== c2) {
hostSetElementText(el, c2);
}
} else {
if (preShapeFlag & ShapeFlags.ARRAY_CHILDREN) {
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
// 老的是数组,新的也是数组,那就全量 diff 算法,是两个数组的比对
patchKeyChildren(c1, c2, el);
} else {
// 老的是数组,新的不是数组,移除老的
unmountChildren(c1);
}
} else {
// 老的是文本,新的是空
if (preShapeFlag & ShapeFlags.TEXT_CHILDREN) {
hostSetElementText(el, '');
}

// 老的是文本,新的是数组
if (shapeFlag & ShapeFlags.ARRAY_CHILDREN) {
mountChildren(c2, el);
}
}
}
};

const patchElement = (n1, n2, container) => {
const el = n2.el = n1.el;
const oldProps = n1.props || {};
const newProps = n2.props || {};
patchProps(oldProps, newProps, el);
patchChildren(n1, n2, el);
};

// 渲染和更新都走这里
const patch = (n1, n2, container, anchor = null) => {
if (n1 === n2) {
return;
}
if (n1 && !isSameVnode(n1, n2)) {
unmount(n1);
n1 = null;
}

const { type } = n2;

switch (type) {
case Text:
processText(n1, n2, container);
break;
case Fragment:
processFragment(n1, n2, container);
break;
default:
processElement(n1, n2, container, anchor);
}
};

const unmount = (vnode) => {
if (vnode.type === Fragment) {
unmountChildren(vnode.children)
} else {
hostRemove(vnode.el);
}
}

// 多次调用 render,会进行虚拟节点的比较,然后再进行更新
const render = (vnode, container) => {
if (vnode === null) {
if (container._vnode) {
unmount(container._vnode);
}
} else {
patch(container._vnode || null, vnode, container);
container._vnode = vnode;
}
};
return {
render
};
}

packages/runtime-core/src/seq.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
export default function getSequence(arr) {
const result = [ 0 ];
const p = result.slice(0);
let start;
let end;
let middle;
const len = arr.length;
for (let i = 0; i < len; i++) {
const arrI = arr[i];
if (arrI !== 0) {
const resultLastIndex = result[result.length - 1];
if (arr[resultLastIndex] < arrI) {
p[i] = result[result.length - 1];
result.push(i);
continue;
}
}

start = 0;
end = result.length - 1;

while (start < end) {
middle = ((start + end) / 2) | 0;
if (arr[result[middle]] < arrI) {
start = middle + 1;
} else {
end = middle;
}
}

if (arrI < arr[result[start]]) {
p[i] = result[start - 1];
result[start] = i;
}
}

let l = result.length;
let last = result[l - 1];

while (l-- > 0) {
result[l] = last;
last = p[last];
}

return result;
}

packages/shared/src/shapeFlags.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
export enum ShapeFlags {
ELEMENT = 1,
FUNCTIONAL_COMPONENT = 1 << 1,
STATEFUL_COMPONENT = 1 << 2,
TEXT_CHILDREN = 1 << 3,
ARRAY_CHILDREN = 1 << 4,
SLOTS_CHILDREN = 1 << 5,
TELEPORT = 1 << 6,
SUSPENSE = 1 << 7,
COMPONENT_SHOULD_KEEP_ALIVE = 1 << 8,
COMPONENT_KEPT_ALIVE = 1 << 9,
COMPONENT = ShapeFlags.STATEFUL_COMPONENT | ShapeFlags.FUNCTIONAL_COMPONENT,
}

packages/shared/src/index.ts

1
2
3
export * from './shapeFlags';

...

patchKeyChildren 函数中实现的 diff 算法

  1. 在比较新的和老的时候,由于两个都是数组,所以比较的时候,先从头开始比较,当遇到不一样的节点的时候,就结束当前比较,再从尾部开始比较,然后确定范围
  2. 在比较的时候,如果有多余的或者新增的话,就直接操作即可,在比较的时候,是同层比较,一层一层的比较,递归进行的