Skip to content

Commit aa6d318

Browse files
SkyZeroZxthePunderWoman
authored andcommitted
fix(core): initialize hydration triggers after late runtime activation
After incremental hydration became tree-shakable, application bootstrap could finish before a routed component activated the runtime. The one-time trigger scan was then skipped, leaving routed and nested hydration triggers uninitialized. Coordinate application bootstrap with runtime activation and initialize once both have occurred. Fixes #69908 (cherry picked from commit cfe2cda)
1 parent d6ec7c7 commit aa6d318

5 files changed

Lines changed: 147 additions & 35 deletions

File tree

‎packages/core/src/core_private_export.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ export {
9797
} from './hydration/api';
9898
export {CACHE_ACTIVE as ɵCACHE_ACTIVE} from './hydration/cache';
9999
export {withEventReplay as ɵwithEventReplay} from './hydration/event_replay';
100+
export {resetIncrementalHydrationRuntimeForTests as ɵresetIncrementalHydrationRuntimeForTests} from './hydration/incremental_runtime';
100101
export {
101102
EVENT_REPLAY_QUEUE as ɵEVENT_REPLAY_QUEUE,
102103
IS_ENABLED_BLOCKING_INITIAL_NAVIGATION as ɵIS_ENABLED_BLOCKING_INITIAL_NAVIGATION,

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

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
} from './i18n';
4545
import {
4646
createDehydratedBlockRegistry,
47+
INCREMENTAL_HYDRATION_BOOTSTRAP,
4748
runIncrementalHydrationBootstrap,
4849
} from './incremental_runtime';
4950
import {
@@ -353,21 +354,31 @@ export function withIncrementalHydration(): Provider[] {
353354
];
354355

355356
if (typeof ngServerMode === 'undefined' || !ngServerMode) {
356-
providers.push({
357-
provide: APP_BOOTSTRAP_LISTENER,
358-
useFactory: () => {
359-
const injector = inject(Injector);
360-
const doc = inject(DOCUMENT);
357+
providers.push(
358+
{
359+
provide: INCREMENTAL_HYDRATION_BOOTSTRAP,
360+
useFactory: () => ({
361+
requested: false,
362+
activated: false,
363+
injector: inject(Injector),
364+
document: inject(DOCUMENT),
365+
}),
366+
},
367+
{
368+
provide: APP_BOOTSTRAP_LISTENER,
369+
useFactory: () => {
370+
const state = inject(INCREMENTAL_HYDRATION_BOOTSTRAP);
361371

362-
return () => {
363-
// No-op when the incremental-hydration runtime has not been
364-
// activated. When activated, performs defer-block scanning,
365-
// trigger initialization, and jsaction wiring.
366-
runIncrementalHydrationBootstrap(injector, doc);
367-
};
372+
return () => {
373+
if (!state.requested) {
374+
state.requested = true;
375+
runIncrementalHydrationBootstrap(state);
376+
}
377+
};
378+
},
379+
multi: true,
368380
},
369-
multi: true,
370-
});
381+
);
371382
}
372383

373384
return providers;

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

Lines changed: 58 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import type {Injector} from '../di';
109
import {DehydratedBlockRegistry} from '../defer/registry';
1110
import {processAndInitTriggers} from '../defer/triggering';
11+
import type {Injector} from '../di';
12+
import {InjectionToken} from '../di/injection_token';
13+
import {INJECTOR} from '../render3/interfaces/view';
14+
import {getLView} from '../render3/state';
1215
import {performanceMarkFeature} from '../util/performance';
1316
import {gatherDeferBlocksCommentNodes} from './node_lookup_utils';
1417
import {
@@ -34,6 +37,18 @@ let _runIncrementalHydrationBootstrap: (injector: Injector, doc: Document) => vo
3437
*/
3538
let isIncrementalHydrationRuntimeActive = false;
3639

40+
interface IncrementalHydrationBootstrapState {
41+
requested: boolean;
42+
activated: boolean;
43+
injector: Injector;
44+
document: Document;
45+
}
46+
47+
export const INCREMENTAL_HYDRATION_BOOTSTRAP =
48+
new InjectionToken<IncrementalHydrationBootstrapState>(
49+
typeof ngDevMode === 'undefined' || ngDevMode ? 'INCREMENTAL_HYDRATION_BOOTSTRAP' : '',
50+
);
51+
3752
/**
3853
* Returns the `DehydratedBlockRegistry` used by incremental hydration, or
3954
* `null` if the runtime has not been activated.
@@ -43,39 +58,60 @@ export function createDehydratedBlockRegistry(): DehydratedBlockRegistry | null
4358
}
4459

4560
/**
46-
* Runs the incremental-hydration bootstrap routine (defer-block scanning,
47-
* trigger initialization, jsaction wiring). Called from `APP_BOOTSTRAP_LISTENER`.
48-
* No-op until the runtime is activated.
61+
* Runs incremental hydration bootstrap once application bootstrap and the
62+
* compiler-generated runtime activation have both occurred.
4963
*/
50-
export function runIncrementalHydrationBootstrap(injector: Injector, doc: Document): void {
51-
_runIncrementalHydrationBootstrap(injector, doc);
64+
export function runIncrementalHydrationBootstrap(state: IncrementalHydrationBootstrapState): void {
65+
if (state.requested && state.activated) {
66+
_runIncrementalHydrationBootstrap(state.injector, state.document);
67+
}
5268
}
5369

5470
/**
5571
* Activates the incremental-hydration runtime.
5672
*
57-
* Emitted by the Angular compiler at the top level of every component file
58-
* whose template contains a `@defer (hydrate ...)` trigger. The first call
59-
* swaps in real implementations; subsequent calls are no-ops.
73+
* Emitted by the Angular compiler before the first hydrating `@defer` block in
74+
* a creation block. The first call swaps in the real implementations. Every
75+
* client call also notifies the current application that the runtime is
76+
* available.
6077
*
6178
* @codeGenApi
6279
*/
6380
export function ɵɵenableIncrementalHydrationRuntime(): void {
64-
if (isIncrementalHydrationRuntimeActive) {
65-
return;
66-
}
67-
isIncrementalHydrationRuntimeActive = true;
81+
if (!isIncrementalHydrationRuntimeActive) {
82+
isIncrementalHydrationRuntimeActive = true;
6883

69-
enableRetrieveDeferBlockDataImpl();
84+
enableRetrieveDeferBlockDataImpl();
7085

71-
performanceMarkFeature('NgIncrementalHydration');
86+
performanceMarkFeature('NgIncrementalHydration');
7287

73-
_dehydratedBlockRegistryFactory = () => new DehydratedBlockRegistry();
88+
_dehydratedBlockRegistryFactory = () => new DehydratedBlockRegistry();
7489

75-
_runIncrementalHydrationBootstrap = (injector, doc) => {
76-
const deferBlockData = processBlockData(injector);
77-
const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body);
78-
processAndInitTriggers(injector, deferBlockData, commentsByBlockId);
79-
appendDeferBlocksToJSActionMap(doc, injector);
80-
};
90+
_runIncrementalHydrationBootstrap = (injector, doc) => {
91+
const deferBlockData = processBlockData(injector);
92+
const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body);
93+
processAndInitTriggers(injector, deferBlockData, commentsByBlockId);
94+
appendDeferBlocksToJSActionMap(doc, injector);
95+
};
96+
}
97+
98+
if (typeof ngServerMode === 'undefined' || !ngServerMode) {
99+
const injector = getLView()[INJECTOR];
100+
const state = injector.get(INCREMENTAL_HYDRATION_BOOTSTRAP, null, {optional: true});
101+
if (state !== null && !state.activated) {
102+
state.activated = true;
103+
runIncrementalHydrationBootstrap(state);
104+
}
105+
}
106+
}
107+
108+
/**
109+
* Resets module-level runtime activation for tests that run SSR and client hydration in the same
110+
* process. This is not a full hydration reset and should only be used when cold client activation
111+
* is part of the behavior under test.
112+
*/
113+
export function resetIncrementalHydrationRuntimeForTests(): void {
114+
isIncrementalHydrationRuntimeActive = false;
115+
_dehydratedBlockRegistryFactory = () => null;
116+
_runIncrementalHydrationBootstrap = () => {};
81117
}

‎packages/core/test/bundling/hydration/bundle.golden_symbols.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@
138138
"HttpResponseBase",
139139
"HydrationFeatureKind",
140140
"ID",
141+
"INCREMENTAL_HYDRATION_BOOTSTRAP",
141142
"INJECTOR",
142143
"INJECTOR",
143144
"INJECTOR_DEF_TYPES",

‎packages/platform-server/test/incremental_hydration_spec.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
PLATFORM_ID,
2222
Provider,
2323
QueryList,
24+
ɵresetIncrementalHydrationRuntimeForTests as resetIncrementalHydrationRuntimeForTests,
2425
ɵresetIncrementalHydrationEnabledWarnedForTests as resetIncrementalHydrationEnabledWarnedForTests,
2526
signal,
2627
ɵTimerScheduler as TimerScheduler,
@@ -1317,6 +1318,65 @@ describe('platform-server partial hydration integration', () => {
13171318
expect(activeObservers.length).toBe(1);
13181319
expect(activeObservers[0].options).toEqual({rootMargin: '123px', threshold: 0.5});
13191320
});
1321+
1322+
it('should create an IntersectionObserver for a nested routed viewport block', async () => {
1323+
@Component({
1324+
selector: 'routed',
1325+
template: `
1326+
@defer (hydrate on interaction) {
1327+
<main>
1328+
@defer (hydrate on viewport({rootMargin: '123px', threshold: 0.5})) {
1329+
<article>defer block rendered!</article>
1330+
} @placeholder {
1331+
<span>Inner block placeholder</span>
1332+
}
1333+
</main>
1334+
} @placeholder {
1335+
<span>Outer block placeholder</span>
1336+
}
1337+
`,
1338+
})
1339+
class RoutedComponent {}
1340+
1341+
@Component({
1342+
selector: 'app',
1343+
imports: [RouterOutlet],
1344+
template: '<router-outlet />',
1345+
})
1346+
class SimpleComponent {}
1347+
1348+
const providers = [
1349+
{provide: APP_ID, useValue: 'custom-app-id'},
1350+
{provide: PlatformLocation, useClass: MockPlatformLocation},
1351+
provideRouter([{path: '', component: RoutedComponent}]),
1352+
] as unknown as Provider[];
1353+
const hydrationFeatures = () => [withIncrementalHydration()];
1354+
1355+
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
1356+
const ssrContents = getAppContents(html);
1357+
1358+
expect(ssrContents).toContain(
1359+
'"__nghDeferData__":{"d0":{"r":1,"s":2},"d1":{"r":1,"s":2,"t":[{"trigger":2,"intersectionObserverOptions":{"rootMargin":"123px","threshold":0.5}}],"p":"d0"}}',
1360+
);
1361+
1362+
// Internal cleanup before we do server->client transition in this test.
1363+
resetTViewsFor(SimpleComponent, RoutedComponent);
1364+
// The root view has no hydration triggers, so verify that the routed view activates a
1365+
// cold client runtime.
1366+
resetIncrementalHydrationRuntimeForTests();
1367+
1368+
////////////////////////////////
1369+
const doc = getDocument();
1370+
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
1371+
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
1372+
hydrationFeatures,
1373+
});
1374+
appRef.tick();
1375+
await appRef.whenStable();
1376+
1377+
expect(activeObservers.length).toBe(1);
1378+
expect(activeObservers[0].options).toEqual({rootMargin: '123px', threshold: 0.5});
1379+
});
13201380
});
13211381

13221382
it('immediate', async () => {
@@ -3068,6 +3128,9 @@ describe('platform-server partial hydration integration', () => {
30683128
expect(ssrContents).toContain(`<p id="hydrated">nope</p>`);
30693129

30703130
resetTViewsFor(SimpleComponent, LazyCmp);
3131+
// The immediate trigger is nested in a lazy route, so verify that it is discovered with a
3132+
// cold client runtime.
3133+
resetIncrementalHydrationRuntimeForTests();
30713134

30723135
const doc = getDocument();
30733136
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {

0 commit comments

Comments
 (0)