Skip to content

Commit 2eebd47

Browse files
AndrewKushniratscott
authored andcommitted
refactor(core): make timer-related @defer logic tree-shakable (#52042)
This commit updates `@defer` logic related to handling `after` and `minimum` parameters tree-shakable. If `after` or `minimum` was used on a `@loading` or `@placeholder` blocks, compiler generates an extra argument for the `ɵɵdefer` instruction. This extra argument is a reference to a function that brings timer-related code. PR Close #52042
1 parent 68ba798 commit 2eebd47

12 files changed

Lines changed: 164 additions & 69 deletions

File tree

‎goldens/size-tracking/integration-payloads.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@
7070
"defer": {
7171
"uncompressed": {
7272
"runtime": 2689,
73-
"main": 124117,
73+
"main": 121811,
7474
"polyfills": 33807,
7575
"src_app_defer_component_ts": 450
7676
}

‎packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_deferred/TEST_CASES.json‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@
5050
],
5151
"failureMessage": "Incorrect template"
5252
}
53-
]
53+
],
54+
"skipForTemplatePipeline": true
5455
},
5556
{
5657
"description": "should generate a deferred block with loading block parameters",
@@ -67,7 +68,8 @@
6768
],
6869
"failureMessage": "Incorrect template"
6970
}
70-
]
71+
],
72+
"skipForTemplatePipeline": true
7173
},
7274
{
7375
"description": "should generate a deferred block with local dependencies",

‎packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_deferred/deferred_with_loading_params_template.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ MyApp.ɵcmp = /*@__PURE__*/ $r3$.ɵɵdefineComponent({
1616
template: function MyApp_Template(rf, ctx) {
1717
if (rf & 1) {
1818
$r3$.ɵɵtemplate(0, MyApp_Defer_0_Template, 1, 0)(1, MyApp_DeferLoading_1_Template, 1, 0);
19-
$r3$.ɵɵdefer(2, 0, null, 1, null, null, 0);
19+
$r3$.ɵɵdefer(2, 0, null, 1, null, null, 0, null, $r3$.ɵɵdeferEnableTimerScheduling);
2020
$r3$.ɵɵdeferOnIdle();
2121
}
2222
},

‎packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_deferred/deferred_with_placeholder_params_template.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ MyApp.ɵcmp = /*@__PURE__*/ $r3$.ɵɵdefineComponent({
1616
template: function MyApp_Template(rf, ctx) {
1717
if (rf & 1) {
1818
$r3$.ɵɵtemplate(0, MyApp_Defer_0_Template, 1, 0)(1, MyApp_DeferPlaceholder_1_Template, 1, 0);
19-
$r3$.ɵɵdefer(2, 0, null, null, 1, null, null, 0);
19+
$r3$.ɵɵdefer(2, 0, null, null, 1, null, null, 0, $r3$.ɵɵdeferEnableTimerScheduling);
2020
$r3$.ɵɵdeferOnIdle();
2121
}
2222
},

‎packages/compiler-cli/test/ngtsc/ngtsc_spec.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8854,6 +8854,47 @@ function allTests(os: string) {
88548854
expect(jsContents).not.toContain('import { CmpA }');
88558855
});
88568856

8857+
it('should include timer scheduler function when ' +
8858+
'`after` or `minimum` parameters are used',
8859+
() => {
8860+
env.write('cmp-a.ts', `
8861+
import { Component } from '@angular/core';
8862+
8863+
@Component({
8864+
standalone: true,
8865+
selector: 'cmp-a',
8866+
template: 'CmpA!'
8867+
})
8868+
export class CmpA {}
8869+
`);
8870+
8871+
env.write('/test.ts', `
8872+
import { Component } from '@angular/core';
8873+
import { CmpA } from './cmp-a';
8874+
8875+
@Component({
8876+
selector: 'test-cmp',
8877+
standalone: true,
8878+
imports: [CmpA],
8879+
template: \`
8880+
@defer {
8881+
<cmp-a />
8882+
} @loading (after 500ms; minimum 300ms) {
8883+
Loading...
8884+
}
8885+
\`,
8886+
})
8887+
export class TestCmp {}
8888+
`);
8889+
8890+
env.driveMain();
8891+
8892+
const jsContents = env.getContents('test.js');
8893+
expect(jsContents)
8894+
.toContain(
8895+
'ɵɵdefer(2, 0, TestCmp_Defer_2_DepsFn, 1, null, null, 0, null, i0.ɵɵdeferEnableTimerScheduling)');
8896+
});
8897+
88578898
describe('imports', () => {
88588899
it('should retain regular imports when symbol is eagerly referenced', () => {
88598900
env.write('cmp-a.ts', `

‎packages/compiler/src/render3/r3_identifiers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,8 @@ export class Identifiers {
160160
o.ExternalReference = {name: 'ɵɵdeferPrefetchOnInteraction', moduleName: CORE};
161161
static deferPrefetchOnViewport:
162162
o.ExternalReference = {name: 'ɵɵdeferPrefetchOnViewport', moduleName: CORE};
163+
static deferEnableTimerScheduling:
164+
o.ExternalReference = {name: 'ɵɵdeferEnableTimerScheduling', moduleName: CORE};
163165

164166
static conditional: o.ExternalReference = {name: 'ɵɵconditional', moduleName: CORE};
165167
static repeater: o.ExternalReference = {name: 'ɵɵrepeater', moduleName: CORE};

‎packages/compiler/src/render3/view/template.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,9 @@ export class TemplateDefinitionBuilder implements t.Visitor<void>, LocalResolver
13231323
o.literal(errorIndex),
13241324
loadingConsts?.length ? this.addToConsts(o.literalArr(loadingConsts)) : o.TYPED_NULL_EXPR,
13251325
placeholderConsts ? this.addToConsts(placeholderConsts) : o.TYPED_NULL_EXPR,
1326+
(loadingConsts?.length || placeholderConsts) ?
1327+
o.importExpr(R3.deferEnableTimerScheduling) :
1328+
o.TYPED_NULL_EXPR,
13261329
]));
13271330

13281331
this.createDeferTriggerInstructions(deferredIndex, triggers, metadata, false);

‎packages/core/src/core_render3_private_export.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ export {
225225
ɵɵdeferPrefetchOnHover,
226226
ɵɵdeferPrefetchOnInteraction,
227227
ɵɵdeferPrefetchOnViewport,
228+
ɵɵdeferEnableTimerScheduling,
228229
ɵɵtext,
229230
ɵɵtextInterpolate,
230231
ɵɵtextInterpolate1,

‎packages/core/src/render3/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@ export {
143143
ɵɵdeferPrefetchOnHover,
144144
ɵɵdeferPrefetchOnInteraction,
145145
ɵɵdeferPrefetchOnViewport,
146+
ɵɵdeferEnableTimerScheduling,
146147

147148
ɵɵtext,
148149
ɵɵtextInterpolate,

‎packages/core/src/render3/instructions/defer.ts‎

Lines changed: 99 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,38 @@ function shouldTriggerDeferBlock(injector: Injector): boolean {
4545
return isPlatformBrowser(injector);
4646
}
4747

48+
/**
49+
* Reference to the timer-based scheduler implementation of defer block state
50+
* rendering method. It's used to make timer-based scheduling tree-shakable.
51+
* If `minimum` or `after` parameters are used, compiler generates an extra
52+
* argument for the `ɵɵdefer` instruction, which references a timer-based
53+
* implementation.
54+
*/
55+
let applyDeferBlockStateWithSchedulingImpl: (typeof applyDeferBlockState)|null = null;
56+
57+
/**
58+
* Enables timer-related scheduling if `after` or `minimum` parameters are setup
59+
* on the `@loading` or `@placeholder` blocks.
60+
*/
61+
export function ɵɵdeferEnableTimerScheduling(
62+
tView: TView, tDetails: TDeferBlockDetails, placeholderConfigIndex?: number|null,
63+
loadingConfigIndex?: number|null) {
64+
const tViewConsts = tView.consts;
65+
if (placeholderConfigIndex != null) {
66+
tDetails.placeholderBlockConfig =
67+
getConstant<DeferredPlaceholderBlockConfig>(tViewConsts, placeholderConfigIndex);
68+
}
69+
if (loadingConfigIndex != null) {
70+
tDetails.loadingBlockConfig =
71+
getConstant<DeferredLoadingBlockConfig>(tViewConsts, loadingConfigIndex);
72+
}
73+
74+
// Enable implementation that supports timer-based scheduling.
75+
if (applyDeferBlockStateWithSchedulingImpl === null) {
76+
applyDeferBlockStateWithSchedulingImpl = applyDeferBlockStateWithScheduling;
77+
}
78+
}
79+
4880
/**
4981
* Creates runtime data structures for defer blocks.
5082
*
@@ -58,39 +90,37 @@ function shouldTriggerDeferBlock(injector: Injector): boolean {
5890
* block.
5991
* @param placeholderConfigIndex Index in the constants array of the configuration of the
6092
* placeholder block.
93+
* @param enableTimerScheduling Function that enables timer-related scheduling if `after`
94+
* or `minimum` parameters are setup on the `@loading` or `@placeholder` blocks.
6195
*
6296
* @codeGenApi
6397
*/
6498
export function ɵɵdefer(
6599
index: number, primaryTmplIndex: number, dependencyResolverFn?: DependencyResolverFn|null,
66100
loadingTmplIndex?: number|null, placeholderTmplIndex?: number|null,
67101
errorTmplIndex?: number|null, loadingConfigIndex?: number|null,
68-
placeholderConfigIndex?: number|null) {
102+
placeholderConfigIndex?: number|null,
103+
enableTimerScheduling?: typeof ɵɵdeferEnableTimerScheduling) {
69104
const lView = getLView();
70105
const tView = getTView();
71-
const tViewConsts = tView.consts;
72106
const adjustedIndex = index + HEADER_OFFSET;
73107

74108
ɵɵtemplate(index, null, 0, 0);
75109

76110
if (tView.firstCreatePass) {
77-
const deferBlockConfig: TDeferBlockDetails = {
111+
const tDetails: TDeferBlockDetails = {
78112
primaryTmplIndex,
79113
loadingTmplIndex: loadingTmplIndex ?? null,
80114
placeholderTmplIndex: placeholderTmplIndex ?? null,
81115
errorTmplIndex: errorTmplIndex ?? null,
82-
placeholderBlockConfig: placeholderConfigIndex != null ?
83-
getConstant<DeferredPlaceholderBlockConfig>(tViewConsts, placeholderConfigIndex) :
84-
null,
85-
loadingBlockConfig: loadingConfigIndex != null ?
86-
getConstant<DeferredLoadingBlockConfig>(tViewConsts, loadingConfigIndex) :
87-
null,
116+
placeholderBlockConfig: null,
117+
loadingBlockConfig: null,
88118
dependencyResolverFn: dependencyResolverFn ?? null,
89119
loadingState: DeferDependenciesLoadingState.NOT_STARTED,
90120
loadingPromise: null,
91121
};
92-
93-
setTDeferBlockDetails(tView, adjustedIndex, deferBlockConfig);
122+
enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex);
123+
setTDeferBlockDetails(tView, adjustedIndex, tDetails);
94124
}
95125

96126
const tNode = getCurrentTNode()!;
@@ -657,16 +687,68 @@ export function renderDeferBlockState(
657687
ngDevMode && assertTNodeForLView(tNode, hostLView);
658688

659689
const lDetails = getLDeferBlockDetails(hostLView, tNode);
660-
const tDetails = getTDeferBlockDetails(hostTView, tNode);
661690

662691
ngDevMode && assertDefined(lDetails, 'Expected a defer block state defined');
663692

664-
const now = Date.now();
665693
const currentState = lDetails[DEFER_BLOCK_STATE];
666694

667-
if (!isValidStateChange(currentState, newState) ||
668-
!isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState))
669-
return;
695+
if (isValidStateChange(currentState, newState) &&
696+
isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState)) {
697+
const tDetails = getTDeferBlockDetails(hostTView, tNode);
698+
const needsScheduling = getLoadingBlockAfter(tDetails) !== null ||
699+
getMinimumDurationForState(tDetails, DeferBlockState.Loading) !== null ||
700+
getMinimumDurationForState(tDetails, DeferBlockState.Placeholder);
701+
702+
if (ngDevMode && needsScheduling) {
703+
assertDefined(
704+
applyDeferBlockStateWithSchedulingImpl, 'Expected scheduling function to be defined');
705+
}
706+
707+
const applyStateFn =
708+
needsScheduling ? applyDeferBlockStateWithSchedulingImpl! : applyDeferBlockState;
709+
applyStateFn(newState, lDetails, lContainer, tNode, hostLView);
710+
}
711+
}
712+
713+
/**
714+
* Applies changes to the DOM to reflect a given state.
715+
*/
716+
function applyDeferBlockState(
717+
newState: DeferBlockState, lDetails: LDeferBlockDetails, lContainer: LContainer, tNode: TNode,
718+
hostLView: LView<unknown>) {
719+
const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
720+
721+
if (stateTmplIndex !== null) {
722+
lDetails[DEFER_BLOCK_STATE] = newState;
723+
const hostTView = hostLView[TVIEW];
724+
const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
725+
const tNode = getTNode(hostTView, adjustedIndex) as TContainerNode;
726+
727+
// There is only 1 view that can be present in an LContainer that
728+
// represents a defer block, so always refer to the first one.
729+
const viewIndex = 0;
730+
731+
removeLViewFromLContainer(lContainer, viewIndex);
732+
const dehydratedView = findMatchingDehydratedView(lContainer, tNode.tView!.ssrId);
733+
const embeddedLView = createAndRenderEmbeddedLView(hostLView, tNode, null, {dehydratedView});
734+
addLViewToLContainer(
735+
lContainer, embeddedLView, viewIndex, shouldAddViewToDom(tNode, dehydratedView));
736+
markViewDirty(embeddedLView);
737+
}
738+
}
739+
740+
/**
741+
* Extends the `applyDeferBlockState` with timer-based scheduling.
742+
* This function becomes available on a page if there are defer blocks
743+
* that use `after` or `minimum` parameters in the `@loading` or
744+
* `@placeholder` blocks.
745+
*/
746+
function applyDeferBlockStateWithScheduling(
747+
newState: DeferBlockState, lDetails: LDeferBlockDetails, lContainer: LContainer, tNode: TNode,
748+
hostLView: LView<unknown>) {
749+
const now = Date.now();
750+
const hostTView = hostLView[TVIEW];
751+
const tDetails = getTDeferBlockDetails(hostTView, tNode);
670752

671753
if (lDetails[STATE_IS_FROZEN_UNTIL] === null || lDetails[STATE_IS_FROZEN_UNTIL] <= now) {
672754
lDetails[STATE_IS_FROZEN_UNTIL] = null;
@@ -690,7 +772,7 @@ export function renderDeferBlockState(
690772
lDetails[NEXT_DEFER_BLOCK_STATE] = null;
691773
}
692774

693-
applyDeferBlockStateToDom(newState, lDetails, lContainer, hostLView, tNode);
775+
applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView);
694776

695777
const duration = getMinimumDurationForState(tDetails, newState);
696778
if (duration !== null) {
@@ -720,8 +802,6 @@ function scheduleDeferBlockUpdate(
720802
renderDeferBlockState(nextState, tNode, lContainer);
721803
}
722804
};
723-
// TODO: this needs refactoring to make `TimerScheduler` that is used inside
724-
// of the `scheduleTimerTrigger` function tree-shakable.
725805
return scheduleTimerTrigger(timeout, callback, hostLView, true);
726806
}
727807

@@ -739,33 +819,6 @@ function isValidStateChange(
739819
return currentState < newState;
740820
}
741821

742-
/**
743-
* Applies changes to the DOM to reflect a given state.
744-
*/
745-
function applyDeferBlockStateToDom(
746-
newState: DeferBlockState, lDetails: LDeferBlockDetails, lContainer: LContainer,
747-
hostLView: LView<unknown>, tNode: TNode) {
748-
const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
749-
750-
if (stateTmplIndex !== null) {
751-
lDetails[DEFER_BLOCK_STATE] = newState;
752-
const hostTView = hostLView[TVIEW];
753-
const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
754-
const tNode = getTNode(hostTView, adjustedIndex) as TContainerNode;
755-
756-
// There is only 1 view that can be present in an LContainer that
757-
// represents a defer block, so always refer to the first one.
758-
const viewIndex = 0;
759-
760-
removeLViewFromLContainer(lContainer, viewIndex);
761-
const dehydratedView = findMatchingDehydratedView(lContainer, tNode.tView!.ssrId);
762-
const embeddedLView = createAndRenderEmbeddedLView(hostLView, tNode, null, {dehydratedView});
763-
addLViewToLContainer(
764-
lContainer, embeddedLView, viewIndex, shouldAddViewToDom(tNode, dehydratedView));
765-
markViewDirty(embeddedLView);
766-
}
767-
}
768-
769822
/**
770823
* Trigger prefetching of dependencies for a defer block.
771824
*

0 commit comments

Comments
 (0)