Skip to content

Commit 29ca6d1

Browse files
devknollAndrewKushnir
authored andcommitted
fix(core): improve support for i18n hydration of projected content (#56192)
When collecting nodes from the DOM for hydration, we need to treat nodes with paths (e.g. content projection) as the new root for all subsequent elements, not just the next one. Additionally, when using content projection it's possible for translated content to become disconnected, e.g. when it doesn't match a selector and there isn't a default. We need to handle such cases by manipulating the disconnected node data associated with hydration as usual. PR Close #56192
1 parent 3ea7794 commit 29ca6d1

5 files changed

Lines changed: 471 additions & 79 deletions

File tree

‎packages/core/src/hydration/annotate.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {APP_ID} from '../application/application_tokens';
1111
import {isDetachedByI18n} from '../i18n/utils';
1212
import {ViewEncapsulation} from '../metadata';
1313
import {Renderer2} from '../render';
14+
import {assertTNode} from '../render3/assert';
1415
import {collectNativeNodes, collectNativeNodesInLContainer} from '../render3/collect_native_nodes';
1516
import {getComponentDef} from '../render3/definition';
1617
import {CONTAINER_HEADER_OFFSET, LContainer} from '../render3/interfaces/container';
@@ -362,16 +363,20 @@ function appendSerializedNodePath(
362363
) {
363364
const noOffsetIndex = tNode.index - HEADER_OFFSET;
364365
ngh[NODES] ??= {};
365-
ngh[NODES][noOffsetIndex] = calcPathForNode(tNode, lView, excludedParentNodes);
366+
// Ensure we don't calculate the path multiple times.
367+
ngh[NODES][noOffsetIndex] ??= calcPathForNode(tNode, lView, excludedParentNodes);
366368
}
367369

368370
/**
369371
* Helper function to append information about a disconnected node.
370372
* This info is needed at runtime to avoid DOM lookups for this element
371373
* and instead, the element would be created from scratch.
372374
*/
373-
function appendDisconnectedNodeIndex(ngh: SerializedView, tNode: TNode) {
374-
const noOffsetIndex = tNode.index - HEADER_OFFSET;
375+
function appendDisconnectedNodeIndex(ngh: SerializedView, tNodeOrNoOffsetIndex: TNode | number) {
376+
const noOffsetIndex =
377+
typeof tNodeOrNoOffsetIndex === 'number'
378+
? tNodeOrNoOffsetIndex
379+
: tNodeOrNoOffsetIndex.index - HEADER_OFFSET;
375380
ngh[DISCONNECTED_NODES] ??= [];
376381
if (!ngh[DISCONNECTED_NODES].includes(noOffsetIndex)) {
377382
ngh[DISCONNECTED_NODES].push(noOffsetIndex);
@@ -404,7 +409,18 @@ function serializeLView(lView: LView, context: HydrationContext): SerializedView
404409
const i18nData = trySerializeI18nBlock(lView, i, context);
405410
if (i18nData) {
406411
ngh[I18N_DATA] ??= {};
407-
ngh[I18N_DATA][noOffsetIndex] = i18nData;
412+
ngh[I18N_DATA][noOffsetIndex] = i18nData.caseQueue;
413+
414+
for (const nodeNoOffsetIndex of i18nData.disconnectedNodes) {
415+
appendDisconnectedNodeIndex(ngh, nodeNoOffsetIndex);
416+
}
417+
418+
for (const nodeNoOffsetIndex of i18nData.disjointNodes) {
419+
const tNode = tView.data[nodeNoOffsetIndex + HEADER_OFFSET] as TNode;
420+
ngDevMode && assertTNode(tNode);
421+
appendSerializedNodePath(ngh, tNode, lView, i18nChildren);
422+
}
423+
408424
continue;
409425
}
410426

‎packages/core/src/hydration/i18n.ts‎

Lines changed: 148 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,19 @@
88

99
import {inject, Injector} from '../di';
1010
import {isRootTemplateMessage} from '../render3/i18n/i18n_util';
11-
import {I18nNode, I18nNodeKind, I18nPlaceholderType, TI18n} from '../render3/interfaces/i18n';
12-
import {TNode, TNodeType} from '../render3/interfaces/node';
11+
import {createIcuIterator} from '../render3/instructions/i18n_icu_container_visitor';
12+
import {I18nNode, I18nNodeKind, I18nPlaceholderType, TI18n, TIcu} from '../render3/interfaces/i18n';
13+
import {isTNodeShape, TNode, TNodeType} from '../render3/interfaces/node';
1314
import type {Renderer} from '../render3/interfaces/renderer';
1415
import type {RNode} from '../render3/interfaces/renderer_dom';
1516
import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView, TVIEW} from '../render3/interfaces/view';
16-
import {nativeRemoveNode} from '../render3/node_manipulation';
17+
import {getFirstNativeNode, nativeRemoveNode} from '../render3/node_manipulation';
1718
import {unwrapRNode} from '../render3/util/view_utils';
1819
import {assertDefined, assertNotEqual} from '../util/assert';
1920

2021
import type {HydrationContext} from './annotate';
2122
import {DehydratedIcuData, DehydratedView, I18N_DATA} from './interfaces';
22-
import {locateNextRNode, tryLocateRNodeByPath} from './node_lookup_utils';
23+
import {isDisconnectedRNode, locateNextRNode, tryLocateRNodeByPath} from './node_lookup_utils';
2324
import {IS_I18N_HYDRATION_ENABLED} from './tokens';
2425
import {
2526
getNgContainerSize,
@@ -130,6 +131,38 @@ function collectI18nChildren(tView: TView): Set<number> | null {
130131
return children.size === 0 ? null : children;
131132
}
132133

134+
/**
135+
* Resulting data from serializing an i18n block.
136+
*/
137+
export interface SerializedI18nBlock {
138+
/**
139+
* A queue of active ICU cases from a depth-first traversal
140+
* of the i18n AST. This is serialized to the client in order
141+
* to correctly associate DOM nodes with i18n nodes during
142+
* hydration.
143+
*/
144+
caseQueue: Array<number>;
145+
146+
/**
147+
* A set of indices in the lView of the block for nodes
148+
* that are disconnected from the DOM. In i18n, this can
149+
* happen when using content projection but some nodes are
150+
* not selected by an <ng-content />.
151+
*/
152+
disconnectedNodes: Set<number>;
153+
154+
/**
155+
* A set of indices in the lView of the block for nodes
156+
* considered "disjoint", indicating that we need to serialize
157+
* a path to the node in order to hydrate it.
158+
*
159+
* A node is considered disjoint when its RNode does not
160+
* directly follow the RNode of the previous i18n node, for
161+
* example, because of content projection.
162+
*/
163+
disjointNodes: Set<number>;
164+
}
165+
133166
/**
134167
* Attempts to serialize i18n data for an i18n block, located at
135168
* the given view and instruction index.
@@ -143,7 +176,7 @@ export function trySerializeI18nBlock(
143176
lView: LView,
144177
index: number,
145178
context: HydrationContext,
146-
): Array<number> | null {
179+
): SerializedI18nBlock | null {
147180
if (!context.isI18nHydrationEnabled) {
148181
return null;
149182
}
@@ -154,38 +187,123 @@ export function trySerializeI18nBlock(
154187
return null;
155188
}
156189

157-
const caseQueue: number[] = [];
158-
tI18n.ast.forEach((node) => serializeI18nBlock(lView, caseQueue, context, node));
159-
return caseQueue.length > 0 ? caseQueue : null;
190+
const serializedI18nBlock: SerializedI18nBlock = {
191+
caseQueue: [],
192+
disconnectedNodes: new Set(),
193+
disjointNodes: new Set(),
194+
};
195+
serializeI18nBlock(lView, serializedI18nBlock, context, tI18n.ast);
196+
197+
return serializedI18nBlock.caseQueue.length === 0 &&
198+
serializedI18nBlock.disconnectedNodes.size === 0 &&
199+
serializedI18nBlock.disjointNodes.size === 0
200+
? null
201+
: serializedI18nBlock;
160202
}
161203

162204
function serializeI18nBlock(
163205
lView: LView,
164-
caseQueue: number[],
206+
serializedI18nBlock: SerializedI18nBlock,
207+
context: HydrationContext,
208+
nodes: I18nNode[],
209+
): Node | null {
210+
let prevRNode = null;
211+
for (const node of nodes) {
212+
const nextRNode = serializeI18nNode(lView, serializedI18nBlock, context, node);
213+
if (nextRNode) {
214+
if (isDisjointNode(prevRNode, nextRNode)) {
215+
serializedI18nBlock.disjointNodes.add(node.index - HEADER_OFFSET);
216+
}
217+
prevRNode = nextRNode;
218+
}
219+
}
220+
return prevRNode;
221+
}
222+
223+
/**
224+
* Helper to determine whether the given nodes are "disjoint".
225+
*
226+
* The i18n hydration process walks through the DOM and i18n nodes
227+
* at the same time. It expects the sibling DOM node of the previous
228+
* i18n node to be the first node of the next i18n node.
229+
*
230+
* In cases of content projection, this won't always be the case. So
231+
* when we detect that, we mark the node as "disjoint", ensuring that
232+
* we will serialize the path to the node. This way, when we hydrate the
233+
* i18n node, we will be able to find the correct place to start.
234+
*/
235+
function isDisjointNode(prevNode: Node | null, nextNode: Node) {
236+
return prevNode && prevNode.nextSibling !== nextNode;
237+
}
238+
239+
/**
240+
* Process the given i18n node for serialization.
241+
* Returns the first RNode for the i18n node to begin hydration.
242+
*/
243+
function serializeI18nNode(
244+
lView: LView,
245+
serializedI18nBlock: SerializedI18nBlock,
165246
context: HydrationContext,
166247
node: I18nNode,
167-
) {
248+
): Node | null {
249+
const maybeRNode = unwrapRNode(lView[node.index]!);
250+
if (!maybeRNode || isDisconnectedRNode(maybeRNode)) {
251+
serializedI18nBlock.disconnectedNodes.add(node.index - HEADER_OFFSET);
252+
return null;
253+
}
254+
255+
const rNode = maybeRNode as Node;
168256
switch (node.kind) {
169-
case I18nNodeKind.TEXT:
170-
const rNode = unwrapRNode(lView[node.index]!);
257+
case I18nNodeKind.TEXT: {
171258
processTextNodeBeforeSerialization(context, rNode);
172259
break;
260+
}
173261

174262
case I18nNodeKind.ELEMENT:
175-
case I18nNodeKind.PLACEHOLDER:
176-
node.children.forEach((node) => serializeI18nBlock(lView, caseQueue, context, node));
263+
case I18nNodeKind.PLACEHOLDER: {
264+
serializeI18nBlock(lView, serializedI18nBlock, context, node.children);
177265
break;
266+
}
178267

179-
case I18nNodeKind.ICU:
268+
case I18nNodeKind.ICU: {
180269
const currentCase = lView[node.currentCaseLViewIndex] as number | null;
181270
if (currentCase != null) {
182271
// i18n uses a negative value to signal a change to a new case, so we
183272
// need to invert it to get the proper value.
184273
const caseIdx = currentCase < 0 ? ~currentCase : currentCase;
185-
caseQueue.push(caseIdx);
186-
node.cases[caseIdx].forEach((node) => serializeI18nBlock(lView, caseQueue, context, node));
274+
serializedI18nBlock.caseQueue.push(caseIdx);
275+
serializeI18nBlock(lView, serializedI18nBlock, context, node.cases[caseIdx]);
187276
}
188277
break;
278+
}
279+
}
280+
281+
return getFirstNativeNodeForI18nNode(lView, node) as Node | null;
282+
}
283+
284+
/**
285+
* Helper function to get the first native node to begin hydrating
286+
* the given i18n node.
287+
*/
288+
function getFirstNativeNodeForI18nNode(lView: LView, node: I18nNode) {
289+
const tView = lView[TVIEW];
290+
const maybeTNode = tView.data[node.index];
291+
292+
if (isTNodeShape(maybeTNode)) {
293+
// If the node is backed by an actual TNode, we can simply delegate.
294+
return getFirstNativeNode(lView, maybeTNode);
295+
} else if (node.kind === I18nNodeKind.ICU) {
296+
// A nested ICU container won't have an actual TNode. In that case, we can use
297+
// an iterator to find the first child.
298+
const icuIterator = createIcuIterator(maybeTNode as TIcu, lView);
299+
let rNode: RNode | null = icuIterator();
300+
301+
// If the ICU container has no nodes, then we use the ICU anchor as the node.
302+
return rNode ?? unwrapRNode(lView[node.index]);
303+
} else {
304+
// Otherwise, the node is a text or trivial element in an ICU container,
305+
// and we can just use the RNode directly.
306+
return unwrapRNode(lView[node.index]) ?? null;
189307
}
190308
}
191309

@@ -346,19 +464,28 @@ function collectI18nNodesFromDom(
346464
nodeOrNodes: I18nNode | I18nNode[],
347465
) {
348466
if (Array.isArray(nodeOrNodes)) {
467+
let nextState = state;
349468
for (const node of nodeOrNodes) {
350-
// If the node is being projected elsewhere, we need to temporarily
351-
// branch the state to that location to continue hydration.
352-
// Otherwise, we continue hydration from the current location.
469+
// Whenever a node doesn't directly follow the previous RNode, it
470+
// is given a path. We need to resume collecting nodes from that location
471+
// until and unless we find another disjoint node.
353472
const targetNode = tryLocateRNodeByPath(
354473
context.hydrationInfo,
355474
context.lView,
356475
node.index - HEADER_OFFSET,
357476
);
358-
const nextState = targetNode ? forkHydrationState(state, targetNode as Node) : state;
477+
if (targetNode) {
478+
nextState = forkHydrationState(state, targetNode as Node);
479+
}
359480
collectI18nNodesFromDom(context, nextState, node);
360481
}
361482
} else {
483+
if (context.disconnectedNodes.has(nodeOrNodes.index - HEADER_OFFSET)) {
484+
// i18n nodes can be considered disconnected if e.g. they were projected.
485+
// In that case, we have to make sure to skip over them.
486+
return;
487+
}
488+
362489
switch (nodeOrNodes.kind) {
363490
case I18nNodeKind.TEXT: {
364491
// Claim a text node for hydration

‎packages/core/src/hydration/node_lookup_utils.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,26 @@ function getNoOffsetIndex(tNode: TNode): number {
4848

4949
/**
5050
* Check whether a given node exists, but is disconnected from the DOM.
51-
*
52-
* Note: we leverage the fact that we have this information available in the DOM emulation
53-
* layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
54-
* only use internal data structures and state to compute this information.
5551
*/
5652
export function isDisconnectedNode(tNode: TNode, lView: LView) {
5753
return (
5854
!(tNode.type & TNodeType.Projection) &&
5955
!!lView[tNode.index] &&
60-
!(unwrapRNode(lView[tNode.index]) as Node)?.isConnected
56+
isDisconnectedRNode(unwrapRNode(lView[tNode.index]))
6157
);
6258
}
6359

60+
/**
61+
* Check whether the given node exists, but is disconnected from the DOM.
62+
*
63+
* Note: we leverage the fact that we have this information available in the DOM emulation
64+
* layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
65+
* only use internal data structures and state to compute this information.
66+
*/
67+
export function isDisconnectedRNode(rNode: RNode | null) {
68+
return !!rNode && !(rNode as Node).isConnected;
69+
}
70+
6471
/**
6572
* Locate a node in an i18n tree that corresponds to a given instruction index.
6673
*
@@ -352,7 +359,7 @@ export function calcPathForNode(
352359
referenceNodeName = renderStringify(parentIndex - HEADER_OFFSET);
353360
}
354361
let rNode = unwrapRNode(lView[tNode.index]);
355-
if (tNode.type & TNodeType.AnyContainer) {
362+
if (tNode.type & (TNodeType.AnyContainer | TNodeType.Icu)) {
356363
// For <ng-container> nodes, instead of serializing a reference
357364
// to the anchor comment node, serialize a location of the first
358365
// DOM element. Paired with the container size (serialized as a part

0 commit comments

Comments
 (0)