UNPKG

9.86 kBJavaScriptView Raw
1import { diff, unmount, applyRef } from './index';
2import { createVNode, Fragment } from '../create-element';
3import { EMPTY_OBJ, EMPTY_ARR } from '../constants';
4import { removeNode } from '../util';
5import { getDomSibling } from '../component';
6
7/**
8 * Diff the children of a virtual node
9 * @param {import('../internal').PreactElement} parentDom The DOM element whose
10 * children are being diffed
11 * @param {import('../index').ComponentChildren[]} renderResult
12 * @param {import('../internal').VNode} newParentVNode The new virtual
13 * node whose children should be diff'ed against oldParentVNode
14 * @param {import('../internal').VNode} oldParentVNode The old virtual
15 * node whose children should be diff'ed against newParentVNode
16 * @param {object} globalContext The current context object - modified by getChildContext
17 * @param {boolean} isSvg Whether or not this DOM node is an SVG node
18 * @param {Array<import('../internal').PreactElement>} excessDomChildren
19 * @param {Array<import('../internal').Component>} commitQueue List of components
20 * which have callbacks to invoke in commitRoot
21 * @param {Node | Text} oldDom The current attached DOM
22 * element any new dom elements should be placed around. Likely `null` on first
23 * render (except when hydrating). Can be a sibling DOM element when diffing
24 * Fragments that have siblings. In most cases, it starts out as `oldChildren[0]._dom`.
25 * @param {boolean} isHydrating Whether or not we are in hydration
26 */
27export function diffChildren(
28 parentDom,
29 renderResult,
30 newParentVNode,
31 oldParentVNode,
32 globalContext,
33 isSvg,
34 excessDomChildren,
35 commitQueue,
36 oldDom,
37 isHydrating
38) {
39 let i, j, oldVNode, childVNode, newDom, sibDom, firstChildDom, refs;
40
41 // This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR
42 // as EMPTY_OBJ._children should be `undefined`.
43 let oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;
44
45 let oldChildrenLength = oldChildren.length;
46
47 // Only in very specific places should this logic be invoked (top level `render` and `diffElementNodes`).
48 // I'm using `EMPTY_OBJ` to signal when `diffChildren` is invoked in these situations. I can't use `null`
49 // for this purpose, because `null` is a valid value for `oldDom` which can mean to skip to this logic
50 // (e.g. if mounting a new tree in which the old DOM should be ignored (usually for Fragments).
51 if (oldDom == EMPTY_OBJ) {
52 if (excessDomChildren != null) {
53 oldDom = excessDomChildren[0];
54 } else if (oldChildrenLength) {
55 oldDom = getDomSibling(oldParentVNode, 0);
56 } else {
57 oldDom = null;
58 }
59 }
60
61 newParentVNode._children = [];
62 for (i = 0; i < renderResult.length; i++) {
63 childVNode = renderResult[i];
64
65 if (childVNode == null || typeof childVNode == 'boolean') {
66 childVNode = newParentVNode._children[i] = null;
67 }
68 // If this newVNode is being reused (e.g. <div>{reuse}{reuse}</div>) in the same diff,
69 // or we are rendering a component (e.g. setState) copy the oldVNodes so it can have
70 // it's own DOM & etc. pointers
71 else if (typeof childVNode == 'string' || typeof childVNode == 'number') {
72 childVNode = newParentVNode._children[i] = createVNode(
73 null,
74 childVNode,
75 null,
76 null,
77 childVNode
78 );
79 } else if (Array.isArray(childVNode)) {
80 childVNode = newParentVNode._children[i] = createVNode(
81 Fragment,
82 { children: childVNode },
83 null,
84 null,
85 null
86 );
87 } else if (childVNode._dom != null || childVNode._component != null) {
88 childVNode = newParentVNode._children[i] = createVNode(
89 childVNode.type,
90 childVNode.props,
91 childVNode.key,
92 null,
93 childVNode._original
94 );
95 } else {
96 childVNode = newParentVNode._children[i] = childVNode;
97 }
98
99 // Terser removes the `continue` here and wraps the loop body
100 // in a `if (childVNode) { ... } condition
101 if (childVNode == null) {
102 continue;
103 }
104
105 childVNode._parent = newParentVNode;
106 childVNode._depth = newParentVNode._depth + 1;
107
108 // Check if we find a corresponding element in oldChildren.
109 // If found, delete the array item by setting to `undefined`.
110 // We use `undefined`, as `null` is reserved for empty placeholders
111 // (holes).
112 oldVNode = oldChildren[i];
113
114 if (
115 oldVNode === null ||
116 (oldVNode &&
117 childVNode.key == oldVNode.key &&
118 childVNode.type === oldVNode.type)
119 ) {
120 oldChildren[i] = undefined;
121 } else {
122 // Either oldVNode === undefined or oldChildrenLength > 0,
123 // so after this loop oldVNode == null or oldVNode is a valid value.
124 for (j = 0; j < oldChildrenLength; j++) {
125 oldVNode = oldChildren[j];
126 // If childVNode is unkeyed, we only match similarly unkeyed nodes, otherwise we match by key.
127 // We always match by type (in either case).
128 if (
129 oldVNode &&
130 childVNode.key == oldVNode.key &&
131 childVNode.type === oldVNode.type
132 ) {
133 oldChildren[j] = undefined;
134 break;
135 }
136 oldVNode = null;
137 }
138 }
139
140 oldVNode = oldVNode || EMPTY_OBJ;
141
142 // Morph the old element into the new one, but don't append it to the dom yet
143 newDom = diff(
144 parentDom,
145 childVNode,
146 oldVNode,
147 globalContext,
148 isSvg,
149 excessDomChildren,
150 commitQueue,
151 oldDom,
152 isHydrating
153 );
154
155 if ((j = childVNode.ref) && oldVNode.ref != j) {
156 if (!refs) refs = [];
157 if (oldVNode.ref) refs.push(oldVNode.ref, null, childVNode);
158 refs.push(j, childVNode._component || newDom, childVNode);
159 }
160
161 // Only proceed if the vnode has not been unmounted by `diff()` above.
162 if (newDom != null) {
163 if (firstChildDom == null) {
164 firstChildDom = newDom;
165 }
166
167 let nextDom;
168 if (childVNode._nextDom !== undefined) {
169 // Only Fragments or components that return Fragment like VNodes will
170 // have a non-undefined _nextDom. Continue the diff from the sibling
171 // of last DOM child of this child VNode
172 nextDom = childVNode._nextDom;
173
174 // Eagerly cleanup _nextDom. We don't need to persist the value because
175 // it is only used by `diffChildren` to determine where to resume the diff after
176 // diffing Components and Fragments. Once we store it the nextDOM local var, we
177 // can clean up the property
178 childVNode._nextDom = undefined;
179 } else if (
180 excessDomChildren == oldVNode ||
181 newDom != oldDom ||
182 newDom.parentNode == null
183 ) {
184 // NOTE: excessDomChildren==oldVNode above:
185 // This is a compression of excessDomChildren==null && oldVNode==null!
186 // The values only have the same type when `null`.
187
188 outer: if (oldDom == null || oldDom.parentNode !== parentDom) {
189 parentDom.appendChild(newDom);
190 nextDom = null;
191 } else {
192 // `j<oldChildrenLength; j+=2` is an alternative to `j++<oldChildrenLength/2`
193 for (
194 sibDom = oldDom, j = 0;
195 (sibDom = sibDom.nextSibling) && j < oldChildrenLength;
196 j += 2
197 ) {
198 if (sibDom == newDom) {
199 break outer;
200 }
201 }
202 parentDom.insertBefore(newDom, oldDom);
203 nextDom = oldDom;
204 }
205
206 // Browsers will infer an option's `value` from `textContent` when
207 // no value is present. This essentially bypasses our code to set it
208 // later in `diff()`. It works fine in all browsers except for IE11
209 // where it breaks setting `select.value`. There it will be always set
210 // to an empty string. Re-applying an options value will fix that, so
211 // there are probably some internal data structures that aren't
212 // updated properly.
213 //
214 // To fix it we make sure to reset the inferred value, so that our own
215 // value check in `diff()` won't be skipped.
216 if (newParentVNode.type == 'option') {
217 parentDom.value = '';
218 }
219 }
220
221 // If we have pre-calculated the nextDOM node, use it. Else calculate it now
222 // Strictly check for `undefined` here cuz `null` is a valid value of `nextDom`.
223 // See more detail in create-element.js:createVNode
224 if (nextDom !== undefined) {
225 oldDom = nextDom;
226 } else {
227 oldDom = newDom.nextSibling;
228 }
229
230 if (typeof newParentVNode.type == 'function') {
231 // Because the newParentVNode is Fragment-like, we need to set it's
232 // _nextDom property to the nextSibling of its last child DOM node.
233 //
234 // `oldDom` contains the correct value here because if the last child
235 // is a Fragment-like, then oldDom has already been set to that child's _nextDom.
236 // If the last child is a DOM VNode, then oldDom will be set to that DOM
237 // node's nextSibling.
238
239 newParentVNode._nextDom = oldDom;
240 }
241 } else if (
242 oldDom &&
243 oldVNode._dom == oldDom &&
244 oldDom.parentNode != parentDom
245 ) {
246 // The above condition is to handle null placeholders. See test in placeholder.test.js:
247 // `efficiently replace null placeholders in parent rerenders`
248 oldDom = getDomSibling(oldVNode);
249 }
250 }
251
252 newParentVNode._dom = firstChildDom;
253
254 // Remove children that are not part of any vnode.
255 if (excessDomChildren != null && typeof newParentVNode.type != 'function') {
256 for (i = excessDomChildren.length; i--; ) {
257 if (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);
258 }
259 }
260
261 // Remove remaining oldChildren if there are any.
262 for (i = oldChildrenLength; i--; ) {
263 if (oldChildren[i] != null) unmount(oldChildren[i], oldChildren[i]);
264 }
265
266 // Set refs only after unmount
267 if (refs) {
268 for (i = 0; i < refs.length; i++) {
269 applyRef(refs[i], refs[++i], refs[++i]);
270 }
271 }
272}
273
274/**
275 * Flatten and loop through the children of a virtual node
276 * @param {import('../index').ComponentChildren} children The unflattened
277 * children of a virtual node
278 * @returns {import('../internal').VNode[]}
279 */
280export function toChildArray(children) {
281 if (children == null || typeof children == 'boolean') {
282 return [];
283 } else if (Array.isArray(children)) {
284 return EMPTY_ARR.concat.apply([], children.map(toChildArray));
285 }
286
287 return [children];
288}