forked from angular/angular
/
instructions.ts
804 lines (709 loc) · 31.1 KB
/
instructions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
/**
* @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.io/license
*/
import {setActiveConsumer} from '@angular/core/primitives/signals';
import {InjectionToken, Injector} from '../di';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {findMatchingDehydratedView} from '../hydration/views';
import {populateDehydratedViewsInLContainer} from '../linker/view_container_ref';
import {assertLContainer, assertTNodeForLView} from '../render3/assert';
import {bindingUpdated} from '../render3/bindings';
import {getComponentDef, getDirectiveDef, getPipeDef} from '../render3/definition';
import {getTemplateLocationDetails} from '../render3/instructions/element_validation';
import {markViewDirty} from '../render3/instructions/mark_view_dirty';
import {handleError} from '../render3/instructions/shared';
import {ɵɵtemplate} from '../render3/instructions/template';
import {LContainer} from '../render3/interfaces/container';
import {DirectiveDefList, PipeDefList} from '../render3/interfaces/definition';
import {TContainerNode, TNode} from '../render3/interfaces/node';
import {isDestroyed} from '../render3/interfaces/type_checks';
import {HEADER_OFFSET, INJECTOR, LView, PARENT, TVIEW, TView} from '../render3/interfaces/view';
import {getCurrentTNode, getLView, getSelectedTNode, getTView, nextBindingIndex} from '../render3/state';
import {isPlatformBrowser} from '../render3/util/misc_utils';
import {getConstant, getTNode, removeLViewOnDestroy, storeLViewOnDestroy} from '../render3/util/view_utils';
import {addLViewToLContainer, createAndRenderEmbeddedLView, removeLViewFromLContainer, shouldAddViewToDom} from '../render3/view_manipulation';
import {assertDefined, throwError} from '../util/assert';
import {performanceMark} from '../util/performance';
import {invokeAllTriggerCleanupFns, invokeTriggerCleanupFns, storeTriggerCleanupFn} from './cleanup';
import {onHover, onInteraction, onViewport, registerDomTrigger} from './dom_triggers';
import {onIdle} from './idle_scheduler';
import {DEFER_BLOCK_STATE, DeferBlockBehavior, DeferBlockConfig, DeferBlockDependencyInterceptor, DeferBlockInternalState, DeferBlockState, DeferDependenciesLoadingState, DeferredLoadingBlockConfig, DeferredPlaceholderBlockConfig, DependencyResolverFn, LDeferBlockDetails, LOADING_AFTER_CLEANUP_FN, NEXT_DEFER_BLOCK_STATE, STATE_IS_FROZEN_UNTIL, TDeferBlockDetails, TriggerType} from './interfaces';
import {onTimer, scheduleTimerTrigger} from './timer_scheduler';
import {addDepsToRegistry, assertDeferredDependenciesLoaded, getLDeferBlockDetails, getLoadingBlockAfter, getMinimumDurationForState, getPrimaryBlockTNode, getTDeferBlockDetails, getTemplateIndexForState, setLDeferBlockDetails, setTDeferBlockDetails} from './utils';
/**
* **INTERNAL**, avoid referencing it in application code.
*
* Injector token that allows to provide `DeferBlockDependencyInterceptor` class
* implementation.
*/
export const DEFER_BLOCK_DEPENDENCY_INTERCEPTOR =
new InjectionToken<DeferBlockDependencyInterceptor>('DEFER_BLOCK_DEPENDENCY_INTERCEPTOR');
/**
* **INTERNAL**, token used for configuring defer block behavior.
*/
export const DEFER_BLOCK_CONFIG =
new InjectionToken<DeferBlockConfig>(ngDevMode ? 'DEFER_BLOCK_CONFIG' : '');
/**
* Returns whether defer blocks should be triggered.
*
* Currently, defer blocks are not triggered on the server,
* only placeholder content is rendered (if provided).
*/
function shouldTriggerDeferBlock(injector: Injector): boolean {
const config = injector.get(DEFER_BLOCK_CONFIG, null, {optional: true});
if (config?.behavior === DeferBlockBehavior.Manual) {
return false;
}
return isPlatformBrowser(injector);
}
/**
* Reference to the timer-based scheduler implementation of defer block state
* rendering method. It's used to make timer-based scheduling tree-shakable.
* If `minimum` or `after` parameters are used, compiler generates an extra
* argument for the `ɵɵdefer` instruction, which references a timer-based
* implementation.
*/
let applyDeferBlockStateWithSchedulingImpl: (typeof applyDeferBlockState)|null = null;
/**
* Enables timer-related scheduling if `after` or `minimum` parameters are setup
* on the `@loading` or `@placeholder` blocks.
*/
export function ɵɵdeferEnableTimerScheduling(
tView: TView, tDetails: TDeferBlockDetails, placeholderConfigIndex?: number|null,
loadingConfigIndex?: number|null) {
const tViewConsts = tView.consts;
if (placeholderConfigIndex != null) {
tDetails.placeholderBlockConfig =
getConstant<DeferredPlaceholderBlockConfig>(tViewConsts, placeholderConfigIndex);
}
if (loadingConfigIndex != null) {
tDetails.loadingBlockConfig =
getConstant<DeferredLoadingBlockConfig>(tViewConsts, loadingConfigIndex);
}
// Enable implementation that supports timer-based scheduling.
if (applyDeferBlockStateWithSchedulingImpl === null) {
applyDeferBlockStateWithSchedulingImpl = applyDeferBlockStateWithScheduling;
}
}
/**
* Creates runtime data structures for defer blocks.
*
* @param index Index of the `defer` instruction.
* @param primaryTmplIndex Index of the template with the primary block content.
* @param dependencyResolverFn Function that contains dependencies for this defer block.
* @param loadingTmplIndex Index of the template with the loading block content.
* @param placeholderTmplIndex Index of the template with the placeholder block content.
* @param errorTmplIndex Index of the template with the error block content.
* @param loadingConfigIndex Index in the constants array of the configuration of the loading.
* block.
* @param placeholderConfigIndex Index in the constants array of the configuration of the
* placeholder block.
* @param enableTimerScheduling Function that enables timer-related scheduling if `after`
* or `minimum` parameters are setup on the `@loading` or `@placeholder` blocks.
*
* @codeGenApi
*/
export function ɵɵdefer(
index: number, primaryTmplIndex: number, dependencyResolverFn?: DependencyResolverFn|null,
loadingTmplIndex?: number|null, placeholderTmplIndex?: number|null,
errorTmplIndex?: number|null, loadingConfigIndex?: number|null,
placeholderConfigIndex?: number|null,
enableTimerScheduling?: typeof ɵɵdeferEnableTimerScheduling) {
const lView = getLView();
const tView = getTView();
const adjustedIndex = index + HEADER_OFFSET;
ɵɵtemplate(index, null, 0, 0);
if (tView.firstCreatePass) {
performanceMark('mark_use_counter', {detail: {feature: 'NgDefer'}});
const tDetails: TDeferBlockDetails = {
primaryTmplIndex,
loadingTmplIndex: loadingTmplIndex ?? null,
placeholderTmplIndex: placeholderTmplIndex ?? null,
errorTmplIndex: errorTmplIndex ?? null,
placeholderBlockConfig: null,
loadingBlockConfig: null,
dependencyResolverFn: dependencyResolverFn ?? null,
loadingState: DeferDependenciesLoadingState.NOT_STARTED,
loadingPromise: null,
};
enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex);
setTDeferBlockDetails(tView, adjustedIndex, tDetails);
}
const tNode = getCurrentTNode()!;
const lContainer = lView[adjustedIndex];
// If hydration is enabled, looks up dehydrated views in the DOM
// using hydration annotation info and stores those views on LContainer.
// In client-only mode, this function is a noop.
populateDehydratedViewsInLContainer(lContainer, tNode, lView);
// Init instance-specific defer details and store it.
const lDetails: LDeferBlockDetails = [
null, // NEXT_DEFER_BLOCK_STATE
DeferBlockInternalState.Initial, // DEFER_BLOCK_STATE
null, // STATE_IS_FROZEN_UNTIL
null, // LOADING_AFTER_CLEANUP_FN
null, // TRIGGER_CLEANUP_FNS
null // PREFETCH_TRIGGER_CLEANUP_FNS
];
setLDeferBlockDetails(lView, adjustedIndex, lDetails);
const cleanupTriggersFn = () => invokeAllTriggerCleanupFns(lDetails);
// When defer block is triggered - unsubscribe from LView destroy cleanup.
storeTriggerCleanupFn(
TriggerType.Regular, lDetails, () => removeLViewOnDestroy(lView, cleanupTriggersFn));
storeLViewOnDestroy(lView, cleanupTriggersFn);
}
/**
* Loads defer block dependencies when a trigger value becomes truthy.
* @codeGenApi
*/
export function ɵɵdeferWhen(rawValue: unknown) {
const lView = getLView();
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, rawValue)) {
const prevConsumer = setActiveConsumer(null);
try {
const value = Boolean(rawValue); // handle truthy or falsy values
const tNode = getSelectedTNode();
const lDetails = getLDeferBlockDetails(lView, tNode);
const renderedState = lDetails[DEFER_BLOCK_STATE];
if (value === false && renderedState === DeferBlockInternalState.Initial) {
// If nothing is rendered yet, render a placeholder (if defined).
renderPlaceholder(lView, tNode);
} else if (
value === true &&
(renderedState === DeferBlockInternalState.Initial ||
renderedState === DeferBlockState.Placeholder)) {
// The `when` condition has changed to `true`, trigger defer block loading
// if the block is either in initial (nothing is rendered) or a placeholder
// state.
triggerDeferBlock(lView, tNode);
}
} finally {
setActiveConsumer(prevConsumer);
}
}
}
/**
* Prefetches the deferred content when a value becomes truthy.
* @codeGenApi
*/
export function ɵɵdeferPrefetchWhen(rawValue: unknown) {
const lView = getLView();
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, rawValue)) {
const prevConsumer = setActiveConsumer(null);
try {
const value = Boolean(rawValue); // handle truthy or falsy values
const tView = lView[TVIEW];
const tNode = getSelectedTNode();
const tDetails = getTDeferBlockDetails(tView, tNode);
if (value === true && tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
// If loading has not been started yet, trigger it now.
triggerPrefetching(tDetails, lView, tNode);
}
} finally {
setActiveConsumer(prevConsumer);
}
}
}
/**
* Sets up logic to handle the `on idle` deferred trigger.
* @codeGenApi
*/
export function ɵɵdeferOnIdle() {
scheduleDelayedTrigger(onIdle);
}
/**
* Sets up logic to handle the `prefetch on idle` deferred trigger.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnIdle() {
scheduleDelayedPrefetching(onIdle);
}
/**
* Sets up logic to handle the `on immediate` deferred trigger.
* @codeGenApi
*/
export function ɵɵdeferOnImmediate() {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
// Render placeholder block only if loading template is not present
// to avoid content flickering, since it would be immediately replaced
// by the loading block.
if (tDetails.loadingTmplIndex === null) {
renderPlaceholder(lView, tNode);
}
triggerDeferBlock(lView, tNode);
}
/**
* Sets up logic to handle the `prefetch on immediate` deferred trigger.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnImmediate() {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
triggerResourceLoading(tDetails, lView, tNode);
}
}
/**
* Creates runtime data structures for the `on timer` deferred trigger.
* @param delay Amount of time to wait before loading the content.
* @codeGenApi
*/
export function ɵɵdeferOnTimer(delay: number) {
scheduleDelayedTrigger(onTimer(delay));
}
/**
* Creates runtime data structures for the `prefetch on timer` deferred trigger.
* @param delay Amount of time to wait before prefetching the content.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnTimer(delay: number) {
scheduleDelayedPrefetching(onTimer(delay));
}
/**
* Creates runtime data structures for the `on hover` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferOnHover(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
renderPlaceholder(lView, tNode);
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onHover, () => triggerDeferBlock(lView, tNode),
TriggerType.Regular);
}
/**
* Creates runtime data structures for the `prefetch on hover` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnHover(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onHover,
() => triggerPrefetching(tDetails, lView, tNode), TriggerType.Prefetch);
}
}
/**
* Creates runtime data structures for the `on interaction` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferOnInteraction(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
renderPlaceholder(lView, tNode);
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onInteraction, () => triggerDeferBlock(lView, tNode),
TriggerType.Regular);
}
/**
* Creates runtime data structures for the `prefetch on interaction` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnInteraction(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onInteraction,
() => triggerPrefetching(tDetails, lView, tNode), TriggerType.Prefetch);
}
}
/**
* Creates runtime data structures for the `on viewport` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferOnViewport(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
renderPlaceholder(lView, tNode);
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerDeferBlock(lView, tNode),
TriggerType.Regular);
}
/**
* Creates runtime data structures for the `prefetch on viewport` deferred trigger.
* @param triggerIndex Index at which to find the trigger element.
* @param walkUpTimes Number of times to walk up/down the tree hierarchy to find the trigger.
* @codeGenApi
*/
export function ɵɵdeferPrefetchOnViewport(triggerIndex: number, walkUpTimes?: number) {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
registerDomTrigger(
lView, tNode, triggerIndex, walkUpTimes, onViewport,
() => triggerPrefetching(tDetails, lView, tNode), TriggerType.Prefetch);
}
}
/********** Helper functions **********/
/**
* Schedules triggering of a defer block for `on idle` and `on timer` conditions.
*/
function scheduleDelayedTrigger(
scheduleFn: (callback: VoidFunction, lView: LView) => VoidFunction) {
const lView = getLView();
const tNode = getCurrentTNode()!;
renderPlaceholder(lView, tNode);
const cleanupFn = scheduleFn(() => triggerDeferBlock(lView, tNode), lView);
const lDetails = getLDeferBlockDetails(lView, tNode);
storeTriggerCleanupFn(TriggerType.Regular, lDetails, cleanupFn);
}
/**
* Schedules prefetching for `on idle` and `on timer` triggers.
*
* @param scheduleFn A function that does the scheduling.
*/
function scheduleDelayedPrefetching(
scheduleFn: (callback: VoidFunction, lView: LView) => VoidFunction) {
const lView = getLView();
const tNode = getCurrentTNode()!;
const tView = lView[TVIEW];
const tDetails = getTDeferBlockDetails(tView, tNode);
if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) {
const lDetails = getLDeferBlockDetails(lView, tNode);
const prefetch = () => triggerPrefetching(tDetails, lView, tNode);
const cleanupFn = scheduleFn(prefetch, lView);
storeTriggerCleanupFn(TriggerType.Prefetch, lDetails, cleanupFn);
}
}
/**
* Transitions a defer block to the new state. Updates the necessary
* data structures and renders corresponding block.
*
* @param newState New state that should be applied to the defer block.
* @param tNode TNode that represents a defer block.
* @param lContainer Represents an instance of a defer block.
* @param skipTimerScheduling Indicates that `@loading` and `@placeholder` block
* should be rendered immediately, even if they have `after` or `minimum` config
* options setup. This flag to needed for testing APIs to transition defer block
* between states via `DeferFixture.render` method.
*/
export function renderDeferBlockState(
newState: DeferBlockState, tNode: TNode, lContainer: LContainer,
skipTimerScheduling = false): void {
const hostLView = lContainer[PARENT];
const hostTView = hostLView[TVIEW];
// Check if this view is not destroyed. Since the loading process was async,
// the view might end up being destroyed by the time rendering happens.
if (isDestroyed(hostLView)) return;
// Make sure this TNode belongs to TView that represents host LView.
ngDevMode && assertTNodeForLView(tNode, hostLView);
const lDetails = getLDeferBlockDetails(hostLView, tNode);
ngDevMode && assertDefined(lDetails, 'Expected a defer block state defined');
const currentState = lDetails[DEFER_BLOCK_STATE];
if (isValidStateChange(currentState, newState) &&
isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState)) {
const tDetails = getTDeferBlockDetails(hostTView, tNode);
const needsScheduling = !skipTimerScheduling &&
(getLoadingBlockAfter(tDetails) !== null ||
getMinimumDurationForState(tDetails, DeferBlockState.Loading) !== null ||
getMinimumDurationForState(tDetails, DeferBlockState.Placeholder));
if (ngDevMode && needsScheduling) {
assertDefined(
applyDeferBlockStateWithSchedulingImpl, 'Expected scheduling function to be defined');
}
const applyStateFn =
needsScheduling ? applyDeferBlockStateWithSchedulingImpl! : applyDeferBlockState;
try {
applyStateFn(newState, lDetails, lContainer, tNode, hostLView);
} catch (error: unknown) {
handleError(hostLView, error);
}
}
}
/**
* Applies changes to the DOM to reflect a given state.
*/
function applyDeferBlockState(
newState: DeferBlockState, lDetails: LDeferBlockDetails, lContainer: LContainer, tNode: TNode,
hostLView: LView<unknown>) {
const stateTmplIndex = getTemplateIndexForState(newState, hostLView, tNode);
if (stateTmplIndex !== null) {
lDetails[DEFER_BLOCK_STATE] = newState;
const hostTView = hostLView[TVIEW];
const adjustedIndex = stateTmplIndex + HEADER_OFFSET;
const tNode = getTNode(hostTView, adjustedIndex) as TContainerNode;
// There is only 1 view that can be present in an LContainer that
// represents a defer block, so always refer to the first one.
const viewIndex = 0;
removeLViewFromLContainer(lContainer, viewIndex);
const dehydratedView = findMatchingDehydratedView(lContainer, tNode.tView!.ssrId);
const embeddedLView = createAndRenderEmbeddedLView(hostLView, tNode, null, {dehydratedView});
addLViewToLContainer(
lContainer, embeddedLView, viewIndex, shouldAddViewToDom(tNode, dehydratedView));
markViewDirty(embeddedLView);
}
}
/**
* Extends the `applyDeferBlockState` with timer-based scheduling.
* This function becomes available on a page if there are defer blocks
* that use `after` or `minimum` parameters in the `@loading` or
* `@placeholder` blocks.
*/
function applyDeferBlockStateWithScheduling(
newState: DeferBlockState, lDetails: LDeferBlockDetails, lContainer: LContainer, tNode: TNode,
hostLView: LView<unknown>) {
const now = Date.now();
const hostTView = hostLView[TVIEW];
const tDetails = getTDeferBlockDetails(hostTView, tNode);
if (lDetails[STATE_IS_FROZEN_UNTIL] === null || lDetails[STATE_IS_FROZEN_UNTIL] <= now) {
lDetails[STATE_IS_FROZEN_UNTIL] = null;
const loadingAfter = getLoadingBlockAfter(tDetails);
const inLoadingAfterPhase = lDetails[LOADING_AFTER_CLEANUP_FN] !== null;
if (newState === DeferBlockState.Loading && loadingAfter !== null && !inLoadingAfterPhase) {
// Trying to render loading, but it has an `after` config,
// so schedule an update action after a timeout.
lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
const cleanupFn =
scheduleDeferBlockUpdate(loadingAfter, lDetails, tNode, lContainer, hostLView);
lDetails[LOADING_AFTER_CLEANUP_FN] = cleanupFn;
} else {
// If we transition to a complete or an error state and there is a pending
// operation to render loading after a timeout - invoke a cleanup operation,
// which stops the timer.
if (newState > DeferBlockState.Loading && inLoadingAfterPhase) {
lDetails[LOADING_AFTER_CLEANUP_FN]!();
lDetails[LOADING_AFTER_CLEANUP_FN] = null;
lDetails[NEXT_DEFER_BLOCK_STATE] = null;
}
applyDeferBlockState(newState, lDetails, lContainer, tNode, hostLView);
const duration = getMinimumDurationForState(tDetails, newState);
if (duration !== null) {
lDetails[STATE_IS_FROZEN_UNTIL] = now + duration;
scheduleDeferBlockUpdate(duration, lDetails, tNode, lContainer, hostLView);
}
}
} else {
// We are still rendering the previous state.
// Update the `NEXT_DEFER_BLOCK_STATE`, which would be
// picked up once it's time to transition to the next state.
lDetails[NEXT_DEFER_BLOCK_STATE] = newState;
}
}
/**
* Schedules an update operation after a specified timeout.
*/
function scheduleDeferBlockUpdate(
timeout: number, lDetails: LDeferBlockDetails, tNode: TNode, lContainer: LContainer,
hostLView: LView<unknown>): VoidFunction {
const callback = () => {
const nextState = lDetails[NEXT_DEFER_BLOCK_STATE];
lDetails[STATE_IS_FROZEN_UNTIL] = null;
lDetails[NEXT_DEFER_BLOCK_STATE] = null;
if (nextState !== null) {
renderDeferBlockState(nextState, tNode, lContainer);
}
};
return scheduleTimerTrigger(timeout, callback, hostLView);
}
/**
* Checks whether we can transition to the next state.
*
* We transition to the next state if the previous state was represented
* with a number that is less than the next state. For example, if the current
* state is "loading" (represented as `1`), we should not show a placeholder
* (represented as `0`), but we can show a completed state (represented as `2`)
* or an error state (represented as `3`).
*/
function isValidStateChange(
currentState: DeferBlockState|DeferBlockInternalState, newState: DeferBlockState): boolean {
return currentState < newState;
}
/**
* Trigger prefetching of dependencies for a defer block.
*
* @param tDetails Static information about this defer block.
* @param lView LView of a host view.
*/
export function triggerPrefetching(tDetails: TDeferBlockDetails, lView: LView, tNode: TNode) {
if (lView[INJECTOR] && shouldTriggerDeferBlock(lView[INJECTOR]!)) {
triggerResourceLoading(tDetails, lView, tNode);
}
}
/**
* Trigger loading of defer block dependencies if the process hasn't started yet.
*
* @param tDetails Static information about this defer block.
* @param lView LView of a host view.
*/
export function triggerResourceLoading(tDetails: TDeferBlockDetails, lView: LView, tNode: TNode) {
const injector = lView[INJECTOR]!;
const tView = lView[TVIEW];
if (tDetails.loadingState !== DeferDependenciesLoadingState.NOT_STARTED) {
// If the loading status is different from initial one, it means that
// the loading of dependencies is in progress and there is nothing to do
// in this function. All details can be obtained from the `tDetails` object.
return;
}
const lDetails = getLDeferBlockDetails(lView, tNode);
const primaryBlockTNode = getPrimaryBlockTNode(tView, tDetails);
// Switch from NOT_STARTED -> IN_PROGRESS state.
tDetails.loadingState = DeferDependenciesLoadingState.IN_PROGRESS;
// Prefetching is triggered, cleanup all registered prefetch triggers.
invokeTriggerCleanupFns(TriggerType.Prefetch, lDetails);
let dependenciesFn = tDetails.dependencyResolverFn;
if (ngDevMode) {
// Check if dependency function interceptor is configured.
const deferDependencyInterceptor =
injector.get(DEFER_BLOCK_DEPENDENCY_INTERCEPTOR, null, {optional: true});
if (deferDependencyInterceptor) {
dependenciesFn = deferDependencyInterceptor.intercept(dependenciesFn);
}
}
// The `dependenciesFn` might be `null` when all dependencies within
// a given defer block were eagerly references elsewhere in a file,
// thus no dynamic `import()`s were produced.
if (!dependenciesFn) {
tDetails.loadingPromise = Promise.resolve().then(() => {
tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
});
return;
}
// Start downloading of defer block dependencies.
tDetails.loadingPromise = Promise.allSettled(dependenciesFn()).then(results => {
let failed = false;
const directiveDefs: DirectiveDefList = [];
const pipeDefs: PipeDefList = [];
for (const result of results) {
if (result.status === 'fulfilled') {
const dependency = result.value;
const directiveDef = getComponentDef(dependency) || getDirectiveDef(dependency);
if (directiveDef) {
directiveDefs.push(directiveDef);
} else {
const pipeDef = getPipeDef(dependency);
if (pipeDef) {
pipeDefs.push(pipeDef);
}
}
} else {
failed = true;
break;
}
}
// Loading is completed, we no longer need this Promise.
tDetails.loadingPromise = null;
if (failed) {
tDetails.loadingState = DeferDependenciesLoadingState.FAILED;
if (tDetails.errorTmplIndex === null) {
const templateLocation = getTemplateLocationDetails(lView);
const error = new RuntimeError(
RuntimeErrorCode.DEFER_LOADING_FAILED,
ngDevMode &&
'Loading dependencies for `@defer` block failed, ' +
`but no \`@error\` block was configured${templateLocation}. ` +
'Consider using the `@error` block to render an error state.');
handleError(lView, error);
}
} else {
tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE;
// Update directive and pipe registries to add newly downloaded dependencies.
const primaryBlockTView = primaryBlockTNode.tView!;
if (directiveDefs.length > 0) {
primaryBlockTView.directiveRegistry =
addDepsToRegistry<DirectiveDefList>(primaryBlockTView.directiveRegistry, directiveDefs);
}
if (pipeDefs.length > 0) {
primaryBlockTView.pipeRegistry =
addDepsToRegistry<PipeDefList>(primaryBlockTView.pipeRegistry, pipeDefs);
}
}
});
}
/** Utility function to render placeholder content (if present) */
function renderPlaceholder(lView: LView, tNode: TNode) {
const lContainer = lView[tNode.index];
ngDevMode && assertLContainer(lContainer);
renderDeferBlockState(DeferBlockState.Placeholder, tNode, lContainer);
}
/**
* Subscribes to the "loading" Promise and renders corresponding defer sub-block,
* based on the loading results.
*
* @param lContainer Represents an instance of a defer block.
* @param tNode Represents defer block info shared across all instances.
*/
function renderDeferStateAfterResourceLoading(
tDetails: TDeferBlockDetails, tNode: TNode, lContainer: LContainer) {
ngDevMode &&
assertDefined(
tDetails.loadingPromise, 'Expected loading Promise to exist on this defer block');
tDetails.loadingPromise!.then(() => {
if (tDetails.loadingState === DeferDependenciesLoadingState.COMPLETE) {
ngDevMode && assertDeferredDependenciesLoaded(tDetails);
// Everything is loaded, show the primary block content
renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
} else if (tDetails.loadingState === DeferDependenciesLoadingState.FAILED) {
renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
}
});
}
/**
* Attempts to trigger loading of defer block dependencies.
* If the block is already in a loading, completed or an error state -
* no additional actions are taken.
*/
function triggerDeferBlock(lView: LView, tNode: TNode) {
const tView = lView[TVIEW];
const lContainer = lView[tNode.index];
const injector = lView[INJECTOR]!;
ngDevMode && assertLContainer(lContainer);
if (!shouldTriggerDeferBlock(injector)) return;
const lDetails = getLDeferBlockDetails(lView, tNode);
const tDetails = getTDeferBlockDetails(tView, tNode);
// Defer block is triggered, cleanup all registered trigger functions.
invokeAllTriggerCleanupFns(lDetails);
switch (tDetails.loadingState) {
case DeferDependenciesLoadingState.NOT_STARTED:
renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
triggerResourceLoading(tDetails, lView, tNode);
// The `loadingState` might have changed to "loading".
if ((tDetails.loadingState as DeferDependenciesLoadingState) ===
DeferDependenciesLoadingState.IN_PROGRESS) {
renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
}
break;
case DeferDependenciesLoadingState.IN_PROGRESS:
renderDeferBlockState(DeferBlockState.Loading, tNode, lContainer);
renderDeferStateAfterResourceLoading(tDetails, tNode, lContainer);
break;
case DeferDependenciesLoadingState.COMPLETE:
ngDevMode && assertDeferredDependenciesLoaded(tDetails);
renderDeferBlockState(DeferBlockState.Complete, tNode, lContainer);
break;
case DeferDependenciesLoadingState.FAILED:
renderDeferBlockState(DeferBlockState.Error, tNode, lContainer);
break;
default:
if (ngDevMode) {
throwError('Unknown defer block state');
}
}
}