forked from angular/angular
/
after_render_hooks.ts
494 lines (446 loc) · 14.7 KB
/
after_render_hooks.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
/**
* @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 {assertNotInReactiveContext} from '../core_reactivity_export_internal';
import {assertInInjectionContext, Injector, ɵɵdefineInjectable} from '../di';
import {inject} from '../di/injector_compatibility';
import {ErrorHandler} from '../error_handler';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {DestroyRef} from '../linker/destroy_ref';
import {assertGreaterThan} from '../util/assert';
import {performanceMark} from '../util/performance';
import {NgZone} from '../zone';
import {isPlatformBrowser} from './util/misc_utils';
/**
* The phase to run an `afterRender` or `afterNextRender` callback in.
*
* Callbacks in the same phase run in the order they are registered. Phases run in the
* following order after each render:
*
* 1. `AfterRenderPhase.EarlyRead`
* 2. `AfterRenderPhase.Write`
* 3. `AfterRenderPhase.MixedReadWrite`
* 4. `AfterRenderPhase.Read`
*
* Angular is unable to verify or enforce that phases are used correctly, and instead
* relies on each developer to follow the guidelines documented for each value and
* carefully choose the appropriate one, refactoring their code if necessary. By doing
* so, Angular is better able to minimize the performance degradation associated with
* manual DOM access, ensuring the best experience for the end users of your application
* or library.
*
* @developerPreview
*/
export enum AfterRenderPhase {
/**
* Use `AfterRenderPhase.EarlyRead` for callbacks that only need to **read** from the
* DOM before a subsequent `AfterRenderPhase.Write` callback, for example to perform
* custom layout that the browser doesn't natively support. **Never** use this phase
* for callbacks that can write to the DOM or when `AfterRenderPhase.Read` is adequate.
*
* <div class="alert is-important">
*
* Using this value can degrade performance.
* Instead, prefer using built-in browser functionality when possible.
*
* </div>
*/
EarlyRead,
/**
* Use `AfterRenderPhase.Write` for callbacks that only **write** to the DOM. **Never**
* use this phase for callbacks that can read from the DOM.
*/
Write,
/**
* Use `AfterRenderPhase.MixedReadWrite` for callbacks that read from or write to the
* DOM, that haven't been refactored to use a different phase. **Never** use this phase
* for callbacks that can use a different phase instead.
*
* <div class="alert is-critical">
*
* Using this value can **significantly** degrade performance.
* Instead, prefer refactoring into multiple callbacks using a more specific phase.
*
* </div>
*/
MixedReadWrite,
/**
* Use `AfterRenderPhase.Read` for callbacks that only **read** from the DOM. **Never**
* use this phase for callbacks that can write to the DOM.
*/
Read,
}
/**
* Options passed to `afterRender` and `afterNextRender`.
*
* @developerPreview
*/
export interface AfterRenderOptions {
/**
* The `Injector` to use during creation.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector;
/**
* The phase the callback should be invoked in.
*
* <div class="alert is-critical">
*
* Defaults to `AfterRenderPhase.MixedReadWrite`. You should choose a more specific
* phase instead. See `AfterRenderPhase` for more information.
*
* </div>
*/
phase?: AfterRenderPhase;
}
/**
* A callback that runs after render.
*
* @developerPreview
*/
export interface AfterRenderRef {
/**
* Shut down the callback, preventing it from being called again.
*/
destroy(): void;
}
/**
* Options passed to `internalAfterNextRender`.
*/
export interface InternalAfterNextRenderOptions {
/**
* The `Injector` to use during creation.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector;
}
/** `AfterRenderRef` that does nothing. */
const NOOP_AFTER_RENDER_REF: AfterRenderRef = {
destroy() {}
};
/**
* Register a callback to run once before any userspace `afterRender` or
* `afterNextRender` callbacks.
*
* This function should almost always be used instead of `afterRender` or
* `afterNextRender` for implementing framework functionality. Consider:
*
* 1.) `AfterRenderPhase.EarlyRead` is intended to be used for implementing
* custom layout. If the framework itself mutates the DOM after *any*
* `AfterRenderPhase.EarlyRead` callbacks are run, the phase can no
* longer reliably serve its purpose.
*
* 2.) Importing `afterRender` in the framework can reduce the ability for it
* to be tree-shaken, and the framework shouldn't need much of the behavior.
*/
export function internalAfterNextRender(
callback: VoidFunction, options?: InternalAfterNextRenderOptions) {
const injector = options?.injector ?? inject(Injector);
// Similarly to the public `afterNextRender` function, an internal one
// is only invoked in a browser.
if (!isPlatformBrowser(injector)) return;
const afterRenderEventManager = injector.get(AfterRenderEventManager);
afterRenderEventManager.internalCallbacks.push(callback);
}
/**
* Register a callback to be invoked each time the application
* finishes rendering.
*
* <div class="alert is-critical">
*
* You should always explicitly specify a non-default [phase](api/core/AfterRenderPhase), or you
* risk significant performance degradation.
*
* </div>
*
* Note that the callback will run
* - in the order it was registered
* - once per render
* - on browser platforms only
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param callback A callback function to register
*
* @usageNotes
*
* Use `afterRender` to read or write the DOM after each render.
*
* ### Example
* ```ts
* @Component({
* selector: 'my-cmp',
* template: `<span #content>{{ ... }}</span>`,
* })
* export class MyComponent {
* @ViewChild('content') contentRef: ElementRef;
*
* constructor() {
* afterRender(() => {
* console.log('content height: ' + this.contentRef.nativeElement.scrollHeight);
* }, {phase: AfterRenderPhase.Read});
* }
* }
* ```
*
* @developerPreview
*/
export function afterRender(callback: VoidFunction, options?: AfterRenderOptions): AfterRenderRef {
ngDevMode &&
assertNotInReactiveContext(
afterRender,
'Call `afterRender` outside of a reactive context. For example, schedule the render ' +
'callback inside the component constructor`.');
!options && assertInInjectionContext(afterRender);
const injector = options?.injector ?? inject(Injector);
if (!isPlatformBrowser(injector)) {
return NOOP_AFTER_RENDER_REF;
}
performanceMark('mark_use_counter', {detail: {feature: 'NgAfterRender'}});
const afterRenderEventManager = injector.get(AfterRenderEventManager);
// Lazily initialize the handler implementation, if necessary. This is so that it can be
// tree-shaken if `afterRender` and `afterNextRender` aren't used.
const callbackHandler = afterRenderEventManager.handler ??= new AfterRenderCallbackHandlerImpl();
const phase = options?.phase ?? AfterRenderPhase.MixedReadWrite;
const destroy = () => {
callbackHandler.unregister(instance);
unregisterFn();
};
const unregisterFn = injector.get(DestroyRef).onDestroy(destroy);
const instance = new AfterRenderCallback(injector, phase, callback);
callbackHandler.register(instance);
return {destroy};
}
/**
* Register a callback to be invoked the next time the application
* finishes rendering.
*
* <div class="alert is-critical">
*
* You should always explicitly specify a non-default [phase](api/core/AfterRenderPhase), or you
* risk significant performance degradation.
*
* </div>
*
* Note that the callback will run
* - in the order it was registered
* - on browser platforms only
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param callback A callback function to register
*
* @usageNotes
*
* Use `afterNextRender` to read or write the DOM once,
* for example to initialize a non-Angular library.
*
* ### Example
* ```ts
* @Component({
* selector: 'my-chart-cmp',
* template: `<div #chart>{{ ... }}</div>`,
* })
* export class MyChartCmp {
* @ViewChild('chart') chartRef: ElementRef;
* chart: MyChart|null;
*
* constructor() {
* afterNextRender(() => {
* this.chart = new MyChart(this.chartRef.nativeElement);
* }, {phase: AfterRenderPhase.Write});
* }
* }
* ```
*
* @developerPreview
*/
export function afterNextRender(
callback: VoidFunction, options?: AfterRenderOptions): AfterRenderRef {
!options && assertInInjectionContext(afterNextRender);
const injector = options?.injector ?? inject(Injector);
if (!isPlatformBrowser(injector)) {
return NOOP_AFTER_RENDER_REF;
}
performanceMark('mark_use_counter', {detail: {feature: 'NgAfterNextRender'}});
const afterRenderEventManager = injector.get(AfterRenderEventManager);
// Lazily initialize the handler implementation, if necessary. This is so that it can be
// tree-shaken if `afterRender` and `afterNextRender` aren't used.
const callbackHandler = afterRenderEventManager.handler ??= new AfterRenderCallbackHandlerImpl();
const phase = options?.phase ?? AfterRenderPhase.MixedReadWrite;
const destroy = () => {
callbackHandler.unregister(instance);
unregisterFn();
};
const unregisterFn = injector.get(DestroyRef).onDestroy(destroy);
const instance = new AfterRenderCallback(injector, phase, () => {
destroy();
callback();
});
callbackHandler.register(instance);
return {destroy};
}
/**
* A wrapper around a function to be used as an after render callback.
*/
class AfterRenderCallback {
private zone: NgZone;
private errorHandler: ErrorHandler|null;
constructor(
injector: Injector, public readonly phase: AfterRenderPhase,
private callbackFn: VoidFunction) {
this.zone = injector.get(NgZone);
this.errorHandler = injector.get(ErrorHandler, null, {optional: true});
}
invoke() {
try {
this.zone.runOutsideAngular(this.callbackFn);
} catch (err) {
this.errorHandler?.handleError(err);
}
}
}
/**
* Implements `afterRender` and `afterNextRender` callback handler logic.
*/
interface AfterRenderCallbackHandler {
/**
* Validate that it's safe for a render operation to begin,
* throwing if not. Not guaranteed to be called if a render
* operation is started before handler was registered.
*/
validateBegin(): void;
/**
* Register a new callback.
*/
register(callback: AfterRenderCallback): void;
/**
* Unregister an existing callback.
*/
unregister(callback: AfterRenderCallback): void;
/**
* Execute callbacks.
*/
execute(): void;
/**
* Perform any necessary cleanup.
*/
destroy(): void;
}
/**
* Core functionality for `afterRender` and `afterNextRender`. Kept separate from
* `AfterRenderEventManager` for tree-shaking.
*/
class AfterRenderCallbackHandlerImpl implements AfterRenderCallbackHandler {
private executingCallbacks = false;
private buckets = {
// Note: the order of these keys controls the order the phases are run.
[AfterRenderPhase.EarlyRead]: new Set<AfterRenderCallback>(),
[AfterRenderPhase.Write]: new Set<AfterRenderCallback>(),
[AfterRenderPhase.MixedReadWrite]: new Set<AfterRenderCallback>(),
[AfterRenderPhase.Read]: new Set<AfterRenderCallback>(),
};
private deferredCallbacks = new Set<AfterRenderCallback>();
validateBegin(): void {
if (this.executingCallbacks) {
throw new RuntimeError(
RuntimeErrorCode.RECURSIVE_APPLICATION_RENDER,
ngDevMode &&
'A new render operation began before the previous operation ended. ' +
'Did you trigger change detection from afterRender or afterNextRender?');
}
}
register(callback: AfterRenderCallback): void {
// If we're currently running callbacks, new callbacks should be deferred
// until the next render operation.
const target = this.executingCallbacks ? this.deferredCallbacks : this.buckets[callback.phase];
target.add(callback);
}
unregister(callback: AfterRenderCallback): void {
this.buckets[callback.phase].delete(callback);
this.deferredCallbacks.delete(callback);
}
execute(): void {
this.executingCallbacks = true;
for (const bucket of Object.values(this.buckets)) {
for (const callback of bucket) {
callback.invoke();
}
}
this.executingCallbacks = false;
for (const callback of this.deferredCallbacks) {
this.buckets[callback.phase].add(callback);
}
this.deferredCallbacks.clear();
}
destroy(): void {
for (const bucket of Object.values(this.buckets)) {
bucket.clear();
}
this.deferredCallbacks.clear();
}
}
/**
* Implements core timing for `afterRender` and `afterNextRender` events.
* Delegates to an optional `AfterRenderCallbackHandler` for implementation.
*/
export class AfterRenderEventManager {
private renderDepth = 0;
/* @internal */
handler: AfterRenderCallbackHandler|null = null;
/* @internal */
internalCallbacks: VoidFunction[] = [];
/**
* Mark the beginning of a render operation (i.e. CD cycle).
* Throws if called while executing callbacks.
*/
begin() {
this.handler?.validateBegin();
this.renderDepth++;
}
/**
* Mark the end of a render operation. Callbacks will be
* executed if there are no more pending operations.
*/
end() {
ngDevMode && assertGreaterThan(this.renderDepth, 0, 'renderDepth must be greater than 0');
this.renderDepth--;
if (this.renderDepth === 0) {
// Note: internal callbacks power `internalAfterNextRender`. Since internal callbacks
// are fairly trivial, they are kept separate so that `AfterRenderCallbackHandlerImpl`
// can still be tree-shaken unless used by the application.
for (const callback of this.internalCallbacks) {
callback();
}
this.internalCallbacks.length = 0;
this.handler?.execute();
}
}
ngOnDestroy() {
this.handler?.destroy();
this.handler = null;
this.internalCallbacks.length = 0;
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ ɵɵdefineInjectable({
token: AfterRenderEventManager,
providedIn: 'root',
factory: () => new AfterRenderEventManager(),
});
}