Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 26 additions & 10 deletions packages/core/src/hydration/annotate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import {
MULTIPLIER,
NODES,
NUM_ROOT_NODES,
PROTECTED_ATTRIBUTES,
SerializedContainerView,
SerializedDeferBlock,
SerializedTriggerDetails,
Expand All @@ -77,6 +78,7 @@ import {
TEMPLATES,
} from './interfaces';
import {calcPathForNode, isDisconnectedNode} from './node_lookup_utils';
import {getHydrationProtectedAttributeName, getStaticAttrValue} from './protected_attributes';
import {isInSkipHydrationBlock, SKIP_HYDRATION_ATTR_NAME} from './skip_hydration';
import {EVENT_REPLAY_ENABLED_DEFAULT, IS_EVENT_REPLAY_ENABLED} from './tokens';
import {
Expand Down Expand Up @@ -726,16 +728,30 @@ function serializeLView(
}
}

// Attach `jsaction` attribute to elements that have registered listeners,
// thus potentially having a need to do an event replay.
if (nativeElementsToEventTypes && tNode.type & TNodeType.Element) {
const nativeElement = unwrapRNode(lView[i]) as Element;
if (nativeElementsToEventTypes.has(nativeElement)) {
setJSActionAttributes(
nativeElement,
nativeElementsToEventTypes.get(nativeElement)!,
parentDeferBlockId,
);
if (tNode.type & TNodeType.Element) {
// Record static attributes that must be left untouched during hydration, because
// re-applying them (even with the same value) triggers unwanted side effects, such as
// an `<iframe src="...">` reloading its resource.
const protectedAttrName = getHydrationProtectedAttributeName(tNode.value);
if (
protectedAttrName !== undefined &&
getStaticAttrValue(tNode.mergedAttrs, protectedAttrName) !== null
) {
ngh[PROTECTED_ATTRIBUTES] ??= {};
ngh[PROTECTED_ATTRIBUTES][noOffsetIndex] = protectedAttrName;
}

// Attach `jsaction` attribute to elements that have registered listeners,
// thus potentially having a need to do an event replay.
if (nativeElementsToEventTypes) {
const nativeElement = unwrapRNode(lView[i]) as Element;
if (nativeElementsToEventTypes.has(nativeElement)) {
setJSActionAttributes(
nativeElement,
nativeElementsToEventTypes.get(nativeElement)!,
parentDeferBlockId,
);
}
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/hydration/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const TEMPLATE_ID = 'i'; // as it's also an "id"
export const NODES = 'n';
export const DISCONNECTED_NODES = 'd';
export const I18N_DATA = 'l';
export const PROTECTED_ATTRIBUTES = 'a';
export const DEFER_BLOCK_ID = 'di';
export const DEFER_BLOCK_STATE = 's';
export const DEFER_PARENT_BLOCK_ID = 'p';
Expand Down Expand Up @@ -112,6 +113,15 @@ export interface SerializedView {
*/
[I18N_DATA]?: Record<number, number[]>;

/**
* Serialized information about static attributes that must not be re-applied during
* hydration, because doing so would trigger an unwanted side effect even though the
* value doesn't change (e.g. an `<iframe src="...">` reloading its resource).
* Key-value pairs where a key is an index of the corresponding element in an LView
* and the value is the name of the attribute to skip.
*/
[PROTECTED_ATTRIBUTES]?: Record<number, string>;

/**
* If this view represents a `@defer` block, this field contains
* unique id of the block.
Expand Down
56 changes: 56 additions & 0 deletions packages/core/src/hydration/protected_attributes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/

import type {TAttributes} from '../render3/interfaces/node';

/**
* Maps a tag name to the name of a static attribute that must not be re-applied during
* hydration.
*
* Setting these attributes again on the client makes the browser reload the referenced external
* resource, even when the value doesn't change. For example, an `<iframe src="...">` rendered on
* the server will reload (and briefly flicker) if hydration calls `setAttribute('src', ...)` on
* it again with the same URL.
*/
const HYDRATION_PROTECTED_ATTRIBUTES = /* @__PURE__ */ new Map<string, string>([
['iframe', 'src'],
['embed', 'src'],
['object', 'data'],
]);

/** Returns the protected attribute name for a given tag name, if any. */
export function getHydrationProtectedAttributeName(tagName: string): string | undefined {
return HYDRATION_PROTECTED_ATTRIBUTES.get(tagName.toLowerCase());
}

/**
* Looks up the value of a static attribute in a `TNode.mergedAttrs` array.
*
* Only considers plain, non-namespaced static attributes (the `[name, value, name, value, ...]`
* pairs that precede any marker in the array, e.g. `AttributeMarker.Bindings`). This is
* sufficient for the protected elements above, which are only ever matched by a plain static
* attribute.
*/
export function getStaticAttrValue(
mergedAttrs: TAttributes | null,
attrName: string,
): string | null {
if (mergedAttrs === null) return null;
for (let i = 0; i < mergedAttrs.length; i += 2) {
const name = mergedAttrs[i];
if (typeof name !== 'string') {
// Reached a marker (namespace, classes, styles, bindings, etc.). No more plain static
// name/value pairs follow after this point.
break;
}
if (name === attrName) {
return mergedAttrs[i + 1] as string;
}
}
return null;
}
12 changes: 12 additions & 0 deletions packages/core/src/hydration/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
ELEMENT_CONTAINERS,
MULTIPLIER,
NUM_ROOT_NODES,
PROTECTED_ATTRIBUTES,
SerializedContainerView,
SerializedDeferBlock,
SerializedTriggerDetails,
Expand Down Expand Up @@ -474,6 +475,17 @@ export function getSerializedContainerViews(
return hydrationInfo.data[CONTAINERS]?.[index] ?? null;
}

/**
* Returns the name of a static attribute that must be left untouched while setting up an
* element's static attributes during hydration, if any (see `PROTECTED_ATTRIBUTES`).
*/
export function getProtectedAttributeName(
hydrationInfo: DehydratedView | null,
index: number,
): string | null {
return hydrationInfo?.data[PROTECTED_ATTRIBUTES]?.[index] ?? null;
}

/**
* Computes the size of a serialized container (the number of root nodes)
* by calculating the sum of root nodes in all dehydrated views in this container.
Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/render3/dom_node_manipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,16 @@ function writeDirectClass(renderer: Renderer, element: RElement, newValue: strin
}

/** Sets up the static DOM attributes on an `RNode`. */
export function setupStaticAttributes(renderer: Renderer, element: RElement, tNode: TNode) {
export function setupStaticAttributes(
renderer: Renderer,
element: RElement,
tNode: TNode,
attrNameToSkip: string | null = null,
) {
const {mergedAttrs, classes, styles} = tNode;

if (mergedAttrs !== null) {
setUpAttributes(renderer, element, mergedAttrs);
setUpAttributes(renderer, element, mergedAttrs, attrNameToSkip);
}

if (classes !== null) {
Expand Down
4 changes: 4 additions & 0 deletions packages/core/src/render3/instructions/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from '../../hydration/skip_hydration';
import {
canHydrateNode,
getProtectedAttributeName,
getSerializedContainerViews,
markRNodeAsClaimedByHydration,
markRNodeAsSkippedByHydration,
Expand Down Expand Up @@ -55,6 +56,7 @@ import {
isSkipHydrationRootTNode,
lastNodeWasCreated,
leaveSkipHydrationBlock,
setSkippedStaticAttrName,
} from '../state';
import {
directiveHostEndFirstCreatePass,
Expand Down Expand Up @@ -340,11 +342,13 @@ function locateOrCreateElementNodeImpl(

// Regular creation mode.
if (isNodeCreationMode) {
setSkippedStaticAttrName(null);
return createElementNode(lView[RENDERER], name, getNamespace());
}

// Hydration mode, looking up an existing element in DOM.
const hydrationInfo = lView[HYDRATION]!;
setSkippedStaticAttrName(getProtectedAttributeName(hydrationInfo, index));
const native = locateNextRNode<RElement>(hydrationInfo, tView, lView, tNode)!;
ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode);
ngDevMode && markRNodeAsClaimedByHydration(native);
Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/render3/instructions/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ import {
getCurrentTNode,
getElementDepthCount,
getSelectedIndex,
getSkippedStaticAttrName,
increaseElementDepthCount,
isCurrentTNodeParent,
isInCheckNoChangesMode,
Expand Down Expand Up @@ -596,7 +597,11 @@ export function elementLikeStartShared(
// It's important that this runs before we've instantiated the directives.
const isElement = tNode.type === TNodeType.Element;
if (isElement) {
setupStaticAttributes(lView[RENDERER], native as RElement, tNode);
// `wasLastNodeCreated()` is `false` only when this node was located in the DOM during
// hydration (as opposed to freshly created). Only in that case can a static attribute
// already be correctly set on the element from the server-rendered HTML.
const attrNameToSkip = wasLastNodeCreated() ? null : getSkippedStaticAttrName();
setupStaticAttributes(lView[RENDERER], native as RElement, tNode, attrNameToSkip);

// any immediate children of a component or template container must be pre-emptively
// monkey-patched with the component view data so that the element can be inspected
Expand Down
17 changes: 17 additions & 0 deletions packages/core/src/render3/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -841,3 +841,20 @@ export function wasLastNodeCreated(): boolean {
export function lastNodeWasCreated(flag: boolean): void {
_wasLastNodeCreated = flag;
}

let _skippedStaticAttrName: string | null = null;

/**
* Retrieves the name of a static attribute that must be left untouched on the most recent DOM
* node, or `null` if there isn't one. Set by hydration when it locates an existing node whose
* attribute must not be re-applied. Kept here, instead of read directly from hydration data,
* so this file doesn't have to import hydration code.
*/
export function getSkippedStaticAttrName(): string | null {
return _skippedStaticAttrName;
}

/** Sets the name of a static attribute that must be left untouched on the most recent DOM node. */
export function setSkippedStaticAttrName(name: string | null): void {
_skippedStaticAttrName = name;
}
16 changes: 13 additions & 3 deletions packages/core/src/render3/util/attrs_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,17 @@ import {RElement} from '../interfaces/renderer_dom';
* @param renderer The renderer to be used
* @param native The element that the attributes will be assigned to
* @param attrs The attribute array of values that will be assigned to the element
* @param attrNameToSkip The name of a static attribute to leave untouched, if present. Used
* during hydration for attributes that must not be re-applied even with the same value
* (e.g. `<iframe src="...">`, where re-setting `src` reloads the resource).
* @returns the index value that was last accessed in the attributes array
*/
export function setUpAttributes(renderer: Renderer, native: RElement, attrs: TAttributes): number {
export function setUpAttributes(
renderer: Renderer,
native: RElement,
attrs: TAttributes,
attrNameToSkip: string | null = null,
): number {
let i = 0;
while (i < attrs.length) {
const value = attrs[i];
Expand All @@ -57,15 +65,17 @@ export function setUpAttributes(renderer: Renderer, native: RElement, attrs: TAt
const namespaceURI = attrs[i++] as string;
const attrName = attrs[i++] as string;
const attrVal = attrs[i++] as string;
renderer.setAttribute(native, attrName, attrVal, namespaceURI);
if (attrName !== attrNameToSkip) {
renderer.setAttribute(native, attrName, attrVal, namespaceURI);
}
} else {
// attrName is string;
const attrName = value as string;
const attrVal = attrs[++i];
// Standard attributes
if (isAnimationProp(attrName)) {
renderer.setProperty(native, attrName, attrVal);
} else {
} else if (attrName !== attrNameToSkip) {
renderer.setAttribute(native, attrName, attrVal as string);
}
i++;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@
"_platformInjector",
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_skippedStaticAttrName",
"_wasLastNodeCreated",
"activeConsumer",
"addAfterRenderSequencesForView",
Expand Down Expand Up @@ -552,6 +553,7 @@
"getRuntimeErrorCode",
"getSelectedIndex",
"getSelectedTNode",
"getSkippedStaticAttrName",
"getStyleHost",
"getTNode",
"getTNodeFromLView",
Expand Down
2 changes: 2 additions & 0 deletions packages/core/test/bundling/defer/bundle.golden_symbols.json
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,7 @@
"_populateDehydratedViewsInLContainer",
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_skippedStaticAttrName",
"_wasLastNodeCreated",
"activeConsumer",
"addAfterRenderSequencesForView",
Expand Down Expand Up @@ -502,6 +503,7 @@
"getRuntimeErrorCode",
"getSelectedIndex",
"getSelectedTNode",
"getSkippedStaticAttrName",
"getStyleHost",
"getTDeferBlockDetails",
"getTNode",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@
"_populateDehydratedViewsInLContainer",
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_skippedStaticAttrName",
"_stashEventListenerImpl",
"_testabilityGetter",
"_wasLastNodeCreated",
Expand Down Expand Up @@ -656,6 +657,7 @@
"getSelectedIndex",
"getSelectedTNode",
"getSimpleChangesStore",
"getSkippedStaticAttrName",
"getStyleHost",
"getSuperType",
"getSymbolIterator",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@
"_populateDehydratedViewsInLContainer",
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_skippedStaticAttrName",
"_stashEventListenerImpl",
"_testabilityGetter",
"_wasLastNodeCreated",
Expand Down Expand Up @@ -652,6 +653,7 @@
"getSelectedIndex",
"getSelectedTNode",
"getSimpleChangesStore",
"getSkippedStaticAttrName",
"getStyleHost",
"getSuperType",
"getSymbolIterator",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@
"PRESERVE_HOST_CONTENT_DEFAULT",
"PREVENT_DEFAULT_ERROR_MESSAGE",
"PROPAGATION_STOPPED_SYMBOL",
"PROTECTED_ATTRIBUTES",
"PendingTasks",
"PendingTasksInternal",
"ProfilerEvent",
Expand Down Expand Up @@ -344,6 +345,7 @@
"_processI18nInsertBefore",
"_retrieveHydrationInfoImpl",
"_runIncrementalHydrationBootstrap",
"_skippedStaticAttrName",
"_stashEventListenerImpl",
"_wasLastNodeCreated",
"activeConsumer",
Expand Down Expand Up @@ -625,6 +627,7 @@
"getPrimaryBlockTNode",
"getProjectionNodes",
"getPromiseCtor",
"getProtectedAttributeName",
"getQueuedEventInfos",
"getResolved",
"getRootTViewTemplate",
Expand Down Expand Up @@ -932,6 +935,7 @@
"setSegmentHead",
"setSelectedIndex",
"setShadowStylingInputFlags",
"setSkippedStaticAttrName",
"setStashFn",
"setTargetElement",
"setThrowInvalidWriteToSignalError",
Expand Down
Loading
Loading