_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/src/di/provider_collection.ts_0_7376
/** * @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 {RuntimeError, RuntimeErrorCode} from '../errors'; import {Type} from '../interface/type'; import {getComponentDef} from '../render3/def_getters'; import {getFactoryDef} from '../render3/definition_factory'; import {throwCyclicDependencyError, throwInvalidProviderError} from '../render3/errors_di'; import {stringifyForError} from '../render3/util/stringify_utils'; import {deepForEach} from '../util/array_utils'; import {EMPTY_ARRAY} from '../util/empty'; import {getClosureSafeProperty} from '../util/property'; import {stringify} from '../util/stringify'; import {resolveForwardRef} from './forward_ref'; import {ENVIRONMENT_INITIALIZER} from './initializer_token'; import {ɵɵinject as inject} from './injector_compatibility'; import {getInjectorDef, InjectorType, InjectorTypeWithProviders} from './interface/defs'; import { ClassProvider, ConstructorProvider, EnvironmentProviders, ExistingProvider, FactoryProvider, InternalEnvironmentProviders, isEnvironmentProviders, ModuleWithProviders, Provider, StaticClassProvider, TypeProvider, ValueProvider, } from './interface/provider'; import {INJECTOR_DEF_TYPES} from './internal_tokens'; /** * Wrap an array of `Provider`s into `EnvironmentProviders`, preventing them from being accidentally * referenced in `@Component` in a component injector. */ export function makeEnvironmentProviders( providers: (Provider | EnvironmentProviders)[], ): EnvironmentProviders { return { ɵproviders: providers, } as unknown as EnvironmentProviders; } /** * @description * This function is used to provide initialization functions that will be executed upon construction * of an environment injector. * * Note that the provided initializer is run in the injection context. * * Previously, this was achieved using the `ENVIRONMENT_INITIALIZER` token which is now deprecated. * * @see {@link ENVIRONMENT_INITIALIZER} * * @usageNotes * The following example illustrates how to configure an initialization function using * `provideEnvironmentInitializer()` * ``` * createEnvironmentInjector( * [ * provideEnvironmentInitializer(() => { * console.log('environment initialized'); * }), * ], * parentInjector * ); * ``` * * @publicApi */ export function provideEnvironmentInitializer(initializerFn: () => void): EnvironmentProviders { return makeEnvironmentProviders([ { provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: initializerFn, }, ]); } /** * A source of providers for the `importProvidersFrom` function. * * @publicApi */ export type ImportProvidersSource = | Type<unknown> | ModuleWithProviders<unknown> | Array<ImportProvidersSource>; type WalkProviderTreeVisitor = ( provider: SingleProvider, container: Type<unknown> | InjectorType<unknown>, ) => void; /** * Collects providers from all NgModules and standalone components, including transitively imported * ones. * * Providers extracted via `importProvidersFrom` are only usable in an application injector or * another environment injector (such as a route injector). They should not be used in component * providers. * * More information about standalone components can be found in [this * guide](guide/components/importing). * * @usageNotes * The results of the `importProvidersFrom` call can be used in the `bootstrapApplication` call: * * ```typescript * await bootstrapApplication(RootComponent, { * providers: [ * importProvidersFrom(NgModuleOne, NgModuleTwo) * ] * }); * ``` * * You can also use the `importProvidersFrom` results in the `providers` field of a route, when a * standalone component is used: * * ```typescript * export const ROUTES: Route[] = [ * { * path: 'foo', * providers: [ * importProvidersFrom(NgModuleOne, NgModuleTwo) * ], * component: YourStandaloneComponent * } * ]; * ``` * * @returns Collected providers from the specified list of types. * @publicApi */ export function importProvidersFrom(...sources: ImportProvidersSource[]): EnvironmentProviders { return { ɵproviders: internalImportProvidersFrom(true, sources), ɵfromNgModule: true, } as InternalEnvironmentProviders; } export function internalImportProvidersFrom( checkForStandaloneCmp: boolean, ...sources: ImportProvidersSource[] ): Provider[] { const providersOut: SingleProvider[] = []; const dedup = new Set<Type<unknown>>(); // already seen types let injectorTypesWithProviders: InjectorTypeWithProviders<unknown>[] | undefined; const collectProviders: WalkProviderTreeVisitor = (provider) => { providersOut.push(provider); }; deepForEach(sources, (source) => { if ((typeof ngDevMode === 'undefined' || ngDevMode) && checkForStandaloneCmp) { const cmpDef = getComponentDef(source); if (cmpDef?.standalone) { throw new RuntimeError( RuntimeErrorCode.IMPORT_PROVIDERS_FROM_STANDALONE, `Importing providers supports NgModule or ModuleWithProviders but got a standalone component "${stringifyForError( source, )}"`, ); } } // Narrow `source` to access the internal type analogue for `ModuleWithProviders`. const internalSource = source as Type<unknown> | InjectorTypeWithProviders<unknown>; if (walkProviderTree(internalSource, collectProviders, [], dedup)) { injectorTypesWithProviders ||= []; injectorTypesWithProviders.push(internalSource); } }); // Collect all providers from `ModuleWithProviders` types. if (injectorTypesWithProviders !== undefined) { processInjectorTypesWithProviders(injectorTypesWithProviders, collectProviders); } return providersOut; } /** * Collects all providers from the list of `ModuleWithProviders` and appends them to the provided * array. */ function processInjectorTypesWithProviders( typesWithProviders: InjectorTypeWithProviders<unknown>[], visitor: WalkProviderTreeVisitor, ): void { for (let i = 0; i < typesWithProviders.length; i++) { const {ngModule, providers} = typesWithProviders[i]; deepForEachProvider( providers! as Array<Provider | InternalEnvironmentProviders>, (provider) => { ngDevMode && validateProvider(provider, providers || EMPTY_ARRAY, ngModule); visitor(provider, ngModule); }, ); } } /** * Internal type for a single provider in a deep provider array. */ export type SingleProvider = | TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | StaticClassProvider; /** * The logic visits an `InjectorType`, an `InjectorTypeWithProviders`, or a standalone * `ComponentType`, and all of its transitive providers and collects providers. * * If an `InjectorTypeWithProviders` that declares providers besides the type is specified, * the function will return "true" to indicate that the providers of the type definition need * to be processed. This allows us to process providers of injector types after all imports of * an injector definition are processed. (following View Engine semantics: see FW-1349) */ expo
{ "end_byte": 7376, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/provider_collection.ts" }
angular/packages/core/src/di/provider_collection.ts_7377_14566
t function walkProviderTree( container: Type<unknown> | InjectorTypeWithProviders<unknown>, visitor: WalkProviderTreeVisitor, parents: Type<unknown>[], dedup: Set<Type<unknown>>, ): container is InjectorTypeWithProviders<unknown> { container = resolveForwardRef(container); if (!container) return false; // The actual type which had the definition. Usually `container`, but may be an unwrapped type // from `InjectorTypeWithProviders`. let defType: Type<unknown> | null = null; let injDef = getInjectorDef(container); const cmpDef = !injDef && getComponentDef(container); if (!injDef && !cmpDef) { // `container` is not an injector type or a component type. It might be: // * An `InjectorTypeWithProviders` that wraps an injector type. // * A standalone directive or pipe that got pulled in from a standalone component's // dependencies. // Try to unwrap it as an `InjectorTypeWithProviders` first. const ngModule: Type<unknown> | undefined = (container as InjectorTypeWithProviders<any>) .ngModule as Type<unknown> | undefined; injDef = getInjectorDef(ngModule); if (injDef) { defType = ngModule!; } else { // Not a component or injector type, so ignore it. return false; } } else if (cmpDef && !cmpDef.standalone) { return false; } else { defType = container as Type<unknown>; } // Check for circular dependencies. if (ngDevMode && parents.indexOf(defType) !== -1) { const defName = stringify(defType); const path = parents.map(stringify); throwCyclicDependencyError(defName, path); } // Check for multiple imports of the same module const isDuplicate = dedup.has(defType); if (cmpDef) { if (isDuplicate) { // This component definition has already been processed. return false; } dedup.add(defType); if (cmpDef.dependencies) { const deps = typeof cmpDef.dependencies === 'function' ? cmpDef.dependencies() : cmpDef.dependencies; for (const dep of deps) { walkProviderTree(dep, visitor, parents, dedup); } } } else if (injDef) { // First, include providers from any imports. if (injDef.imports != null && !isDuplicate) { // Before processing defType's imports, add it to the set of parents. This way, if it ends // up deeply importing itself, this can be detected. ngDevMode && parents.push(defType); // Add it to the set of dedups. This way we can detect multiple imports of the same module dedup.add(defType); let importTypesWithProviders: InjectorTypeWithProviders<any>[] | undefined; try { deepForEach(injDef.imports, (imported) => { if (walkProviderTree(imported, visitor, parents, dedup)) { importTypesWithProviders ||= []; // If the processed import is an injector type with providers, we store it in the // list of import types with providers, so that we can process those afterwards. importTypesWithProviders.push(imported); } }); } finally { // Remove it from the parents set when finished. ngDevMode && parents.pop(); } // Imports which are declared with providers (TypeWithProviders) need to be processed // after all imported modules are processed. This is similar to how View Engine // processes/merges module imports in the metadata resolver. See: FW-1349. if (importTypesWithProviders !== undefined) { processInjectorTypesWithProviders(importTypesWithProviders, visitor); } } if (!isDuplicate) { // Track the InjectorType and add a provider for it. // It's important that this is done after the def's imports. const factory = getFactoryDef(defType) || (() => new defType!()); // Append extra providers to make more info available for consumers (to retrieve an injector // type), as well as internally (to calculate an injection scope correctly and eagerly // instantiate a `defType` when an injector is created). // Provider to create `defType` using its factory. visitor({provide: defType, useFactory: factory, deps: EMPTY_ARRAY}, defType); // Make this `defType` available to an internal logic that calculates injector scope. visitor({provide: INJECTOR_DEF_TYPES, useValue: defType, multi: true}, defType); // Provider to eagerly instantiate `defType` via `INJECTOR_INITIALIZER`. visitor( {provide: ENVIRONMENT_INITIALIZER, useValue: () => inject(defType!), multi: true}, defType, ); } // Next, include providers listed on the definition itself. const defProviders = injDef.providers as Array<SingleProvider | InternalEnvironmentProviders>; if (defProviders != null && !isDuplicate) { const injectorType = container as InjectorType<any>; deepForEachProvider(defProviders, (provider) => { ngDevMode && validateProvider(provider as SingleProvider, defProviders, injectorType); visitor(provider, injectorType); }); } } else { // Should not happen, but just in case. return false; } return ( defType !== container && (container as InjectorTypeWithProviders<any>).providers !== undefined ); } function validateProvider( provider: SingleProvider, providers: Array<SingleProvider | InternalEnvironmentProviders>, containerType: Type<unknown>, ): void { if ( isTypeProvider(provider) || isValueProvider(provider) || isFactoryProvider(provider) || isExistingProvider(provider) ) { return; } // Here we expect the provider to be a `useClass` provider (by elimination). const classRef = resolveForwardRef( provider && ((provider as StaticClassProvider | ClassProvider).useClass || provider.provide), ); if (!classRef) { throwInvalidProviderError(containerType, providers, provider); } } function deepForEachProvider( providers: Array<Provider | InternalEnvironmentProviders>, fn: (provider: SingleProvider) => void, ): void { for (let provider of providers) { if (isEnvironmentProviders(provider)) { provider = provider.ɵproviders; } if (Array.isArray(provider)) { deepForEachProvider(provider, fn); } else { fn(provider); } } } export const USE_VALUE = getClosureSafeProperty<ValueProvider>({ provide: String, useValue: getClosureSafeProperty, }); export function isValueProvider(value: SingleProvider): value is ValueProvider { return value !== null && typeof value == 'object' && USE_VALUE in value; } export function isExistingProvider(value: SingleProvider): value is ExistingProvider { return !!(value && (value as ExistingProvider).useExisting); } export function isFactoryProvider(value: SingleProvider): value is FactoryProvider { return !!(value && (value as FactoryProvider).useFactory); } export function isTypeProvider(value: SingleProvider): value is TypeProvider { return typeof value === 'function'; } export function isClassProvider(value: SingleProvider): value is ClassProvider { return !!(value as StaticClassProvider | ClassProvider).useClass; }
{ "end_byte": 14566, "start_byte": 7377, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/provider_collection.ts" }
angular/packages/core/src/di/metadata_attr.ts_0_1638
/** * @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 {ɵɵinjectAttribute} from '../render3/instructions/di_attr'; import {makeParamDecorator} from '../util/decorators'; /** * Type of the Attribute decorator / constructor function. * * @publicApi */ export interface AttributeDecorator { /** * Parameter decorator for a directive constructor that designates * a host-element attribute whose value is injected as a constant string literal. * * @usageNotes * * Suppose we have an `<input>` element and want to know its `type`. * * ```html * <input type="text"> * ``` * * The following example uses the decorator to inject the string literal `text` in a directive. * * {@example core/ts/metadata/metadata.ts region='attributeMetadata'} * * The following example uses the decorator in a component constructor. * * {@example core/ts/metadata/metadata.ts region='attributeFactory'} * */ (name: string): any; new (name: string): Attribute; } /** * Type of the Attribute metadata. * * @publicApi */ export interface Attribute { /** * The name of the attribute whose value can be injected. */ attributeName: string; } /** * Attribute decorator and metadata. * * @Annotation * @publicApi */ export const Attribute: AttributeDecorator = makeParamDecorator( 'Attribute', (attributeName?: string) => ({ attributeName, __NG_ELEMENT_ID__: () => ɵɵinjectAttribute(attributeName!), }), );
{ "end_byte": 1638, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/metadata_attr.ts" }
angular/packages/core/src/di/injection_token.ts_0_3890
/** * @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} from '../interface/type'; import {assertLessThan} from '../util/assert'; import {ɵɵdefineInjectable} from './interface/defs'; /** * Creates a token that can be used in a DI Provider. * * Use an `InjectionToken` whenever the type you are injecting is not reified (does not have a * runtime representation) such as when injecting an interface, callable type, array or * parameterized type. * * `InjectionToken` is parameterized on `T` which is the type of object which will be returned by * the `Injector`. This provides an additional level of type safety. * * <div class="alert is-helpful"> * * **Important Note**: Ensure that you use the same instance of the `InjectionToken` in both the * provider and the injection call. Creating a new instance of `InjectionToken` in different places, * even with the same description, will be treated as different tokens by Angular's DI system, * leading to a `NullInjectorError`. * * </div> * * <code-example format="typescript" language="typescript" path="injection-token/src/main.ts" * region="InjectionToken"></code-example> * * When creating an `InjectionToken`, you can optionally specify a factory function which returns * (possibly by creating) a default value of the parameterized type `T`. This sets up the * `InjectionToken` using this factory as a provider as if it was defined explicitly in the * application's root injector. If the factory function, which takes zero arguments, needs to inject * dependencies, it can do so using the [`inject`](api/core/inject) function. * As you can see in the Tree-shakable InjectionToken example below. * * Additionally, if a `factory` is specified you can also specify the `providedIn` option, which * overrides the above behavior and marks the token as belonging to a particular `@NgModule` (note: * this option is now deprecated). As mentioned above, `'root'` is the default value for * `providedIn`. * * The `providedIn: NgModule` and `providedIn: 'any'` options are deprecated. * * @usageNotes * ### Basic Examples * * ### Plain InjectionToken * * {@example core/di/ts/injector_spec.ts region='InjectionToken'} * * ### Tree-shakable InjectionToken * * {@example core/di/ts/injector_spec.ts region='ShakableInjectionToken'} * * @publicApi */ export class InjectionToken<T> { /** @internal */ readonly ngMetadataName = 'InjectionToken'; readonly ɵprov: unknown; /** * @param _desc Description for the token, * used only for debugging purposes, * it should but does not need to be unique * @param options Options for the token's usage, as described above */ constructor( protected _desc: string, options?: { providedIn?: Type<any> | 'root' | 'platform' | 'any' | null; factory: () => T; }, ) { this.ɵprov = undefined; if (typeof options == 'number') { (typeof ngDevMode === 'undefined' || ngDevMode) && assertLessThan(options, 0, 'Only negative numbers are supported here'); // This is a special hack to assign __NG_ELEMENT_ID__ to this instance. // See `InjectorMarkers` (this as any).__NG_ELEMENT_ID__ = options; } else if (options !== undefined) { this.ɵprov = ɵɵdefineInjectable({ token: this, providedIn: options.providedIn || 'root', factory: options.factory, }); } } /** * @internal */ get multi(): InjectionToken<Array<T>> { return this as InjectionToken<Array<T>>; } toString(): string { return `InjectionToken ${this._desc}`; } } export interface InjectableDefToken<T> extends InjectionToken<T> { ɵprov: unknown; }
{ "end_byte": 3890, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injection_token.ts" }
angular/packages/core/src/di/contextual.ts_0_3021
/** * @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 {RuntimeError, RuntimeErrorCode} from '../errors'; import { InjectorProfilerContext, setInjectorProfilerContext, } from '../render3/debug/injector_profiler'; import {getInjectImplementation, setInjectImplementation} from './inject_switch'; import type {Injector} from './injector'; import {getCurrentInjector, setCurrentInjector} from './injector_compatibility'; import {assertNotDestroyed, R3Injector} from './r3_injector'; /** * Runs the given function in the [context](guide/di/dependency-injection-context) of the given * `Injector`. * * Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies * from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in * any asynchronous callbacks or after any `await` points. * * @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn` * is executing * @param fn the closure to be run in the context of `injector` * @returns the return value of the function, if any * @publicApi */ export function runInInjectionContext<ReturnT>(injector: Injector, fn: () => ReturnT): ReturnT { if (injector instanceof R3Injector) { assertNotDestroyed(injector); } let prevInjectorProfilerContext: InjectorProfilerContext; if (ngDevMode) { prevInjectorProfilerContext = setInjectorProfilerContext({injector, token: null}); } const prevInjector = setCurrentInjector(injector); const previousInjectImplementation = setInjectImplementation(undefined); try { return fn(); } finally { setCurrentInjector(prevInjector); ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext!); setInjectImplementation(previousInjectImplementation); } } /** * Whether the current stack frame is inside an injection context. */ export function isInInjectionContext(): boolean { return getInjectImplementation() !== undefined || getCurrentInjector() != null; } /** * Asserts that the current stack frame is within an [injection * context](guide/di/dependency-injection-context) and has access to `inject`. * * @param debugFn a reference to the function making the assertion (used for the error message). * * @publicApi */ export function assertInInjectionContext(debugFn: Function): void { // Taking a `Function` instead of a string name here prevents the unminified name of the function // from being retained in the bundle regardless of minification. if (!isInInjectionContext()) { throw new RuntimeError( RuntimeErrorCode.MISSING_INJECTION_CONTEXT, ngDevMode && debugFn.name + '() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`', ); } }
{ "end_byte": 3021, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/contextual.ts" }
angular/packages/core/src/di/injector_marker.ts_0_757
/** * @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 */ /** * Special markers which can be left on `Type.__NG_ELEMENT_ID__` which are used by the Ivy's * `NodeInjector`. Usually these markers contain factory functions. But in case of this special * marker we can't leave behind a function because it would create tree shaking problem. * * Currently only `Injector` is special. * * NOTE: the numbers here must be negative, because positive numbers are used as IDs for bloom * filter. */ export const enum InjectorMarkers { /** * Marks that the current type is `Injector` */ Injector = -1, }
{ "end_byte": 757, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injector_marker.ts" }
angular/packages/core/src/di/index.ts_0_1870
/** * @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 */ /** * @module * @description * The `di` module provides dependency injection container services. */ export * from './metadata'; export {assertInInjectionContext, runInInjectionContext} from './contextual'; export {InjectFlags} from './interface/injector'; export { ɵɵdefineInjectable, defineInjectable, ɵɵdefineInjector, InjectableType, InjectorType, } from './interface/defs'; export {forwardRef, resolveForwardRef, ForwardRefFn} from './forward_ref'; export {Injectable, InjectableDecorator, InjectableProvider} from './injectable'; export {Injector} from './injector'; export {EnvironmentInjector} from './r3_injector'; export { importProvidersFrom, ImportProvidersSource, makeEnvironmentProviders, provideEnvironmentInitializer, } from './provider_collection'; export {ENVIRONMENT_INITIALIZER} from './initializer_token'; export {ProviderToken} from './provider_token'; export {ɵɵinject, inject, ɵɵinvalidFactoryDep} from './injector_compatibility'; export {InjectOptions} from './interface/injector'; export {INJECTOR} from './injector_token'; export { ClassProvider, ModuleWithProviders, ClassSansProvider, ImportedNgModuleProviders, ConstructorProvider, EnvironmentProviders, ConstructorSansProvider, ExistingProvider, ExistingSansProvider, FactoryProvider, FactorySansProvider, Provider, StaticClassProvider, StaticClassSansProvider, StaticProvider, TypeProvider, ValueProvider, ValueSansProvider, } from './interface/provider'; export {InjectionToken} from './injection_token'; export {HostAttributeToken} from './host_attribute_token'; export {HOST_TAG_NAME} from './host_tag_name_token';
{ "end_byte": 1870, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/index.ts" }
angular/packages/core/src/di/metadata.ts_0_6533
/** * @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 {makeParamDecorator} from '../util/decorators'; import {attachInjectFlag} from './injector_compatibility'; import {DecoratorFlags, InternalInjectFlags} from './interface/injector'; /** * Type of the Inject decorator / constructor function. * * @publicApi */ export interface InjectDecorator { /** * Parameter decorator on a dependency parameter of a class constructor * that specifies a custom provider of the dependency. * * @usageNotes * The following example shows a class constructor that specifies a * custom provider of a dependency using the parameter decorator. * * When `@Inject()` is not present, the injector uses the type annotation of the * parameter as the provider. * * <code-example path="core/di/ts/metadata_spec.ts" region="InjectWithoutDecorator"> * </code-example> * * @see [Dependency Injection Guide](guide/di/dependency-injection * */ (token: any): any; new (token: any): Inject; } /** * Type of the Inject metadata. * * @publicApi */ export interface Inject { /** * A DI token that maps to the dependency to be injected. */ token: any; } /** * Inject decorator and metadata. * * @Annotation * @publicApi */ export const Inject: InjectDecorator = attachInjectFlag( // Disable tslint because `DecoratorFlags` is a const enum which gets inlined. makeParamDecorator('Inject', (token: any) => ({token})), // tslint:disable-next-line: no-toplevel-property-access DecoratorFlags.Inject, ); /** * Type of the Optional decorator / constructor function. * * @publicApi */ export interface OptionalDecorator { /** * Parameter decorator to be used on constructor parameters, * which marks the parameter as being an optional dependency. * The DI framework provides `null` if the dependency is not found. * * Can be used together with other parameter decorators * that modify how dependency injection operates. * * @usageNotes * * The following code allows the possibility of a `null` result: * * <code-example path="core/di/ts/metadata_spec.ts" region="Optional"> * </code-example> * * @see [Dependency Injection Guide](guide/di/dependency-injection. */ (): any; new (): Optional; } /** * Type of the Optional metadata. * * @publicApi */ export interface Optional {} /** * Optional decorator and metadata. * * @Annotation * @publicApi */ export const Optional: OptionalDecorator = // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined. // tslint:disable-next-line: no-toplevel-property-access attachInjectFlag(makeParamDecorator('Optional'), InternalInjectFlags.Optional); /** * Type of the Self decorator / constructor function. * * @publicApi */ export interface SelfDecorator { /** * Parameter decorator to be used on constructor parameters, * which tells the DI framework to start dependency resolution from the local injector. * * Resolution works upward through the injector hierarchy, so the children * of this class must configure their own providers or be prepared for a `null` result. * * @usageNotes * * In the following example, the dependency can be resolved * by the local injector when instantiating the class itself, but not * when instantiating a child. * * <code-example path="core/di/ts/metadata_spec.ts" region="Self"> * </code-example> * * @see {@link SkipSelf} * @see {@link Optional} * */ (): any; new (): Self; } /** * Type of the Self metadata. * * @publicApi */ export interface Self {} /** * Self decorator and metadata. * * @Annotation * @publicApi */ export const Self: SelfDecorator = // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined. // tslint:disable-next-line: no-toplevel-property-access attachInjectFlag(makeParamDecorator('Self'), InternalInjectFlags.Self); /** * Type of the `SkipSelf` decorator / constructor function. * * @publicApi */ export interface SkipSelfDecorator { /** * Parameter decorator to be used on constructor parameters, * which tells the DI framework to start dependency resolution from the parent injector. * Resolution works upward through the injector hierarchy, so the local injector * is not checked for a provider. * * @usageNotes * * In the following example, the dependency can be resolved when * instantiating a child, but not when instantiating the class itself. * * <code-example path="core/di/ts/metadata_spec.ts" region="SkipSelf"> * </code-example> * * @see [Dependency Injection guide](guide/di/di-in-action#skip). * @see {@link Self} * @see {@link Optional} * */ (): any; new (): SkipSelf; } /** * Type of the `SkipSelf` metadata. * * @publicApi */ export interface SkipSelf {} /** * `SkipSelf` decorator and metadata. * * @Annotation * @publicApi */ export const SkipSelf: SkipSelfDecorator = // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined. // tslint:disable-next-line: no-toplevel-property-access attachInjectFlag(makeParamDecorator('SkipSelf'), InternalInjectFlags.SkipSelf); /** * Type of the `Host` decorator / constructor function. * * @publicApi */ export interface HostDecorator { /** * Parameter decorator on a view-provider parameter of a class constructor * that tells the DI framework to resolve the view by checking injectors of child * elements, and stop when reaching the host element of the current component. * * @usageNotes * * The following shows use with the `@Optional` decorator, and allows for a `null` result. * * <code-example path="core/di/ts/metadata_spec.ts" region="Host"> * </code-example> * * For an extended example, see ["Dependency Injection * Guide"](guide/di/di-in-action#optional). */ (): any; new (): Host; } /** * Type of the Host metadata. * * @publicApi */ export interface Host {} /** * Host decorator and metadata. * * @Annotation * @publicApi */ export const Host: HostDecorator = // Disable tslint because `InternalInjectFlags` is a const enum which gets inlined. // tslint:disable-next-line: no-toplevel-property-access attachInjectFlag(makeParamDecorator('Host'), InternalInjectFlags.Host);
{ "end_byte": 6533, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/metadata.ts" }
angular/packages/core/src/di/create_injector.ts_0_1864
/** * @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 {EMPTY_ARRAY} from '../util/empty'; import {stringify} from '../util/stringify'; import type {Injector} from './injector'; import type {Provider, StaticProvider} from './interface/provider'; import {importProvidersFrom} from './provider_collection'; import {getNullInjector, R3Injector} from './r3_injector'; import {InjectorScope} from './scope'; /** * Create a new `Injector` which is configured using a `defType` of `InjectorType<any>`s. */ export function createInjector( defType: /* InjectorType<any> */ any, parent: Injector | null = null, additionalProviders: Array<Provider | StaticProvider> | null = null, name?: string, ): Injector { const injector = createInjectorWithoutInjectorInstances( defType, parent, additionalProviders, name, ); injector.resolveInjectorInitializers(); return injector; } /** * Creates a new injector without eagerly resolving its injector types. Can be used in places * where resolving the injector types immediately can lead to an infinite loop. The injector types * should be resolved at a later point by calling `_resolveInjectorDefTypes`. */ export function createInjectorWithoutInjectorInstances( defType: /* InjectorType<any> */ any, parent: Injector | null = null, additionalProviders: Array<Provider | StaticProvider> | null = null, name?: string, scopes = new Set<InjectorScope>(), ): R3Injector { const providers = [additionalProviders || EMPTY_ARRAY, importProvidersFrom(defType)]; name = name || (typeof defType === 'object' ? undefined : stringify(defType)); return new R3Injector(providers, parent || getNullInjector(), name || null, scopes); }
{ "end_byte": 1864, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/create_injector.ts" }
angular/packages/core/src/di/provider_token.ts_0_518
/** * @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 {AbstractType, Type} from '../interface/type'; import {InjectionToken} from './injection_token'; /** * @description * * Token that can be used to retrieve an instance from an injector or through a query. * * @publicApi */ export type ProviderToken<T> = Type<T> | AbstractType<T> | InjectionToken<T>;
{ "end_byte": 518, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/provider_token.ts" }
angular/packages/core/src/di/injector_token.ts_0_906
/** * @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 {InjectionToken} from './injection_token'; import type {Injector} from './injector'; import {InjectorMarkers} from './injector_marker'; /** * An InjectionToken that gets the current `Injector` for `createInjector()`-style injectors. * * Requesting this token instead of `Injector` allows `StaticInjector` to be tree-shaken from a * project. * * @publicApi */ export const INJECTOR = new InjectionToken<Injector>( ngDevMode ? 'INJECTOR' : '', // Disable tslint because this is const enum which gets inlined not top level prop access. // tslint:disable-next-line: no-toplevel-property-access InjectorMarkers.Injector as any, // Special value used by Ivy to identify `Injector`. );
{ "end_byte": 906, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injector_token.ts" }
angular/packages/core/src/di/internal_tokens.ts_0_424
/** * @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} from '../interface/type'; import {InjectionToken} from './injection_token'; export const INJECTOR_DEF_TYPES = new InjectionToken<ReadonlyArray<Type<unknown>>>( ngDevMode ? 'INJECTOR_DEF_TYPES' : '', );
{ "end_byte": 424, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/internal_tokens.ts" }
angular/packages/core/src/di/injector_compatibility.ts_0_7900
/** * @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 '../util/ng_dev_mode'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import {Type} from '../interface/type'; import {emitInjectEvent} from '../render3/debug/injector_profiler'; import {stringify} from '../util/stringify'; import {resolveForwardRef} from './forward_ref'; import {getInjectImplementation, injectRootLimpMode} from './inject_switch'; import type {Injector} from './injector'; import { DecoratorFlags, InjectFlags, InjectOptions, InternalInjectFlags, } from './interface/injector'; import {ProviderToken} from './provider_token'; import type {HostAttributeToken} from './host_attribute_token'; const _THROW_IF_NOT_FOUND = {}; export const THROW_IF_NOT_FOUND = _THROW_IF_NOT_FOUND; /* * Name of a property (that we patch onto DI decorator), which is used as an annotation of which * InjectFlag this decorator represents. This allows to avoid direct references to the DI decorators * in the code, thus making them tree-shakable. */ const DI_DECORATOR_FLAG = '__NG_DI_FLAG__'; export const NG_TEMP_TOKEN_PATH = 'ngTempTokenPath'; const NG_TOKEN_PATH = 'ngTokenPath'; const NEW_LINE = /\n/gm; const NO_NEW_LINE = 'ɵ'; export const SOURCE = '__source'; /** * Current injector value used by `inject`. * - `undefined`: it is an error to call `inject` * - `null`: `inject` can be called but there is no injector (limp-mode). * - Injector instance: Use the injector for resolution. */ let _currentInjector: Injector | undefined | null = undefined; export function getCurrentInjector(): Injector | undefined | null { return _currentInjector; } export function setCurrentInjector( injector: Injector | null | undefined, ): Injector | undefined | null { const former = _currentInjector; _currentInjector = injector; return former; } export function injectInjectorOnly<T>(token: ProviderToken<T>): T; export function injectInjectorOnly<T>(token: ProviderToken<T>, flags?: InjectFlags): T | null; export function injectInjectorOnly<T>( token: ProviderToken<T>, flags = InjectFlags.Default, ): T | null { if (_currentInjector === undefined) { throw new RuntimeError( RuntimeErrorCode.MISSING_INJECTION_CONTEXT, ngDevMode && `inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with \`runInInjectionContext\`.`, ); } else if (_currentInjector === null) { return injectRootLimpMode(token, undefined, flags); } else { const value = _currentInjector.get( token, flags & InjectFlags.Optional ? null : undefined, flags, ); ngDevMode && emitInjectEvent(token as Type<unknown>, value, flags); return value; } } /** * Generated instruction: injects a token from the currently active injector. * * (Additional documentation moved to `inject`, as it is the public API, and an alias for this * instruction) * * @see inject * @codeGenApi * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm. */ export function ɵɵinject<T>(token: ProviderToken<T>): T; export function ɵɵinject<T>(token: ProviderToken<T>, flags?: InjectFlags): T | null; export function ɵɵinject(token: HostAttributeToken): string; export function ɵɵinject(token: HostAttributeToken, flags?: InjectFlags): string | null; export function ɵɵinject<T>( token: ProviderToken<T> | HostAttributeToken, flags?: InjectFlags, ): string | null; export function ɵɵinject<T>( token: ProviderToken<T> | HostAttributeToken, flags = InjectFlags.Default, ): T | null { return (getInjectImplementation() || injectInjectorOnly)( resolveForwardRef(token as Type<T>), flags, ); } /** * Throws an error indicating that a factory function could not be generated by the compiler for a * particular class. * * The name of the class is not mentioned here, but will be in the generated factory function name * and thus in the stack trace. * * @codeGenApi */ export function ɵɵinvalidFactoryDep(index: number): never { throw new RuntimeError( RuntimeErrorCode.INVALID_FACTORY_DEPENDENCY, ngDevMode && `This constructor is not compatible with Angular Dependency Injection because its dependency at index ${index} of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index ${index} is correct and 2) the correct Angular decorators are defined for this class and its ancestors.`, ); } /** * @param token A token that represents a dependency that should be injected. * @returns the injected value if operation is successful, `null` otherwise. * @throws if called outside of a supported context. * * @publicApi */ export function inject<T>(token: ProviderToken<T>): T; /** * @param token A token that represents a dependency that should be injected. * @param flags Control how injection is executed. The flags correspond to injection strategies that * can be specified with parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`. * @returns the injected value if operation is successful, `null` otherwise. * @throws if called outside of a supported context. * * @publicApi * @deprecated prefer an options object instead of `InjectFlags` */ export function inject<T>(token: ProviderToken<T>, flags?: InjectFlags): T | null; /** * @param token A token that represents a dependency that should be injected. * @param options Control how injection is executed. Options correspond to injection strategies * that can be specified with parameter decorators `@Host`, `@Self`, `@SkipSelf`, and * `@Optional`. * @returns the injected value if operation is successful. * @throws if called outside of a supported context, or if the token is not found. * * @publicApi */ export function inject<T>(token: ProviderToken<T>, options: InjectOptions & {optional?: false}): T; /** * @param token A token that represents a dependency that should be injected. * @param options Control how injection is executed. Options correspond to injection strategies * that can be specified with parameter decorators `@Host`, `@Self`, `@SkipSelf`, and * `@Optional`. * @returns the injected value if operation is successful, `null` if the token is not * found and optional injection has been requested. * @throws if called outside of a supported context, or if the token is not found and optional * injection was not requested. * * @publicApi */ export function inject<T>(token: ProviderToken<T>, options: InjectOptions): T | null; /** * @param token A token that represents a static attribute on the host node that should be injected. * @returns Value of the attribute if it exists. * @throws If called outside of a supported context or the attribute does not exist. * * @publicApi */ export function inject(token: HostAttributeToken): string; /** * @param token A token that represents a static attribute on the host node that should be injected. * @returns Value of the attribute if it exists, otherwise `null`. * @throws If called outside of a supported context. * * @publicApi */ export function inject(token: HostAttributeToken, options: {optional: true}): string | null; /** * @param token A token that represents a static attribute on the host node that should be injected. * @returns Value of the attribute if it exists. * @throws If called outside of a supported context or the attribute does not exist. * * @publicApi */ export function inject(token: HostAttributeToken, options: {optional: false}): string; /** * Injects
{ "end_byte": 7900, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injector_compatibility.ts" }
angular/packages/core/src/di/injector_compatibility.ts_7901_14509
a token from the currently active injector. * `inject` is only supported in an [injection context](guide/di/dependency-injection-context). It * can be used during: * - Construction (via the `constructor`) of a class being instantiated by the DI system, such * as an `@Injectable` or `@Component`. * - In the initializer for fields of such classes. * - In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`. * - In the `factory` function specified for an `InjectionToken`. * - In a stackframe of a function call in a DI context * * @param token A token that represents a dependency that should be injected. * @param flags Optional flags that control how injection is executed. * The flags correspond to injection strategies that can be specified with * parameter decorators `@Host`, `@Self`, `@SkipSelf`, and `@Optional`. * @returns the injected value if operation is successful, `null` otherwise. * @throws if called outside of a supported context. * * @usageNotes * In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a * field initializer: * * ```typescript * @Injectable({providedIn: 'root'}) * export class Car { * radio: Radio|undefined; * // OK: field initializer * spareTyre = inject(Tyre); * * constructor() { * // OK: constructor body * this.radio = inject(Radio); * } * } * ``` * * It is also legal to call `inject` from a provider's factory: * * ```typescript * providers: [ * {provide: Car, useFactory: () => { * // OK: a class factory * const engine = inject(Engine); * return new Car(engine); * }} * ] * ``` * * Calls to the `inject()` function outside of the class creation context will result in error. Most * notably, calls to `inject()` are disallowed after a class instance was created, in methods * (including lifecycle hooks): * * ```typescript * @Component({ ... }) * export class CarComponent { * ngOnInit() { * // ERROR: too late, the component instance was already created * const engine = inject(Engine); * engine.start(); * } * } * ``` * * @publicApi */ export function inject<T>( token: ProviderToken<T> | HostAttributeToken, flags: InjectFlags | InjectOptions = InjectFlags.Default, ) { // The `as any` here _shouldn't_ be necessary, but without it JSCompiler // throws a disambiguation error due to the multiple signatures. return ɵɵinject(token as any, convertToBitFlags(flags)); } // Converts object-based DI flags (`InjectOptions`) to bit flags (`InjectFlags`). export function convertToBitFlags( flags: InjectOptions | InjectFlags | undefined, ): InjectFlags | undefined { if (typeof flags === 'undefined' || typeof flags === 'number') { return flags; } // While TypeScript doesn't accept it without a cast, bitwise OR with false-y values in // JavaScript is a no-op. We can use that for a very codesize-efficient conversion from // `InjectOptions` to `InjectFlags`. return (InternalInjectFlags.Default | // comment to force a line break in the formatter ((flags.optional && InternalInjectFlags.Optional) as number) | ((flags.host && InternalInjectFlags.Host) as number) | ((flags.self && InternalInjectFlags.Self) as number) | ((flags.skipSelf && InternalInjectFlags.SkipSelf) as number)) as InjectFlags; } export function injectArgs(types: (ProviderToken<any> | any[])[]): any[] { const args: any[] = []; for (let i = 0; i < types.length; i++) { const arg = resolveForwardRef(types[i]); if (Array.isArray(arg)) { if (arg.length === 0) { throw new RuntimeError( RuntimeErrorCode.INVALID_DIFFER_INPUT, ngDevMode && 'Arguments array must have arguments.', ); } let type: Type<any> | undefined = undefined; let flags: InjectFlags = InjectFlags.Default; for (let j = 0; j < arg.length; j++) { const meta = arg[j]; const flag = getInjectFlag(meta); if (typeof flag === 'number') { // Special case when we handle @Inject decorator. if (flag === DecoratorFlags.Inject) { type = meta.token; } else { flags |= flag; } } else { type = meta; } } args.push(ɵɵinject(type!, flags)); } else { args.push(ɵɵinject(arg)); } } return args; } /** * Attaches a given InjectFlag to a given decorator using monkey-patching. * Since DI decorators can be used in providers `deps` array (when provider is configured using * `useFactory`) without initialization (e.g. `Host`) and as an instance (e.g. `new Host()`), we * attach the flag to make it available both as a static property and as a field on decorator * instance. * * @param decorator Provided DI decorator. * @param flag InjectFlag that should be applied. */ export function attachInjectFlag(decorator: any, flag: InternalInjectFlags | DecoratorFlags): any { decorator[DI_DECORATOR_FLAG] = flag; decorator.prototype[DI_DECORATOR_FLAG] = flag; return decorator; } /** * Reads monkey-patched property that contains InjectFlag attached to a decorator. * * @param token Token that may contain monkey-patched DI flags property. */ export function getInjectFlag(token: any): number | undefined { return token[DI_DECORATOR_FLAG]; } export function catchInjectorError( e: any, token: any, injectorErrorName: string, source: string | null, ): never { const tokenPath: any[] = e[NG_TEMP_TOKEN_PATH]; if (token[SOURCE]) { tokenPath.unshift(token[SOURCE]); } e.message = formatError('\n' + e.message, tokenPath, injectorErrorName, source); e[NG_TOKEN_PATH] = tokenPath; e[NG_TEMP_TOKEN_PATH] = null; throw e; } export function formatError( text: string, obj: any, injectorErrorName: string, source: string | null = null, ): string { text = text && text.charAt(0) === '\n' && text.charAt(1) == NO_NEW_LINE ? text.slice(2) : text; let context = stringify(obj); if (Array.isArray(obj)) { context = obj.map(stringify).join(' -> '); } else if (typeof obj === 'object') { let parts = <string[]>[]; for (let key in obj) { if (obj.hasOwnProperty(key)) { let value = obj[key]; parts.push( key + ':' + (typeof value === 'string' ? JSON.stringify(value) : stringify(value)), ); } } context = `{${parts.join(', ')}}`; } return `${injectorErrorName}${source ? '(' + source + ')' : ''}[${context}]: ${text.replace( NEW_LINE, '\n ', )}`; }
{ "end_byte": 14509, "start_byte": 7901, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injector_compatibility.ts" }
angular/packages/core/src/di/injectable.ts_0_3306
/** * @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} from '../interface/type'; import {makeDecorator, TypeDecorator} from '../util/decorators'; import { ClassSansProvider, ConstructorSansProvider, ExistingSansProvider, FactorySansProvider, StaticClassSansProvider, ValueSansProvider, } from './interface/provider'; import {compileInjectable} from './jit/injectable'; export {compileInjectable}; /** * Injectable providers used in `@Injectable` decorator. * * @publicApi */ export type InjectableProvider = | ValueSansProvider | ExistingSansProvider | StaticClassSansProvider | ConstructorSansProvider | FactorySansProvider | ClassSansProvider; /** * Type of the Injectable decorator / constructor function. * * @publicApi */ export interface InjectableDecorator { /** * Decorator that marks a class as available to be * provided and injected as a dependency. * * @see [Introduction to Services and DI](guide/di) * @see [Dependency Injection Guide](guide/di/dependency-injection * * @usageNotes * * Marking a class with `@Injectable` ensures that the compiler * will generate the necessary metadata to create the class's * dependencies when the class is injected. * * The following example shows how a service class is properly * marked so that a supporting service can be injected upon creation. * * <code-example path="core/di/ts/metadata_spec.ts" region="Injectable"></code-example> * */ (): TypeDecorator; ( options?: {providedIn: Type<any> | 'root' | 'platform' | 'any' | null} & InjectableProvider, ): TypeDecorator; new (): Injectable; new ( options?: {providedIn: Type<any> | 'root' | 'platform' | 'any' | null} & InjectableProvider, ): Injectable; } /** * Type of the Injectable metadata. * * @publicApi */ export interface Injectable { /** * Determines which injectors will provide the injectable. * * - `Type<any>` - associates the injectable with an `@NgModule` or other `InjectorType`. This * option is DEPRECATED. * - 'null' : Equivalent to `undefined`. The injectable is not provided in any scope automatically * and must be added to a `providers` array of an [@NgModule](api/core/NgModule#providers), * [@Component](api/core/Directive#providers) or [@Directive](api/core/Directive#providers). * * The following options specify that this injectable should be provided in one of the following * injectors: * - 'root' : The application-level injector in most apps. * - 'platform' : A special singleton platform injector shared by all * applications on the page. * - 'any' : Provides a unique instance in each lazy loaded module while all eagerly loaded * modules share one instance. This option is DEPRECATED. * */ providedIn?: Type<any> | 'root' | 'platform' | 'any' | null; } /** * Injectable decorator and metadata. * * @Annotation * @publicApi */ export const Injectable: InjectableDecorator = makeDecorator( 'Injectable', undefined, undefined, undefined, (type: Type<any>, meta: Injectable) => compileInjectable(type as any, meta), );
{ "end_byte": 3306, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/injectable.ts" }
angular/packages/core/src/di/interface/injector.ts_0_3380
/** * @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 */ /** * Special flag indicating that a decorator is of type `Inject`. It's used to make `Inject` * decorator tree-shakable (so we don't have to rely on the `instanceof` checks). * Note: this flag is not included into the `InjectFlags` since it's an internal-only API. */ export const enum DecoratorFlags { Inject = -1, } /** * Injection flags for DI. * * @publicApi * @deprecated use an options object for [`inject`](api/core/inject) instead. */ export enum InjectFlags { // TODO(alxhub): make this 'const' (and remove `InternalInjectFlags` enum) when ngc no longer // writes exports of it into ngfactory files. /** Check self and check parent injector if needed */ Default = 0b0000, /** * Specifies that an injector should retrieve a dependency from any injector until reaching the * host element of the current component. (Only used with Element Injector) */ Host = 0b0001, /** Don't ascend to ancestors of the node requesting injection. */ Self = 0b0010, /** Skip the node that is requesting injection. */ SkipSelf = 0b0100, /** Inject `defaultValue` instead if token not found. */ Optional = 0b1000, } /** * This enum is an exact copy of the `InjectFlags` enum above, but the difference is that this is a * const enum, so actual enum values would be inlined in generated code. The `InjectFlags` enum can * be turned into a const enum when ViewEngine is removed (see TODO at the `InjectFlags` enum * above). The benefit of inlining is that we can use these flags at the top level without affecting * tree-shaking (see "no-toplevel-property-access" tslint rule for more info). * Keep this enum in sync with `InjectFlags` enum above. */ export const enum InternalInjectFlags { /** Check self and check parent injector if needed */ Default = 0b0000, /** * Specifies that an injector should retrieve a dependency from any injector until reaching the * host element of the current component. (Only used with Element Injector) */ Host = 0b0001, /** Don't ascend to ancestors of the node requesting injection. */ Self = 0b0010, /** Skip the node that is requesting injection. */ SkipSelf = 0b0100, /** Inject `defaultValue` instead if token not found. */ Optional = 0b1000, /** * This token is being injected into a pipe. * * This flag is intentionally not in the public facing `InjectFlags` because it is only added by * the compiler and is not a developer applicable flag. */ ForPipe = 0b10000, } /** * Type of the options argument to [`inject`](api/core/inject). * * @publicApi */ export interface InjectOptions { /** * Use optional injection, and return `null` if the requested token is not found. */ optional?: boolean; /** * Start injection at the parent of the current injector. */ skipSelf?: boolean; /** * Only query the current injector for the token, and don't fall back to the parent injector if * it's not found. */ self?: boolean; /** * Stop injection at the host component's injector. Only relevant when injecting from an element * injector, and a no-op for environment injectors. */ host?: boolean; }
{ "end_byte": 3380, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/injector.ts" }
angular/packages/core/src/di/interface/BUILD.bazel_0_690
load("//tools:defaults.bzl", "ts_library", "tsec_test") package(default_visibility = [ "//devtools:__subpackages__", "//packages:__pkg__", "//packages/core:__subpackages__", "//tools/public_api_guard:__pkg__", ]) ts_library( name = "interface", srcs = glob( [ "**/*.ts", ], ), deps = [ "//packages/core/src/interface", "//packages/core/src/util", "@npm//rxjs", ], ) tsec_test( name = "tsec_test", target = "interface", tsconfig = "//packages:tsec_config", ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", ]), visibility = ["//visibility:public"], )
{ "end_byte": 690, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/BUILD.bazel" }
angular/packages/core/src/di/interface/provider.ts_0_8254
/** * @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} from '../../interface/type'; /** * Configures the `Injector` to return a value for a token. * Base for `ValueProvider` decorator. * * @publicApi */ export interface ValueSansProvider { /** * The value to inject. */ useValue: any; } /** * Configures the `Injector` to return a value for a token. * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * ### Example * * {@example core/di/ts/provider_spec.ts region='ValueProvider'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */ export interface ValueProvider extends ValueSansProvider { /** * An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`. */ provide: any; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Configures the `Injector` to return an instance of `useClass` for a token. * Base for `StaticClassProvider` decorator. * * @publicApi */ export interface StaticClassSansProvider { /** * An optional class to instantiate for the `token`. By default, the `provide` * class is instantiated. */ useClass: Type<any>; /** * A list of `token`s to be resolved by the injector. The list of values is then * used as arguments to the `useClass` constructor. */ deps: any[]; } /** * Configures the `Injector` to return an instance of `useClass` for a token. * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='StaticClassProvider'} * * Note that following two providers are not equal: * * {@example core/di/ts/provider_spec.ts region='StaticClassProviderDifference'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */ export interface StaticClassProvider extends StaticClassSansProvider { /** * An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`. */ provide: any; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Configures the `Injector` to return an instance of a token. * * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * ```ts * @Injectable(SomeModule, {deps: []}) * class MyService {} * ``` * * @publicApi */ export interface ConstructorSansProvider { /** * A list of `token`s to be resolved by the injector. */ deps?: any[]; } /** * Configures the `Injector` to return an instance of a token. * * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='ConstructorProvider'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */ export interface ConstructorProvider extends ConstructorSansProvider { /** * An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`. */ provide: Type<any>; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Configures the `Injector` to return a value of another `useExisting` token. * * @see {@link ExistingProvider} * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @publicApi */ export interface ExistingSansProvider { /** * Existing `token` to return. (Equivalent to `injector.get(useExisting)`) */ useExisting: any; } /** * Configures the `Injector` to return a value of another `useExisting` token. * * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='ExistingProvider'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */ export interface ExistingProvider extends ExistingSansProvider { /** * An injection token. Typically an instance of `Type` or `InjectionToken`, but can be `any`. */ provide: any; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Configures the `Injector` to return a value by invoking a `useFactory` function. * * @see {@link FactoryProvider} * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @publicApi */ export interface FactorySansProvider { /** * A function to invoke to create a value for this `token`. The function is invoked with * resolved values of `token`s in the `deps` field. */ useFactory: Function; /** * A list of `token`s to be resolved by the injector. The list of values is then * used as arguments to the `useFactory` function. */ deps?: any[]; } /** * Configures the `Injector` to return a value by invoking a `useFactory` function. * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='FactoryProvider'} * * Dependencies can also be marked as optional: * * {@example core/di/ts/provider_spec.ts region='FactoryProviderOptionalDeps'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */ export interface FactoryProvider extends FactorySansProvider { /** * An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`). */ provide: any; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Describes how an `Injector` should be configured as static (that is, without reflection). * A static provider provides tokens to an injector for various types of dependencies. * * @see {@link Injector.create()} * @see [Dependency Injection Guide](guide/di/dependency-injection-providers). * * @publicApi */ export type StaticProvider = | ValueProvider | ExistingProvider | StaticClassProvider | ConstructorProvider | FactoryProvider | any[]; /** * Configures the `Injector` to return an instance of `Type` when `Type' is used as the token. * * Create an instance by invoking the `new` operator and supplying additional arguments. * This form is a short form of `TypeProvider`; * * For more details, see the ["Dependency Injection Guide"](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='TypeProvider'} * * @publicApi */ export interface TypeProvider extends Type<any> {} /** * Configures the `Injector` to return a value by invoking a `useClass` function. * Base for `ClassProvider` decorator. * * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @publicApi */ export interface ClassSansProvider { /** * Class to instantiate for the `token`. */ useClass: Type<any>; } /** * Configures the `Injector` to return an instance of `useClass` for a token. * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @usageNotes * * {@example core/di/ts/provider_spec.ts region='ClassProvider'} * * Note that following two providers are not equal: * * {@example core/di/ts/provider_spec.ts region='ClassProviderDifference'} * * ### Multi-value example * * {@example core/di/ts/provider_spec.ts region='MultiProviderAspect'} * * @publicApi */
{ "end_byte": 8254, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/provider.ts" }
angular/packages/core/src/di/interface/provider.ts_8255_11196
export interface ClassProvider extends ClassSansProvider { /** * An injection token. (Typically an instance of `Type` or `InjectionToken`, but can be `any`). */ provide: any; /** * When true, injector returns an array of instances. This is useful to allow multiple * providers spread across many files to provide configuration information to a common token. */ multi?: boolean; } /** * Describes how the `Injector` should be configured. * @see [Dependency Injection Guide](guide/di/dependency-injection. * * @see {@link StaticProvider} * * @publicApi */ export type Provider = | TypeProvider | ValueProvider | ClassProvider | ConstructorProvider | ExistingProvider | FactoryProvider | any[]; /** * Encapsulated `Provider`s that are only accepted during creation of an `EnvironmentInjector` (e.g. * in an `NgModule`). * * Using this wrapper type prevents providers which are only designed to work in * application/environment injectors from being accidentally included in * `@Component.providers` and ending up in a component injector. * * This wrapper type prevents access to the `Provider`s inside. * * @see {@link makeEnvironmentProviders} * @see {@link importProvidersFrom} * * @publicApi */ export type EnvironmentProviders = { ɵbrand: 'EnvironmentProviders'; }; export interface InternalEnvironmentProviders extends EnvironmentProviders { ɵproviders: (Provider | EnvironmentProviders)[]; /** * If present, indicates that the `EnvironmentProviders` were derived from NgModule providers. * * This is used to produce clearer error messages. */ ɵfromNgModule?: true; } export function isEnvironmentProviders( value: Provider | EnvironmentProviders | InternalEnvironmentProviders, ): value is InternalEnvironmentProviders { return value && !!(value as InternalEnvironmentProviders).ɵproviders; } /** * Describes a function that is used to process provider lists (such as provider * overrides). */ export type ProcessProvidersFunction = (providers: Provider[]) => Provider[]; /** * A wrapper around an NgModule that associates it with providers * Usage without a generic type is deprecated. * * @publicApi */ export interface ModuleWithProviders<T> { ngModule: Type<T>; providers?: Array<Provider | EnvironmentProviders>; } /** * Providers that were imported from NgModules via the `importProvidersFrom` function. * * These providers are meant for use in an application injector (or other environment injectors) and * should not be used in component injectors. * * This type cannot be directly implemented. It's returned from the `importProvidersFrom` function * and serves to prevent the extracted NgModule providers from being used in the wrong contexts. * * @see {@link importProvidersFrom} * * @publicApi * @deprecated replaced by `EnvironmentProviders` */ export type ImportedNgModuleProviders = EnvironmentProviders;
{ "end_byte": 11196, "start_byte": 8255, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/provider.ts" }
angular/packages/core/src/di/interface/defs.ts_0_7740
/** * @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} from '../../interface/type'; import {getClosureSafeProperty} from '../../util/property'; import { ClassProvider, ConstructorProvider, EnvironmentProviders, ExistingProvider, FactoryProvider, StaticClassProvider, ValueProvider, } from './provider'; /** * Information about how a type or `InjectionToken` interfaces with the DI system. * * At a minimum, this includes a `factory` which defines how to create the given type `T`, possibly * requesting injection of other types if necessary. * * Optionally, a `providedIn` parameter specifies that the given type belongs to a particular * `Injector`, `NgModule`, or a special scope (e.g. `'root'`). A value of `null` indicates * that the injectable does not belong to any scope. * * @codeGenApi * @publicApi The ViewEngine compiler emits code with this type for injectables. This code is * deployed to npm, and should be treated as public api. */ export interface ɵɵInjectableDeclaration<T> { /** * Specifies that the given type belongs to a particular injector: * - `InjectorType` such as `NgModule`, * - `'root'` the root injector * - `'any'` all injectors. * - `null`, does not belong to any injector. Must be explicitly listed in the injector * `providers`. */ providedIn: InjectorType<any> | 'root' | 'platform' | 'any' | 'environment' | null; /** * The token to which this definition belongs. * * Note that this may not be the same as the type that the `factory` will create. */ token: unknown; /** * Factory method to execute to create an instance of the injectable. */ factory: (t?: Type<any>) => T; /** * In a case of no explicit injector, a location where the instance of the injectable is stored. */ value: T | undefined; } /** * Information about the providers to be included in an `Injector` as well as how the given type * which carries the information should be created by the DI system. * * An `InjectorDef` can import other types which have `InjectorDefs`, forming a deep nested * structure of providers with a defined priority (identically to how `NgModule`s also have * an import/dependency structure). * * NOTE: This is a private type and should not be exported * * @codeGenApi */ export interface ɵɵInjectorDef<T> { // TODO(alxhub): Narrow down the type here once decorators properly change the return type of the // class they are decorating (to add the ɵprov property for example). providers: ( | Type<any> | ValueProvider | ExistingProvider | FactoryProvider | ConstructorProvider | StaticClassProvider | ClassProvider | EnvironmentProviders | any[] )[]; imports: (InjectorType<any> | InjectorTypeWithProviders<any>)[]; } /** * A `Type` which has a `ɵprov: ɵɵInjectableDeclaration` static field. * * `InjectableType`s contain their own Dependency Injection metadata and are usable in an * `InjectorDef`-based `StaticInjector`. * * @publicApi */ export interface InjectableType<T> extends Type<T> { /** * Opaque type whose structure is highly version dependent. Do not rely on any properties. */ ɵprov: unknown; } /** * A type which has an `InjectorDef` static field. * * `InjectorTypes` can be used to configure a `StaticInjector`. * * This is an opaque type whose structure is highly version dependent. Do not rely on any * properties. * * @publicApi */ export interface InjectorType<T> extends Type<T> { ɵfac?: unknown; ɵinj: unknown; } /** * Describes the `InjectorDef` equivalent of a `ModuleWithProviders`, an `InjectorType` with an * associated array of providers. * * Objects of this type can be listed in the imports section of an `InjectorDef`. * * NOTE: This is a private type and should not be exported */ export interface InjectorTypeWithProviders<T> { ngModule: InjectorType<T>; providers?: ( | Type<any> | ValueProvider | ExistingProvider | FactoryProvider | ConstructorProvider | StaticClassProvider | ClassProvider | EnvironmentProviders | any[] )[]; } /** * Construct an injectable definition which defines how a token will be constructed by the DI * system, and in which injectors (if any) it will be available. * * This should be assigned to a static `ɵprov` field on a type, which will then be an * `InjectableType`. * * Options: * * `providedIn` determines which injectors will include the injectable, by either associating it * with an `@NgModule` or other `InjectorType`, or by specifying that this injectable should be * provided in the `'root'` injector, which will be the application-level injector in most apps. * * `factory` gives the zero argument function which will create an instance of the injectable. * The factory can call [`inject`](api/core/inject) to access the `Injector` and request injection * of dependencies. * * @codeGenApi * @publicApi This instruction has been emitted by ViewEngine for some time and is deployed to npm. */ export function ɵɵdefineInjectable<T>(opts: { token: unknown; providedIn?: Type<any> | 'root' | 'platform' | 'any' | 'environment' | null; factory: () => T; }): unknown { return { token: opts.token, providedIn: (opts.providedIn as any) || null, factory: opts.factory, value: undefined, } as ɵɵInjectableDeclaration<T>; } /** * @deprecated in v8, delete after v10. This API should be used only by generated code, and that * code should now use ɵɵdefineInjectable instead. * @publicApi */ export const defineInjectable = ɵɵdefineInjectable; /** * Construct an `InjectorDef` which configures an injector. * * This should be assigned to a static injector def (`ɵinj`) field on a type, which will then be an * `InjectorType`. * * Options: * * * `providers`: an optional array of providers to add to the injector. Each provider must * either have a factory or point to a type which has a `ɵprov` static property (the * type must be an `InjectableType`). * * `imports`: an optional array of imports of other `InjectorType`s or `InjectorTypeWithModule`s * whose providers will also be added to the injector. Locally provided types will override * providers from imports. * * @codeGenApi */ export function ɵɵdefineInjector(options: {providers?: any[]; imports?: any[]}): unknown { return {providers: options.providers || [], imports: options.imports || []}; } /** * Read the injectable def (`ɵprov`) for `type` in a way which is immune to accidentally reading * inherited value. * * @param type A type which may have its own (non-inherited) `ɵprov`. */ export function getInjectableDef<T>(type: any): ɵɵInjectableDeclaration<T> | null { return getOwnDefinition(type, NG_PROV_DEF) || getOwnDefinition(type, NG_INJECTABLE_DEF); } export function isInjectable(type: any): boolean { return getInjectableDef(type) !== null; } /** * Return definition only if it is defined directly on `type` and is not inherited from a base * class of `type`. */ function getOwnDefinition<T>(type: any, field: string): ɵɵInjectableDeclaration<T> | null { return type.hasOwnProperty(field) ? type[field] : null; } /** * Read the injectable def (`ɵprov`) for `type` or read the `ɵprov` from one of its ancestors. * * @param type A type which may have `ɵprov`, via inheritance. * * @deprecated Will be removed in a future version of Angular, where an error will occur in the * scenario if we find the `ɵprov` on an ancestor only. */ export function getInheritedInjec
{ "end_byte": 7740, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/defs.ts" }
angular/packages/core/src/di/interface/defs.ts_7741_9116
ableDef<T>(type: any): ɵɵInjectableDeclaration<T> | null { const def = type && (type[NG_PROV_DEF] || type[NG_INJECTABLE_DEF]); if (def) { ngDevMode && console.warn( `DEPRECATED: DI is instantiating a token "${type.name}" that inherits its @Injectable decorator but does not provide one itself.\n` + `This will become an error in a future version of Angular. Please add @Injectable() to the "${type.name}" class.`, ); return def; } else { return null; } } /** * Read the injector def type in a way which is immune to accidentally reading inherited value. * * @param type type which may have an injector def (`ɵinj`) */ export function getInjectorDef<T>(type: any): ɵɵInjectorDef<T> | null { return type && (type.hasOwnProperty(NG_INJ_DEF) || type.hasOwnProperty(NG_INJECTOR_DEF)) ? (type as any)[NG_INJ_DEF] : null; } export const NG_PROV_DEF = getClosureSafeProperty({ɵprov: getClosureSafeProperty}); export const NG_INJ_DEF = getClosureSafeProperty({ɵinj: getClosureSafeProperty}); // We need to keep these around so we can read off old defs if new defs are unavailable export const NG_INJECTABLE_DEF = getClosureSafeProperty({ngInjectableDef: getClosureSafeProperty}); export const NG_INJECTOR_DEF = getClosureSafeProperty({ngInjectorDef: getClosureSafeProperty});
{ "end_byte": 9116, "start_byte": 7741, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/interface/defs.ts" }
angular/packages/core/src/di/jit/environment.ts_0_870
/** * @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 {resolveForwardRef} from '../forward_ref'; import {ɵɵinject, ɵɵinvalidFactoryDep} from '../injector_compatibility'; import {ɵɵdefineInjectable, ɵɵdefineInjector} from '../interface/defs'; /** * A mapping of the @angular/core API surface used in generated expressions to the actual symbols. * * This should be kept up to date with the public exports of @angular/core. */ export const angularCoreDiEnv: {[name: string]: Function} = { 'ɵɵdefineInjectable': ɵɵdefineInjectable, 'ɵɵdefineInjector': ɵɵdefineInjector, 'ɵɵinject': ɵɵinject, 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep, 'resolveForwardRef': resolveForwardRef, };
{ "end_byte": 870, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/jit/environment.ts" }
angular/packages/core/src/di/jit/util.ts_0_2606
/** * @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 {R3DependencyMetadataFacade} from '../../compiler/compiler_facade'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; import {Type} from '../../interface/type'; import {ReflectionCapabilities} from '../../reflection/reflection_capabilities'; import {Host, Inject, Optional, Self, SkipSelf} from '../metadata'; import {Attribute} from '../metadata_attr'; let _reflect: ReflectionCapabilities | null = null; export function getReflect(): ReflectionCapabilities { return (_reflect = _reflect || new ReflectionCapabilities()); } export function reflectDependencies(type: Type<any>): R3DependencyMetadataFacade[] { return convertDependencies(getReflect().parameters(type)); } export function convertDependencies(deps: any[]): R3DependencyMetadataFacade[] { return deps.map((dep) => reflectDependency(dep)); } function reflectDependency(dep: any | any[]): R3DependencyMetadataFacade { const meta: R3DependencyMetadataFacade = { token: null, attribute: null, host: false, optional: false, self: false, skipSelf: false, }; if (Array.isArray(dep) && dep.length > 0) { for (let j = 0; j < dep.length; j++) { const param = dep[j]; if (param === undefined) { // param may be undefined if type of dep is not set by ngtsc continue; } const proto = Object.getPrototypeOf(param); if (param instanceof Optional || proto.ngMetadataName === 'Optional') { meta.optional = true; } else if (param instanceof SkipSelf || proto.ngMetadataName === 'SkipSelf') { meta.skipSelf = true; } else if (param instanceof Self || proto.ngMetadataName === 'Self') { meta.self = true; } else if (param instanceof Host || proto.ngMetadataName === 'Host') { meta.host = true; } else if (param instanceof Inject) { meta.token = param.token; } else if (param instanceof Attribute) { if (param.attributeName === undefined) { throw new RuntimeError( RuntimeErrorCode.INVALID_INJECTION_TOKEN, ngDevMode && `Attribute name must be defined.`, ); } meta.attribute = param.attributeName; } else { meta.token = param; } } } else if (dep === undefined || (Array.isArray(dep) && dep.length === 0)) { meta.token = null; } else { meta.token = dep; } return meta; }
{ "end_byte": 2606, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/jit/util.ts" }
angular/packages/core/src/di/jit/injectable.ts_0_4522
/** * @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 { getCompilerFacade, JitCompilerUsage, R3InjectableMetadataFacade, } from '../../compiler/compiler_facade'; import {Type} from '../../interface/type'; import {NG_FACTORY_DEF} from '../../render3/fields'; import {getClosureSafeProperty} from '../../util/property'; import {resolveForwardRef} from '../forward_ref'; import {Injectable} from '../injectable'; import {NG_PROV_DEF} from '../interface/defs'; import { ClassSansProvider, ExistingSansProvider, FactorySansProvider, ValueProvider, ValueSansProvider, } from '../interface/provider'; import {angularCoreDiEnv} from './environment'; import {convertDependencies, reflectDependencies} from './util'; /** * Compile an Angular injectable according to its `Injectable` metadata, and patch the resulting * injectable def (`ɵprov`) onto the injectable type. */ export function compileInjectable(type: Type<any>, meta?: Injectable): void { let ngInjectableDef: any = null; let ngFactoryDef: any = null; // if NG_PROV_DEF is already defined on this class then don't overwrite it if (!type.hasOwnProperty(NG_PROV_DEF)) { Object.defineProperty(type, NG_PROV_DEF, { get: () => { if (ngInjectableDef === null) { const compiler = getCompilerFacade({ usage: JitCompilerUsage.Decorator, kind: 'injectable', type, }); ngInjectableDef = compiler.compileInjectable( angularCoreDiEnv, `ng:///${type.name}/ɵprov.js`, getInjectableMetadata(type, meta), ); } return ngInjectableDef; }, }); } // if NG_FACTORY_DEF is already defined on this class then don't overwrite it if (!type.hasOwnProperty(NG_FACTORY_DEF)) { Object.defineProperty(type, NG_FACTORY_DEF, { get: () => { if (ngFactoryDef === null) { const compiler = getCompilerFacade({ usage: JitCompilerUsage.Decorator, kind: 'injectable', type, }); ngFactoryDef = compiler.compileFactory(angularCoreDiEnv, `ng:///${type.name}/ɵfac.js`, { name: type.name, type, typeArgumentCount: 0, // In JIT mode types are not available nor used. deps: reflectDependencies(type), target: compiler.FactoryTarget.Injectable, }); } return ngFactoryDef; }, // Leave this configurable so that the factories from directives or pipes can take precedence. configurable: true, }); } } type UseClassProvider = Injectable & ClassSansProvider & {deps?: any[]}; const USE_VALUE = getClosureSafeProperty<ValueProvider>({ provide: String, useValue: getClosureSafeProperty, }); function isUseClassProvider(meta: Injectable): meta is UseClassProvider { return (meta as UseClassProvider).useClass !== undefined; } function isUseValueProvider(meta: Injectable): meta is Injectable & ValueSansProvider { return USE_VALUE in meta; } function isUseFactoryProvider(meta: Injectable): meta is Injectable & FactorySansProvider { return (meta as FactorySansProvider).useFactory !== undefined; } function isUseExistingProvider(meta: Injectable): meta is Injectable & ExistingSansProvider { return (meta as ExistingSansProvider).useExisting !== undefined; } function getInjectableMetadata(type: Type<any>, srcMeta?: Injectable): R3InjectableMetadataFacade { // Allow the compilation of a class with a `@Injectable()` decorator without parameters const meta: Injectable = srcMeta || {providedIn: null}; const compilerMeta: R3InjectableMetadataFacade = { name: type.name, type: type, typeArgumentCount: 0, providedIn: meta.providedIn, }; if ((isUseClassProvider(meta) || isUseFactoryProvider(meta)) && meta.deps !== undefined) { compilerMeta.deps = convertDependencies(meta.deps); } // Check to see if the user explicitly provided a `useXxxx` property. if (isUseClassProvider(meta)) { compilerMeta.useClass = meta.useClass; } else if (isUseValueProvider(meta)) { compilerMeta.useValue = meta.useValue; } else if (isUseFactoryProvider(meta)) { compilerMeta.useFactory = meta.useFactory; } else if (isUseExistingProvider(meta)) { compilerMeta.useExisting = meta.useExisting; } return compilerMeta; }
{ "end_byte": 4522, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/di/jit/injectable.ts" }
angular/packages/core/src/change_detection/change_detector_ref.ts_0_6639
/** * @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 {InjectFlags} from '../di'; import {InternalInjectFlags} from '../di/interface/injector'; import {TNode, TNodeType} from '../render3/interfaces/node'; import {isComponentHost} from '../render3/interfaces/type_checks'; import {DECLARATION_COMPONENT_VIEW, LView} from '../render3/interfaces/view'; import {getCurrentTNode, getLView} from '../render3/state'; import {getComponentLViewByIndex} from '../render3/util/view_utils'; import {ViewRef} from '../render3/view_ref'; /** * Base class that provides change detection functionality. * A change-detection tree collects all views that are to be checked for changes. * Use the methods to add and remove views from the tree, initiate change-detection, * and explicitly mark views as _dirty_, meaning that they have changed and need to be re-rendered. * * @see [Using change detection hooks](guide/components/lifecycle#using-change-detection-hooks) * @see [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection) * * @usageNotes * * The following examples demonstrate how to modify default change-detection behavior * to perform explicit detection when needed. * * ### Use `markForCheck()` with `CheckOnce` strategy * * The following example sets the `OnPush` change-detection strategy for a component * (`CheckOnce`, rather than the default `CheckAlways`), then forces a second check * after an interval. * * <code-example path="core/ts/change_detect/change-detection.ts" * region="mark-for-check"></code-example> * * ### Detach change detector to limit how often check occurs * * The following example defines a component with a large list of read-only data * that is expected to change constantly, many times per second. * To improve performance, we want to check and update the list * less often than the changes actually occur. To do that, we detach * the component's change detector and perform an explicit local check every five seconds. * * <code-example path="core/ts/change_detect/change-detection.ts" region="detach"></code-example> * * * ### Reattaching a detached component * * The following example creates a component displaying live data. * The component detaches its change detector from the main change detector tree * when the `live` property is set to false, and reattaches it when the property * becomes true. * * <code-example path="core/ts/change_detect/change-detection.ts" region="reattach"></code-example> * * @publicApi */ export abstract class ChangeDetectorRef { /** * When a view uses the {@link ChangeDetectionStrategy#OnPush} (checkOnce) * change detection strategy, explicitly marks the view as changed so that * it can be checked again. * * Components are normally marked as dirty (in need of rerendering) when inputs * have changed or events have fired in the view. Call this method to ensure that * a component is checked even if these triggers have not occurred. * * <!-- TODO: Add a link to a chapter on OnPush components --> * */ abstract markForCheck(): void; /** * Detaches this view from the change-detection tree. * A detached view is not checked until it is reattached. * Use in combination with `detectChanges()` to implement local change detection checks. * * Detached views are not checked during change detection runs until they are * re-attached, even if they are marked as dirty. * * <!-- TODO: Add a link to a chapter on detach/reattach/local digest --> * <!-- TODO: Add a live demo once ref.detectChanges is merged into master --> * */ abstract detach(): void; /** * Checks this view and its children. Use in combination with {@link ChangeDetectorRef#detach} * to implement local change detection checks. * * <!-- TODO: Add a link to a chapter on detach/reattach/local digest --> * <!-- TODO: Add a live demo once ref.detectChanges is merged into master --> * */ abstract detectChanges(): void; /** * Checks the change detector and its children, and throws if any changes are detected. * * Use in development mode to verify that running change detection doesn't introduce * other changes. Calling it in production mode is a noop. * * @deprecated This is a test-only API that does not have a place in production interface. * `checkNoChanges` is already part of an `ApplicationRef` tick when the app is running in dev * mode. For more granular `checkNoChanges` validation, use `ComponentFixture`. */ abstract checkNoChanges(): void; /** * Re-attaches the previously detached view to the change detection tree. * Views are attached to the tree by default. * * <!-- TODO: Add a link to a chapter on detach/reattach/local digest --> * */ abstract reattach(): void; /** * @internal * @nocollapse */ static __NG_ELEMENT_ID__: (flags: InjectFlags) => ChangeDetectorRef = injectChangeDetectorRef; } /** Returns a ChangeDetectorRef (a.k.a. a ViewRef) */ export function injectChangeDetectorRef(flags: InjectFlags): ChangeDetectorRef { return createViewRef( getCurrentTNode()!, getLView(), (flags & InternalInjectFlags.ForPipe) === InternalInjectFlags.ForPipe, ); } /** * Creates a ViewRef and stores it on the injector as ChangeDetectorRef (public alias). * * @param tNode The node that is requesting a ChangeDetectorRef * @param lView The view to which the node belongs * @param isPipe Whether the view is being injected into a pipe. * @returns The ChangeDetectorRef to use */ function createViewRef(tNode: TNode, lView: LView, isPipe: boolean): ChangeDetectorRef { if (isComponentHost(tNode) && !isPipe) { // The LView represents the location where the component is declared. // Instead we want the LView for the component View and so we need to look it up. const componentView = getComponentLViewByIndex(tNode.index, lView); // look down return new ViewRef(componentView, componentView); } else if ( tNode.type & (TNodeType.AnyRNode | TNodeType.AnyContainer | TNodeType.Icu | TNodeType.LetDeclaration) ) { // The LView represents the location where the injection is requested from. // We need to locate the containing LView (in case where the `lView` is an embedded view) const hostComponentView = lView[DECLARATION_COMPONENT_VIEW]; // look up return new ViewRef(hostComponentView, lView); } return null!; }
{ "end_byte": 6639, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/change_detector_ref.ts" }
angular/packages/core/src/change_detection/constants.ts_0_1039
/** * @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 */ /** * The strategy that the default change detector uses to detect changes. * When set, takes effect the next time change detection is triggered. * * @see [Change detection usage](/api/core/ChangeDetectorRef?tab=usage-notes) * @see [Skipping component subtrees](/best-practices/skipping-subtrees) * * @publicApi */ export enum ChangeDetectionStrategy { /** * Use the `CheckOnce` strategy, meaning that automatic change detection is deactivated * until reactivated by setting the strategy to `Default` (`CheckAlways`). * Change detection can still be explicitly invoked. * This strategy applies to all child directives and cannot be overridden. */ OnPush = 0, /** * Use the default `CheckAlways` strategy, in which change detection is automatic until * explicitly deactivated. */ Default = 1, }
{ "end_byte": 1039, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/constants.ts" }
angular/packages/core/src/change_detection/pipe_transform.ts_0_1209
/** * @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 */ /** * An interface that is implemented by pipes in order to perform a transformation. * Angular invokes the `transform` method with the value of a binding * as the first argument, and any parameters as the second argument in list form. * * @usageNotes * * In the following example, `TruncatePipe` returns the shortened value with an added ellipses. * * <code-example path="core/ts/pipes/simple_truncate.ts" header="simple_truncate.ts"></code-example> * * Invoking `{{ 'It was the best of times' | truncate }}` in a template will produce `It was...`. * * In the following example, `TruncatePipe` takes parameters that sets the truncated length and the * string to append with. * * <code-example path="core/ts/pipes/truncate.ts" header="truncate.ts"></code-example> * * Invoking `{{ 'It was the best of times' | truncate:4:'....' }}` in a template will produce `It * was the best....`. * * @publicApi */ export interface PipeTransform { transform(value: any, ...args: any[]): any; }
{ "end_byte": 1209, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/pipe_transform.ts" }
angular/packages/core/src/change_detection/change_detection.ts_0_1774
/** * @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 {DefaultIterableDifferFactory} from './differs/default_iterable_differ'; import {DefaultKeyValueDifferFactory} from './differs/default_keyvalue_differ'; import {IterableDifferFactory, IterableDiffers} from './differs/iterable_differs'; import {KeyValueDifferFactory, KeyValueDiffers} from './differs/keyvalue_differs'; export {SimpleChange, SimpleChanges} from '../interface/simple_change'; export {devModeEqual} from '../util/comparison'; export {ChangeDetectorRef} from './change_detector_ref'; export {ChangeDetectionStrategy} from './constants'; export { DefaultIterableDiffer, DefaultIterableDifferFactory, } from './differs/default_iterable_differ'; export {DefaultKeyValueDifferFactory} from './differs/default_keyvalue_differ'; export { IterableChangeRecord, IterableChanges, IterableDiffer, IterableDifferFactory, IterableDiffers, NgIterable, TrackByFunction, } from './differs/iterable_differs'; export { KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFactory, KeyValueDiffers, } from './differs/keyvalue_differs'; export {PipeTransform} from './pipe_transform'; /** * Structural diffing for `Object`s and `Map`s. */ const keyValDiff: KeyValueDifferFactory[] = [new DefaultKeyValueDifferFactory()]; /** * Structural diffing for `Iterable` types such as `Array`s. */ const iterableDiff: IterableDifferFactory[] = [new DefaultIterableDifferFactory()]; export const defaultIterableDiffers = new IterableDiffers(iterableDiff); export const defaultKeyValueDiffers = new KeyValueDiffers(keyValDiff);
{ "end_byte": 1774, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/change_detection.ts" }
angular/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts_0_8640
/** * @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 {Subscription} from 'rxjs'; import {ApplicationRef} from '../../application/application_ref'; import { ENVIRONMENT_INITIALIZER, EnvironmentProviders, inject, Injectable, InjectionToken, makeEnvironmentProviders, StaticProvider, } from '../../di'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; import {PendingTasksInternal} from '../../pending_tasks'; import {performanceMarkFeature} from '../../util/performance'; import {NgZone} from '../../zone'; import {InternalNgZoneOptions} from '../../zone/ng_zone'; import { ChangeDetectionScheduler, ZONELESS_SCHEDULER_DISABLED, ZONELESS_ENABLED, SCHEDULE_IN_ROOT_ZONE, } from './zoneless_scheduling'; import {SCHEDULE_IN_ROOT_ZONE_DEFAULT} from './flags'; @Injectable({providedIn: 'root'}) export class NgZoneChangeDetectionScheduler { private readonly zone = inject(NgZone); private readonly changeDetectionScheduler = inject(ChangeDetectionScheduler); private readonly applicationRef = inject(ApplicationRef); private _onMicrotaskEmptySubscription?: Subscription; initialize(): void { if (this._onMicrotaskEmptySubscription) { return; } this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({ next: () => { // `onMicroTaskEmpty` can happen _during_ the zoneless scheduler change detection because // zone.run(() => {}) will result in `checkStable` at the end of the `zone.run` closure // and emit `onMicrotaskEmpty` synchronously if run coalsecing is false. if (this.changeDetectionScheduler.runningTick) { return; } this.zone.run(() => { this.applicationRef.tick(); }); }, }); } ngOnDestroy() { this._onMicrotaskEmptySubscription?.unsubscribe(); } } /** * Internal token used to verify that `provideZoneChangeDetection` is not used * with the bootstrapModule API. */ export const PROVIDED_NG_ZONE = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '', {factory: () => false}, ); export function internalProvideZoneChangeDetection({ ngZoneFactory, ignoreChangesOutsideZone, scheduleInRootZone, }: { ngZoneFactory?: () => NgZone; ignoreChangesOutsideZone?: boolean; scheduleInRootZone?: boolean; }): StaticProvider[] { ngZoneFactory ??= () => new NgZone({...getNgZoneOptions(), scheduleInRootZone} as InternalNgZoneOptions); return [ {provide: NgZone, useFactory: ngZoneFactory}, { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory: () => { const ngZoneChangeDetectionScheduler = inject(NgZoneChangeDetectionScheduler, { optional: true, }); if ( (typeof ngDevMode === 'undefined' || ngDevMode) && ngZoneChangeDetectionScheduler === null ) { throw new RuntimeError( RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP, `A required Injectable was not found in the dependency injection tree. ` + 'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.', ); } return () => ngZoneChangeDetectionScheduler!.initialize(); }, }, { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory: () => { const service = inject(ZoneStablePendingTask); return () => { service.initialize(); }; }, }, // Always disable scheduler whenever explicitly disabled, even if another place called // `provideZoneChangeDetection` without the 'ignore' option. ignoreChangesOutsideZone === true ? {provide: ZONELESS_SCHEDULER_DISABLED, useValue: true} : [], { provide: SCHEDULE_IN_ROOT_ZONE, useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT, }, ]; } /** * Provides `NgZone`-based change detection for the application bootstrapped using * `bootstrapApplication`. * * `NgZone` is already provided in applications by default. This provider allows you to configure * options like `eventCoalescing` in the `NgZone`. * This provider is not available for `platformBrowser().bootstrapModule`, which uses * `BootstrapOptions` instead. * * @usageNotes * ```typescript * bootstrapApplication(MyApp, {providers: [ * provideZoneChangeDetection({eventCoalescing: true}), * ]}); * ``` * * @publicApi * @see {@link bootstrapApplication} * @see {@link NgZoneOptions} */ export function provideZoneChangeDetection(options?: NgZoneOptions): EnvironmentProviders { const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone; const scheduleInRootZone = (options as any)?.scheduleInRootZone; const zoneProviders = internalProvideZoneChangeDetection({ ngZoneFactory: () => { const ngZoneOptions = getNgZoneOptions(options); ngZoneOptions.scheduleInRootZone = scheduleInRootZone; if (ngZoneOptions.shouldCoalesceEventChangeDetection) { performanceMarkFeature('NgZone_CoalesceEvent'); } return new NgZone(ngZoneOptions); }, ignoreChangesOutsideZone, scheduleInRootZone, }); return makeEnvironmentProviders([ {provide: PROVIDED_NG_ZONE, useValue: true}, {provide: ZONELESS_ENABLED, useValue: false}, zoneProviders, ]); } /** * Used to configure event and run coalescing with `provideZoneChangeDetection`. * * @publicApi * * @see {@link provideZoneChangeDetection} */ export interface NgZoneOptions { /** * Optionally specify coalescing event change detections or not. * Consider the following case. * * ``` * <div (click)="doSomething()"> * <button (click)="doSomethingElse()"></button> * </div> * ``` * * When button is clicked, because of the event bubbling, both * event handlers will be called and 2 change detections will be * triggered. We can coalesce such kind of events to only trigger * change detection only once. * * By default, this option will be false. So the events will not be * coalesced and the change detection will be triggered multiple times. * And if this option be set to true, the change detection will be * triggered async by scheduling a animation frame. So in the case above, * the change detection will only be triggered once. */ eventCoalescing?: boolean; /** * Optionally specify if `NgZone#run()` method invocations should be coalesced * into a single change detection. * * Consider the following case. * ``` * for (let i = 0; i < 10; i ++) { * ngZone.run(() => { * // do something * }); * } * ``` * * This case triggers the change detection multiple times. * With ngZoneRunCoalescing options, all change detections in an event loop trigger only once. * In addition, the change detection executes in requestAnimation. * */ runCoalescing?: boolean; /** * When false, change detection is scheduled when Angular receives * a clear indication that templates need to be refreshed. This includes: * * - calling `ChangeDetectorRef.markForCheck` * - calling `ComponentRef.setInput` * - updating a signal that is read in a template * - attaching a view that is marked dirty * - removing a view * - registering a render hook (templates are only refreshed if render hooks do one of the above) * * @deprecated This option was introduced out of caution as a way for developers to opt out of the * new behavior in v18 which schedule change detection for the above events when they occur * outside the Zone. After monitoring the results post-release, we have determined that this * feature is working as desired and do not believe it should ever be disabled by setting * this option to `true`. */ ignoreChangesOutsideZone?: boolean; } // Transforms a set of `BootstrapOptions` (supported by the NgModule-based bootstrap APIs) -> // `NgZoneOptions` that are recognized by the NgZone constructor. Passing no options will result in // a set of default options returned. export function getNgZoneOptions(options?: NgZoneOptions): InternalNgZoneOptions { return { enableLongStackTrace: typeof ngDevMode === 'undefined' ? false : !!ngDevMode, shouldCoalesceEventChangeDetection: options?.eventCoalescing ?? false, shouldCoalesceRunChangeDetection: options?.runCoalescing ?? false, }; }
{ "end_byte": 8640, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts" }
angular/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts_8642_10034
@Injectable({providedIn: 'root'}) export class ZoneStablePendingTask { private readonly subscription = new Subscription(); private initialized = false; private readonly zone = inject(NgZone); private readonly pendingTasks = inject(PendingTasksInternal); initialize() { if (this.initialized) { return; } this.initialized = true; let task: number | null = null; if (!this.zone.isStable && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks) { task = this.pendingTasks.add(); } this.zone.runOutsideAngular(() => { this.subscription.add( this.zone.onStable.subscribe(() => { NgZone.assertNotInAngularZone(); // Check whether there are no pending macro/micro tasks in the next tick // to allow for NgZone to update the state. queueMicrotask(() => { if ( task !== null && !this.zone.hasPendingMacrotasks && !this.zone.hasPendingMicrotasks ) { this.pendingTasks.remove(task); task = null; } }); }), ); }); this.subscription.add( this.zone.onUnstable.subscribe(() => { NgZone.assertInAngularZone(); task ??= this.pendingTasks.add(); }), ); } ngOnDestroy() { this.subscription.unsubscribe(); } }
{ "end_byte": 10034, "start_byte": 8642, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/ng_zone_scheduling.ts" }
angular/packages/core/src/change_detection/scheduling/exhaustive_check_no_changes.ts_0_6480
/** * @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 {ApplicationRef} from '../../application/application_ref'; import {ChangeDetectionSchedulerImpl} from './zoneless_scheduling_impl'; import {inject} from '../../di/injector_compatibility'; import {makeEnvironmentProviders} from '../../di/provider_collection'; import {NgZone} from '../../zone/ng_zone'; import {EnvironmentInjector} from '../../di/r3_injector'; import {ENVIRONMENT_INITIALIZER} from '../../di/initializer_token'; import {CheckNoChangesMode} from '../../render3/state'; import {ErrorHandler} from '../../error_handler'; import {checkNoChangesInternal} from '../../render3/instructions/change_detection'; import {ZONELESS_ENABLED} from './zoneless_scheduling'; /** * Used to periodically verify no expressions have changed after they were checked. * * @param options Used to configure when the check will execute. * - `interval` will periodically run exhaustive `checkNoChanges` on application views * - `useNgZoneOnStable` will use ZoneJS to determine when change detection might have run * in an application using ZoneJS to drive change detection. When the `NgZone.onStable` would * have emitted, all views attached to the `ApplicationRef` are checked for changes. * - 'exhaustive' means that all views attached to `ApplicationRef` and all the descendants of those views will be * checked for changes (excluding those subtrees which are detached via `ChangeDetectorRef.detach()`). * This is useful because the check that runs after regular change detection does not work for components using `ChangeDetectionStrategy.OnPush`. * This check is will surface any existing errors hidden by `OnPush` components. By default, this check is exhaustive * and will always check all views, regardless of their "dirty" state and `ChangeDetectionStrategy`. * * When the `useNgZoneOnStable` option is `true`, this function will provide its own `NgZone` implementation and needs * to come after any other `NgZone` provider, including `provideZoneChangeDetection()` and `provideExperimentalZonelessChangeDetection()`. * * @experimental * @publicApi */ export function provideExperimentalCheckNoChangesForDebug(options: { interval?: number; useNgZoneOnStable?: boolean; exhaustive?: boolean; }) { if (typeof ngDevMode === 'undefined' || ngDevMode) { if (options.interval === undefined && !options.useNgZoneOnStable) { throw new Error('Must provide one of `useNgZoneOnStable` or `interval`'); } const checkNoChangesMode = options?.exhaustive === false ? CheckNoChangesMode.OnlyDirtyViews : CheckNoChangesMode.Exhaustive; return makeEnvironmentProviders([ options?.useNgZoneOnStable ? {provide: NgZone, useFactory: () => new DebugNgZoneForCheckNoChanges(checkNoChangesMode)} : [], options?.interval !== undefined ? exhaustiveCheckNoChangesInterval(options.interval, checkNoChangesMode) : [], { provide: ENVIRONMENT_INITIALIZER, multi: true, useValue: () => { if ( options?.useNgZoneOnStable && !(inject(NgZone) instanceof DebugNgZoneForCheckNoChanges) ) { throw new Error( '`provideExperimentalCheckNoChangesForDebug` with `useNgZoneOnStable` must be after any other provider for `NgZone`.', ); } }, }, ]); } else { return makeEnvironmentProviders([]); } } export class DebugNgZoneForCheckNoChanges extends NgZone { private applicationRef?: ApplicationRef; private scheduler?: ChangeDetectionSchedulerImpl; private errorHandler?: ErrorHandler; private readonly injector = inject(EnvironmentInjector); constructor(private readonly checkNoChangesMode: CheckNoChangesMode) { const zonelessEnabled = inject(ZONELESS_ENABLED); // Use coalescing to ensure we aren't ever running this check synchronously super({ shouldCoalesceEventChangeDetection: true, shouldCoalesceRunChangeDetection: zonelessEnabled, }); if (zonelessEnabled) { // prevent emits to ensure code doesn't rely on these this.onMicrotaskEmpty.emit = () => {}; this.onStable.emit = () => { this.scheduler ||= this.injector.get(ChangeDetectionSchedulerImpl); if (this.scheduler.pendingRenderTaskId || this.scheduler.runningTick) { return; } this.checkApplicationViews(); }; this.onUnstable.emit = () => {}; } else { this.runOutsideAngular(() => { this.onStable.subscribe(() => { this.checkApplicationViews(); }); }); } } private checkApplicationViews() { this.applicationRef ||= this.injector.get(ApplicationRef); for (const view of this.applicationRef.allViews) { try { checkNoChangesInternal(view._lView, this.checkNoChangesMode, view.notifyErrorHandler); } catch (e) { this.errorHandler ||= this.injector.get(ErrorHandler); this.errorHandler.handleError(e); } } } } function exhaustiveCheckNoChangesInterval( interval: number, checkNoChangesMode: CheckNoChangesMode, ) { return { provide: ENVIRONMENT_INITIALIZER, multi: true, useFactory: () => { const applicationRef = inject(ApplicationRef); const errorHandler = inject(ErrorHandler); const scheduler = inject(ChangeDetectionSchedulerImpl); const ngZone = inject(NgZone); return () => { function scheduleCheckNoChanges() { ngZone.runOutsideAngular(() => { setTimeout(() => { if (applicationRef.destroyed) { return; } if (scheduler.pendingRenderTaskId || scheduler.runningTick) { scheduleCheckNoChanges(); return; } for (const view of applicationRef.allViews) { try { checkNoChangesInternal(view._lView, checkNoChangesMode, view.notifyErrorHandler); } catch (e) { errorHandler.handleError(e); } } scheduleCheckNoChanges(); }, interval); }); } scheduleCheckNoChanges(); }; }, }; }
{ "end_byte": 6480, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/exhaustive_check_no_changes.ts" }
angular/packages/core/src/change_detection/scheduling/zoneless_scheduling.ts_0_3637
/** * @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 {InjectionToken} from '../../di/injection_token'; export const enum NotificationSource { // Change detection needs to run in order to synchronize application state // with the DOM when the following notifications are received: // This operation indicates that a subtree needs to be traversed during change detection. MarkAncestorsForTraversal, // A component/directive gets a new input. SetInput, // Defer block state updates need change detection to fully render the state. DeferBlockStateUpdate, // Debugging tools updated state and have requested change detection. DebugApplyChanges, // ChangeDetectorRef.markForCheck indicates the component is dirty/needs to refresh. MarkForCheck, // Bound listener callbacks execute and can update state without causing other notifications from // above. Listener, // Custom elements do sometimes require checking directly. CustomElement, // The following notifications do not require views to be refreshed // but we should execute render hooks: // Render hooks are guaranteed to execute with the schedulers timing. RenderHook, DeferredRenderHook, // Views might be created outside and manipulated in ways that // we cannot be aware of. When a view is attached, Angular now "knows" // about it and we now know that DOM might have changed (and we should // run render hooks). If the attached view is dirty, the `MarkAncestorsForTraversal` // notification should also be received. ViewAttached, // When DOM removal happens, render hooks may be interested in the new // DOM state but we do not need to refresh any views unless. If change // detection is required after DOM removal, another notification should // be received (i.e. `markForCheck`). ViewDetachedFromDOM, // Applying animations might result in new DOM state and should rerun render hooks AsyncAnimationsLoaded, // The scheduler is notified when a pending task is removed via the public API. // This allows us to make stability async, delayed until the next application tick. PendingTaskRemoved, // An `effect()` outside of the view tree became dirty and might need to run. RootEffect, // An `effect()` within the view tree became dirty. ViewEffect, } /** * Injectable that is notified when an `LView` is made aware of changes to application state. */ export abstract class ChangeDetectionScheduler { abstract notify(source: NotificationSource): void; abstract runningTick: boolean; } /** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */ export const ZONELESS_ENABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '', {providedIn: 'root', factory: () => false}, ); /** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */ export const PROVIDED_ZONELESS = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '', {providedIn: 'root', factory: () => false}, ); export const ZONELESS_SCHEDULER_DISABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '', ); // TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular. export const SCHEDULE_IN_ROOT_ZONE = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '', );
{ "end_byte": 3637, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/zoneless_scheduling.ts" }
angular/packages/core/src/change_detection/scheduling/flags.ts_0_256
/** * @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 */ export const SCHEDULE_IN_ROOT_ZONE_DEFAULT = false;
{ "end_byte": 256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/flags.ts" }
angular/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts_0_2030
/** * @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 {Subscription} from 'rxjs'; import {ApplicationRef, ApplicationRefDirtyFlags} from '../../application/application_ref'; import {Injectable} from '../../di/injectable'; import {inject} from '../../di/injector_compatibility'; import {EnvironmentProviders} from '../../di/interface/provider'; import {makeEnvironmentProviders} from '../../di/provider_collection'; import {RuntimeError, RuntimeErrorCode, formatRuntimeError} from '../../errors'; import {PendingTasksInternal} from '../../pending_tasks'; import { scheduleCallbackWithMicrotask, scheduleCallbackWithRafRace, } from '../../util/callback_scheduler'; import {performanceMarkFeature} from '../../util/performance'; import {NgZone, NgZonePrivate, NoopNgZone, angularZoneInstanceIdProperty} from '../../zone/ng_zone'; import { ChangeDetectionScheduler, NotificationSource, ZONELESS_ENABLED, PROVIDED_ZONELESS, ZONELESS_SCHEDULER_DISABLED, SCHEDULE_IN_ROOT_ZONE, } from './zoneless_scheduling'; const CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT = 100; let consecutiveMicrotaskNotifications = 0; let stackFromLastFewNotifications: string[] = []; function trackMicrotaskNotificationForDebugging() { consecutiveMicrotaskNotifications++; if (CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT - consecutiveMicrotaskNotifications < 5) { const stack = new Error().stack; if (stack) { stackFromLastFewNotifications.push(stack); } } if (consecutiveMicrotaskNotifications === CONSECUTIVE_MICROTASK_NOTIFICATION_LIMIT) { throw new RuntimeError( RuntimeErrorCode.INFINITE_CHANGE_DETECTION, 'Angular could not stabilize because there were endless change notifications within the browser event loop. ' + 'The stack from the last several notifications: \n' + stackFromLastFewNotifications.join('\n'), ); } }
{ "end_byte": 2030, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts" }
angular/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts_2032_10570
@Injectable({providedIn: 'root'}) export class ChangeDetectionSchedulerImpl implements ChangeDetectionScheduler { private readonly appRef = inject(ApplicationRef); private readonly taskService = inject(PendingTasksInternal); private readonly ngZone = inject(NgZone); private readonly zonelessEnabled = inject(ZONELESS_ENABLED); private readonly disableScheduling = inject(ZONELESS_SCHEDULER_DISABLED, {optional: true}) ?? false; private readonly zoneIsDefined = typeof Zone !== 'undefined' && !!Zone.root.run; private readonly schedulerTickApplyArgs = [{data: {'__scheduler_tick__': true}}]; private readonly subscriptions = new Subscription(); private readonly angularZoneId = this.zoneIsDefined ? (this.ngZone as NgZonePrivate)._inner?.get(angularZoneInstanceIdProperty) : null; private readonly scheduleInRootZone = !this.zonelessEnabled && this.zoneIsDefined && (inject(SCHEDULE_IN_ROOT_ZONE, {optional: true}) ?? false); private cancelScheduledCallback: null | (() => void) = null; private useMicrotaskScheduler = false; runningTick = false; pendingRenderTaskId: number | null = null; constructor() { this.subscriptions.add( this.appRef.afterTick.subscribe(() => { // If the scheduler isn't running a tick but the application ticked, that means // someone called ApplicationRef.tick manually. In this case, we should cancel // any change detections that had been scheduled so we don't run an extra one. if (!this.runningTick) { this.cleanup(); } }), ); this.subscriptions.add( this.ngZone.onUnstable.subscribe(() => { // If the zone becomes unstable when we're not running tick (this happens from the zone.run), // we should cancel any scheduled change detection here because at this point we // know that the zone will stabilize at some point and run change detection itself. if (!this.runningTick) { this.cleanup(); } }), ); // TODO(atscott): These conditions will need to change when zoneless is the default // Instead, they should flip to checking if ZoneJS scheduling is provided this.disableScheduling ||= !this.zonelessEnabled && // NoopNgZone without enabling zoneless means no scheduling whatsoever (this.ngZone instanceof NoopNgZone || // The same goes for the lack of Zone without enabling zoneless scheduling !this.zoneIsDefined); } notify(source: NotificationSource): void { if (!this.zonelessEnabled && source === NotificationSource.Listener) { // When the notification comes from a listener, we skip the notification unless the // application has enabled zoneless. Ideally, listeners wouldn't notify the scheduler at all // automatically. We do not know that a developer made a change in the listener callback that // requires an `ApplicationRef.tick` (synchronize templates / run render hooks). We do this // only for an easier migration from OnPush components to zoneless. Because listeners are // usually executed inside the Angular zone and listeners automatically call `markViewDirty`, // developers never needed to manually use `ChangeDetectorRef.markForCheck` or some other API // to make listener callbacks work correctly with `OnPush` components. return; } let force = false; switch (source) { case NotificationSource.MarkAncestorsForTraversal: { this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal; break; } case NotificationSource.DebugApplyChanges: case NotificationSource.DeferBlockStateUpdate: case NotificationSource.MarkForCheck: case NotificationSource.Listener: case NotificationSource.SetInput: { this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeCheck; break; } case NotificationSource.DeferredRenderHook: { // Render hooks are "deferred" when they're triggered from other render hooks. Using the // deferred dirty flags ensures that adding new hooks doesn't automatically trigger a loop // inside tick(). this.appRef.deferredDirtyFlags |= ApplicationRefDirtyFlags.AfterRender; break; } case NotificationSource.CustomElement: { // We use `ViewTreeTraversal` to ensure we refresh the element even if this is triggered // during CD. In practice this is a no-op since the elements code also calls via a // `markForRefresh()` API which sends `NotificationSource.MarkAncestorsForTraversal` anyway. this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal; force = true; break; } case NotificationSource.RootEffect: { this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.RootEffects; // Root effects still force a CD, even if the scheduler is disabled. This ensures that // effects always run, even when triggered from outside the zone when the scheduler is // otherwise disabled. force = true; break; } case NotificationSource.ViewEffect: { // This is technically a no-op, since view effects will also send a // `MarkAncestorsForTraversal` notification. Still, we set this for logical consistency. this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal; // View effects still force a CD, even if the scheduler is disabled. This ensures that // effects always run, even when triggered from outside the zone when the scheduler is // otherwise disabled. force = true; break; } case NotificationSource.PendingTaskRemoved: { // Removing a pending task via the public API forces a scheduled tick, ensuring that // stability is async and delayed until there was at least an opportunity to run // application synchronization. This prevents some footguns when working with the // public API for pending tasks where developers attempt to update application state // immediately after removing the last task. force = true; break; } case NotificationSource.ViewDetachedFromDOM: case NotificationSource.ViewAttached: case NotificationSource.RenderHook: case NotificationSource.AsyncAnimationsLoaded: default: { // These notifications only schedule a tick but do not change whether we should refresh // views. Instead, we only need to run render hooks unless another notification from the // other set is also received before `tick` happens. this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.AfterRender; } } if (!this.shouldScheduleTick(force)) { return; } if (typeof ngDevMode === 'undefined' || ngDevMode) { if (this.useMicrotaskScheduler) { trackMicrotaskNotificationForDebugging(); } else { consecutiveMicrotaskNotifications = 0; stackFromLastFewNotifications.length = 0; } } const scheduleCallback = this.useMicrotaskScheduler ? scheduleCallbackWithMicrotask : scheduleCallbackWithRafRace; this.pendingRenderTaskId = this.taskService.add(); if (this.scheduleInRootZone) { this.cancelScheduledCallback = Zone.root.run(() => scheduleCallback(() => this.tick())); } else { this.cancelScheduledCallback = this.ngZone.runOutsideAngular(() => scheduleCallback(() => this.tick()), ); } } private shouldScheduleTick(force: boolean): boolean { if ((this.disableScheduling && !force) || this.appRef.destroyed) { return false; } // already scheduled or running if (this.pendingRenderTaskId !== null || this.runningTick || this.appRef._runningTick) { return false; } // If we're inside the zone don't bother with scheduler. Zone will stabilize // eventually and run change detection. if ( !this.zonelessEnabled && this.zoneIsDefined && Zone.current.get(angularZoneInstanceIdProperty + this.angularZoneId) ) { return false; } return true; } /** * Calls ApplicationRef._tick inside the `NgZone`. * * Calling `tick` directly runs change detection and cancels any change detection that had been * scheduled previously. * * @param shouldRefreshViews Passed directly to `ApplicationRef._tick` and skips straight to * render hooks when `false`. */
{ "end_byte": 10570, "start_byte": 2032, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts" }
angular/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts_10573_16965
private tick(): void { // When ngZone.run below exits, onMicrotaskEmpty may emit if the zone is // stable. We want to prevent double ticking so we track whether the tick is // already running and skip it if so. if (this.runningTick || this.appRef.destroyed) { return; } // If we reach the tick and there is no work to be done in ApplicationRef.tick, // skip it altogether and clean up. There may be no work if, for example, the only // event that notified the scheduler was the removal of a pending task. if (this.appRef.dirtyFlags === ApplicationRefDirtyFlags.None) { this.cleanup(); return; } // The scheduler used to pass "whether to check views" as a boolean flag instead of setting // fine-grained dirtiness flags, and global checking was always used on the first pass. This // created an interesting edge case: if a notification made a view dirty and then ticked via the // scheduler (and not the zone) a global check was still performed. // // Ideally, this would not be the case, and only zone-based ticks would do global passes. // However this is a breaking change and requires fixes in g3. Until this cleanup can be done, // we add the `ViewTreeGlobal` flag to request a global check if any views are dirty in a // scheduled tick (unless zoneless is enabled, in which case global checks aren't really a // thing). // // TODO(alxhub): clean up and remove this workaround as a breaking change. if (!this.zonelessEnabled && this.appRef.dirtyFlags & ApplicationRefDirtyFlags.ViewTreeAny) { this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeGlobal; } const task = this.taskService.add(); try { this.ngZone.run( () => { this.runningTick = true; this.appRef._tick(); }, undefined, this.schedulerTickApplyArgs, ); } catch (e: unknown) { this.taskService.remove(task); throw e; } finally { this.cleanup(); } // If we're notified of a change within 1 microtask of running change // detection, run another round in the same event loop. This allows code // which uses Promise.resolve (see NgModel) to avoid // ExpressionChanged...Error to still be reflected in a single browser // paint, even if that spans multiple rounds of change detection. this.useMicrotaskScheduler = true; scheduleCallbackWithMicrotask(() => { this.useMicrotaskScheduler = false; this.taskService.remove(task); }); } ngOnDestroy() { this.subscriptions.unsubscribe(); this.cleanup(); } private cleanup() { this.runningTick = false; this.cancelScheduledCallback?.(); this.cancelScheduledCallback = null; // If this is the last task, the service will synchronously emit a stable // notification. If there is a subscriber that then acts in a way that // tries to notify the scheduler again, we need to be able to respond to // schedule a new change detection. Therefore, we should clear the task ID // before removing it from the pending tasks (or the tasks service should // not synchronously emit stable, similar to how Zone stableness only // happens if it's still stable after a microtask). if (this.pendingRenderTaskId !== null) { const taskId = this.pendingRenderTaskId; this.pendingRenderTaskId = null; this.taskService.remove(taskId); } } } /** * Provides change detection without ZoneJS for the application bootstrapped using * `bootstrapApplication`. * * This function allows you to configure the application to not use the state/state changes of * ZoneJS to schedule change detection in the application. This will work when ZoneJS is not present * on the page at all or if it exists because something else is using it (either another Angular * application which uses ZoneJS for scheduling or some other library that relies on ZoneJS). * * This can also be added to the `TestBed` providers to configure the test environment to more * closely match production behavior. This will help give higher confidence that components are * compatible with zoneless change detection. * * ZoneJS uses browser events to trigger change detection. When using this provider, Angular will * instead use Angular APIs to schedule change detection. These APIs include: * * - `ChangeDetectorRef.markForCheck` * - `ComponentRef.setInput` * - updating a signal that is read in a template * - when bound host or template listeners are triggered * - attaching a view that was marked dirty by one of the above * - removing a view * - registering a render hook (templates are only refreshed if render hooks do one of the above) * * @usageNotes * ```typescript * bootstrapApplication(MyApp, {providers: [ * provideExperimentalZonelessChangeDetection(), * ]}); * ``` * * This API is experimental. Neither the shape, nor the underlying behavior is stable and can change * in patch versions. There are known feature gaps and API ergonomic considerations. We will iterate * on the exact API based on the feedback and our understanding of the problem and solution space. * * @publicApi * @experimental * @see [bootstrapApplication](/api/platform-browser/bootstrapApplication) */ export function provideExperimentalZonelessChangeDetection(): EnvironmentProviders { performanceMarkFeature('NgZoneless'); if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) { const message = formatRuntimeError( RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE, `The application is using zoneless change detection, but is still loading Zone.js. ` + `Consider removing Zone.js to get the full benefits of zoneless. ` + `In applications using the Angular CLI, Zone.js is typically included in the "polyfills" section of the angular.json file.`, ); console.warn(message); } return makeEnvironmentProviders([ {provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl}, {provide: NgZone, useClass: NoopNgZone}, {provide: ZONELESS_ENABLED, useValue: true}, {provide: SCHEDULE_IN_ROOT_ZONE, useValue: false}, typeof ngDevMode === 'undefined' || ngDevMode ? [{provide: PROVIDED_ZONELESS, useValue: true}] : [], ]); }
{ "end_byte": 16965, "start_byte": 10573, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/scheduling/zoneless_scheduling_impl.ts" }
angular/packages/core/src/change_detection/differs/keyvalue_differs.ts_0_5564
/** * @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 {Optional, SkipSelf, StaticProvider, ɵɵdefineInjectable} from '../../di'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; import {DefaultKeyValueDifferFactory} from './default_keyvalue_differ'; /** * A differ that tracks changes made to an object over time. * * @publicApi */ export interface KeyValueDiffer<K, V> { /** * Compute a difference between the previous state and the new `object` state. * * @param object containing the new value. * @returns an object describing the difference. The return value is only valid until the next * `diff()` invocation. */ diff(object: Map<K, V>): KeyValueChanges<K, V> | null; /** * Compute a difference between the previous state and the new `object` state. * * @param object containing the new value. * @returns an object describing the difference. The return value is only valid until the next * `diff()` invocation. */ diff(object: {[key: string]: V}): KeyValueChanges<string, V> | null; // TODO(TS2.1): diff<KP extends string>(this: KeyValueDiffer<KP, V>, object: Record<KP, V>): // KeyValueDiffer<KP, V>; } /** * An object describing the changes in the `Map` or `{[k:string]: string}` since last time * `KeyValueDiffer#diff()` was invoked. * * @publicApi */ export interface KeyValueChanges<K, V> { /** * Iterate over all changes. `KeyValueChangeRecord` will contain information about changes * to each item. */ forEachItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void; /** * Iterate over changes in the order of original Map showing where the original items * have moved. */ forEachPreviousItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void; /** * Iterate over all keys for which values have changed. */ forEachChangedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void; /** * Iterate over all added items. */ forEachAddedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void; /** * Iterate over all removed items. */ forEachRemovedItem(fn: (r: KeyValueChangeRecord<K, V>) => void): void; } /** * Record representing the item change information. * * @publicApi */ export interface KeyValueChangeRecord<K, V> { /** * Current key in the Map. */ readonly key: K; /** * Current value for the key or `null` if removed. */ readonly currentValue: V | null; /** * Previous value for the key or `null` if added. */ readonly previousValue: V | null; } /** * Provides a factory for {@link KeyValueDiffer}. * * @publicApi */ export interface KeyValueDifferFactory { /** * Test to see if the differ knows how to diff this kind of object. */ supports(objects: any): boolean; /** * Create a `KeyValueDiffer`. */ create<K, V>(): KeyValueDiffer<K, V>; } export function defaultKeyValueDiffersFactory() { return new KeyValueDiffers([new DefaultKeyValueDifferFactory()]); } /** * A repository of different Map diffing strategies used by NgClass, NgStyle, and others. * * @publicApi */ export class KeyValueDiffers { /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: KeyValueDiffers, providedIn: 'root', factory: defaultKeyValueDiffersFactory, }); private readonly factories: KeyValueDifferFactory[]; constructor(factories: KeyValueDifferFactory[]) { this.factories = factories; } static create<S>(factories: KeyValueDifferFactory[], parent?: KeyValueDiffers): KeyValueDiffers { if (parent) { const copied = parent.factories.slice(); factories = factories.concat(copied); } return new KeyValueDiffers(factories); } /** * Takes an array of {@link KeyValueDifferFactory} and returns a provider used to extend the * inherited {@link KeyValueDiffers} instance with the provided factories and return a new * {@link KeyValueDiffers} instance. * * @usageNotes * ### Example * * The following example shows how to extend an existing list of factories, * which will only be applied to the injector for this component and its children. * This step is all that's required to make a new {@link KeyValueDiffer} available. * * ``` * @Component({ * viewProviders: [ * KeyValueDiffers.extend([new ImmutableMapDiffer()]) * ] * }) * ``` */ static extend<S>(factories: KeyValueDifferFactory[]): StaticProvider { return { provide: KeyValueDiffers, useFactory: (parent: KeyValueDiffers) => { // if parent is null, it means that we are in the root injector and we have just overridden // the default injection mechanism for KeyValueDiffers, in such a case just assume // `defaultKeyValueDiffersFactory`. return KeyValueDiffers.create(factories, parent || defaultKeyValueDiffersFactory()); }, // Dependency technically isn't optional, but we can provide a better error message this way. deps: [[KeyValueDiffers, new SkipSelf(), new Optional()]], }; } find(kv: any): KeyValueDifferFactory { const factory = this.factories.find((f) => f.supports(kv)); if (factory) { return factory; } throw new RuntimeError( RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY, ngDevMode && `Cannot find a differ supporting object '${kv}'`, ); } }
{ "end_byte": 5564, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/keyvalue_differs.ts" }
angular/packages/core/src/change_detection/differs/default_keyvalue_differ.ts_0_768
/** * @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 {RuntimeError, RuntimeErrorCode} from '../../errors'; import {isJsObject} from '../../util/iterable'; import {stringify} from '../../util/stringify'; import { KeyValueChangeRecord, KeyValueChanges, KeyValueDiffer, KeyValueDifferFactory, } from './keyvalue_differs'; export class DefaultKeyValueDifferFactory<K, V> implements KeyValueDifferFactory { constructor() {} supports(obj: any): boolean { return obj instanceof Map || isJsObject(obj); } create<K, V>(): KeyValueDiffer<K, V> { return new DefaultKeyValueDiffer<K, V>(); } }
{ "end_byte": 768, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_keyvalue_differ.ts" }
angular/packages/core/src/change_detection/differs/default_keyvalue_differ.ts_770_8228
export class DefaultKeyValueDiffer<K, V> implements KeyValueDiffer<K, V>, KeyValueChanges<K, V> { private _records = new Map<K, KeyValueChangeRecord_<K, V>>(); private _mapHead: KeyValueChangeRecord_<K, V> | null = null; // _appendAfter is used in the check loop private _appendAfter: KeyValueChangeRecord_<K, V> | null = null; private _previousMapHead: KeyValueChangeRecord_<K, V> | null = null; private _changesHead: KeyValueChangeRecord_<K, V> | null = null; private _changesTail: KeyValueChangeRecord_<K, V> | null = null; private _additionsHead: KeyValueChangeRecord_<K, V> | null = null; private _additionsTail: KeyValueChangeRecord_<K, V> | null = null; private _removalsHead: KeyValueChangeRecord_<K, V> | null = null; private _removalsTail: KeyValueChangeRecord_<K, V> | null = null; get isDirty(): boolean { return ( this._additionsHead !== null || this._changesHead !== null || this._removalsHead !== null ); } forEachItem(fn: (r: KeyValueChangeRecord<K, V>) => void) { let record: KeyValueChangeRecord_<K, V> | null; for (record = this._mapHead; record !== null; record = record._next) { fn(record); } } forEachPreviousItem(fn: (r: KeyValueChangeRecord<K, V>) => void) { let record: KeyValueChangeRecord_<K, V> | null; for (record = this._previousMapHead; record !== null; record = record._nextPrevious) { fn(record); } } forEachChangedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) { let record: KeyValueChangeRecord_<K, V> | null; for (record = this._changesHead; record !== null; record = record._nextChanged) { fn(record); } } forEachAddedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) { let record: KeyValueChangeRecord_<K, V> | null; for (record = this._additionsHead; record !== null; record = record._nextAdded) { fn(record); } } forEachRemovedItem(fn: (r: KeyValueChangeRecord<K, V>) => void) { let record: KeyValueChangeRecord_<K, V> | null; for (record = this._removalsHead; record !== null; record = record._nextRemoved) { fn(record); } } diff(map?: Map<any, any> | {[k: string]: any} | null): any { if (!map) { map = new Map(); } else if (!(map instanceof Map || isJsObject(map))) { throw new RuntimeError( RuntimeErrorCode.INVALID_DIFFER_INPUT, ngDevMode && `Error trying to diff '${stringify(map)}'. Only maps and objects are allowed`, ); } return this.check(map) ? this : null; } onDestroy() {} /** * Check the current state of the map vs the previous. * The algorithm is optimised for when the keys do no change. */ check(map: Map<any, any> | {[k: string]: any}): boolean { this._reset(); let insertBefore = this._mapHead; this._appendAfter = null; this._forEach(map, (value: any, key: any) => { if (insertBefore && insertBefore.key === key) { this._maybeAddToChanges(insertBefore, value); this._appendAfter = insertBefore; insertBefore = insertBefore._next; } else { const record = this._getOrCreateRecordForKey(key, value); insertBefore = this._insertBeforeOrAppend(insertBefore, record); } }); // Items remaining at the end of the list have been deleted if (insertBefore) { if (insertBefore._prev) { insertBefore._prev._next = null; } this._removalsHead = insertBefore; for ( let record: KeyValueChangeRecord_<K, V> | null = insertBefore; record !== null; record = record._nextRemoved ) { if (record === this._mapHead) { this._mapHead = null; } this._records.delete(record.key); record._nextRemoved = record._next; record.previousValue = record.currentValue; record.currentValue = null; record._prev = null; record._next = null; } } // Make sure tails have no next records from previous runs if (this._changesTail) this._changesTail._nextChanged = null; if (this._additionsTail) this._additionsTail._nextAdded = null; return this.isDirty; } /** * Inserts a record before `before` or append at the end of the list when `before` is null. * * Notes: * - This method appends at `this._appendAfter`, * - This method updates `this._appendAfter`, * - The return value is the new value for the insertion pointer. */ private _insertBeforeOrAppend( before: KeyValueChangeRecord_<K, V> | null, record: KeyValueChangeRecord_<K, V>, ): KeyValueChangeRecord_<K, V> | null { if (before) { const prev = before._prev; record._next = before; record._prev = prev; before._prev = record; if (prev) { prev._next = record; } if (before === this._mapHead) { this._mapHead = record; } this._appendAfter = before; return before; } if (this._appendAfter) { this._appendAfter._next = record; record._prev = this._appendAfter; } else { this._mapHead = record; } this._appendAfter = record; return null; } private _getOrCreateRecordForKey(key: K, value: V): KeyValueChangeRecord_<K, V> { if (this._records.has(key)) { const record = this._records.get(key)!; this._maybeAddToChanges(record, value); const prev = record._prev; const next = record._next; if (prev) { prev._next = next; } if (next) { next._prev = prev; } record._next = null; record._prev = null; return record; } const record = new KeyValueChangeRecord_<K, V>(key); this._records.set(key, record); record.currentValue = value; this._addToAdditions(record); return record; } /** @internal */ _reset() { if (this.isDirty) { let record: KeyValueChangeRecord_<K, V> | null; // let `_previousMapHead` contain the state of the map before the changes this._previousMapHead = this._mapHead; for (record = this._previousMapHead; record !== null; record = record._next) { record._nextPrevious = record._next; } // Update `record.previousValue` with the value of the item before the changes // We need to update all changed items (that's those which have been added and changed) for (record = this._changesHead; record !== null; record = record._nextChanged) { record.previousValue = record.currentValue; } for (record = this._additionsHead; record != null; record = record._nextAdded) { record.previousValue = record.currentValue; } this._changesHead = this._changesTail = null; this._additionsHead = this._additionsTail = null; this._removalsHead = null; } } // Add the record or a given key to the list of changes only when the value has actually changed private _maybeAddToChanges(record: KeyValueChangeRecord_<K, V>, newValue: any): void { if (!Object.is(newValue, record.currentValue)) { record.previousValue = record.currentValue; record.currentValue = newValue; this._addToChanges(record); } } private _addToAdditions(record: KeyValueChangeRecord_<K, V>) { if (this._additionsHead === null) { this._additionsHead = this._additionsTail = record; } else { this._additionsTail!._nextAdded = record; this._additionsTail = record; } }
{ "end_byte": 8228, "start_byte": 770, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_keyvalue_differ.ts" }
angular/packages/core/src/change_detection/differs/default_keyvalue_differ.ts_8232_9362
private _addToChanges(record: KeyValueChangeRecord_<K, V>) { if (this._changesHead === null) { this._changesHead = this._changesTail = record; } else { this._changesTail!._nextChanged = record; this._changesTail = record; } } /** @internal */ private _forEach<K, V>(obj: Map<K, V> | {[k: string]: V}, fn: (v: V, k: any) => void) { if (obj instanceof Map) { obj.forEach(fn); } else { Object.keys(obj).forEach((k) => fn(obj[k], k)); } } } class KeyValueChangeRecord_<K, V> implements KeyValueChangeRecord<K, V> { previousValue: V | null = null; currentValue: V | null = null; /** @internal */ _nextPrevious: KeyValueChangeRecord_<K, V> | null = null; /** @internal */ _next: KeyValueChangeRecord_<K, V> | null = null; /** @internal */ _prev: KeyValueChangeRecord_<K, V> | null = null; /** @internal */ _nextAdded: KeyValueChangeRecord_<K, V> | null = null; /** @internal */ _nextRemoved: KeyValueChangeRecord_<K, V> | null = null; /** @internal */ _nextChanged: KeyValueChangeRecord_<K, V> | null = null; constructor(public key: K) {} }
{ "end_byte": 9362, "start_byte": 8232, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_keyvalue_differ.ts" }
angular/packages/core/src/change_detection/differs/iterable_differs.ts_0_6641
/** * @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 {ɵɵdefineInjectable} from '../../di/interface/defs'; import {StaticProvider} from '../../di/interface/provider'; import {Optional, SkipSelf} from '../../di/metadata'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; import {DefaultIterableDifferFactory} from '../differs/default_iterable_differ'; /** * A type describing supported iterable types. * * @publicApi */ export type NgIterable<T> = Array<T> | Iterable<T>; /** * A strategy for tracking changes over time to an iterable. Used by {@link NgForOf} to * respond to changes in an iterable by effecting equivalent changes in the DOM. * * @publicApi */ export interface IterableDiffer<V> { /** * Compute a difference between the previous state and the new `object` state. * * @param object containing the new value. * @returns an object describing the difference. The return value is only valid until the next * `diff()` invocation. */ diff(object: NgIterable<V> | undefined | null): IterableChanges<V> | null; } /** * An object describing the changes in the `Iterable` collection since last time * `IterableDiffer#diff()` was invoked. * * @publicApi */ export interface IterableChanges<V> { /** * Iterate over all changes. `IterableChangeRecord` will contain information about changes * to each item. */ forEachItem(fn: (record: IterableChangeRecord<V>) => void): void; /** * Iterate over a set of operations which when applied to the original `Iterable` will produce the * new `Iterable`. * * NOTE: These are not necessarily the actual operations which were applied to the original * `Iterable`, rather these are a set of computed operations which may not be the same as the * ones applied. * * @param record A change which needs to be applied * @param previousIndex The `IterableChangeRecord#previousIndex` of the `record` refers to the * original `Iterable` location, where as `previousIndex` refers to the transient location * of the item, after applying the operations up to this point. * @param currentIndex The `IterableChangeRecord#currentIndex` of the `record` refers to the * original `Iterable` location, where as `currentIndex` refers to the transient location * of the item, after applying the operations up to this point. */ forEachOperation( fn: ( record: IterableChangeRecord<V>, previousIndex: number | null, currentIndex: number | null, ) => void, ): void; /** * Iterate over changes in the order of original `Iterable` showing where the original items * have moved. */ forEachPreviousItem(fn: (record: IterableChangeRecord<V>) => void): void; /** Iterate over all added items. */ forEachAddedItem(fn: (record: IterableChangeRecord<V>) => void): void; /** Iterate over all moved items. */ forEachMovedItem(fn: (record: IterableChangeRecord<V>) => void): void; /** Iterate over all removed items. */ forEachRemovedItem(fn: (record: IterableChangeRecord<V>) => void): void; /** * Iterate over all items which had their identity (as computed by the `TrackByFunction`) * changed. */ forEachIdentityChange(fn: (record: IterableChangeRecord<V>) => void): void; } /** * Record representing the item change information. * * @publicApi */ export interface IterableChangeRecord<V> { /** Current index of the item in `Iterable` or null if removed. */ readonly currentIndex: number | null; /** Previous index of the item in `Iterable` or null if added. */ readonly previousIndex: number | null; /** The item. */ readonly item: V; /** Track by identity as computed by the `TrackByFunction`. */ readonly trackById: any; } /** * A function optionally passed into the `NgForOf` directive to customize how `NgForOf` uniquely * identifies items in an iterable. * * `NgForOf` needs to uniquely identify items in the iterable to correctly perform DOM updates * when items in the iterable are reordered, new items are added, or existing items are removed. * * * In all of these scenarios it is usually desirable to only update the DOM elements associated * with the items affected by the change. This behavior is important to: * * - preserve any DOM-specific UI state (like cursor position, focus, text selection) when the * iterable is modified * - enable animation of item addition, removal, and iterable reordering * - preserve the value of the `<select>` element when nested `<option>` elements are dynamically * populated using `NgForOf` and the bound iterable is updated * * A common use for custom `trackBy` functions is when the model that `NgForOf` iterates over * contains a property with a unique identifier. For example, given a model: * * ```ts * class User { * id: number; * name: string; * ... * } * ``` * a custom `trackBy` function could look like the following: * ```ts * function userTrackBy(index, user) { * return user.id; * } * ``` * * A custom `trackBy` function must have several properties: * * - be [idempotent](https://en.wikipedia.org/wiki/Idempotence) (be without side effects, and always * return the same value for a given input) * - return unique value for all unique inputs * - be fast * * @see [`NgForOf#ngForTrackBy`](api/common/NgForOf#ngForTrackBy) * @publicApi */ export interface TrackByFunction<T> { // Note: the type parameter `U` enables more accurate template type checking in case a trackBy // function is declared using a base type of the iterated type. The `U` type gives TypeScript // additional freedom to infer a narrower type for the `item` parameter type, instead of imposing // the trackBy's declared item type as the inferred type for `T`. // See https://github.com/angular/angular/issues/40125 /** * @param index The index of the item within the iterable. * @param item The item in the iterable. */ <U extends T>(index: number, item: T & U): any; } /** * Provides a factory for {@link IterableDiffer}. * * @publicApi */ export interface IterableDifferFactory { supports(objects: any): boolean; create<V>(trackByFn?: TrackByFunction<V>): IterableDiffer<V>; } export function defaultIterableDiffersFactory() { return new IterableDiffers([new DefaultIterableDifferFactory()]); } /** * A repository of different iterable diffing strategies used by NgFor, NgClass, and others. * * @publicApi */ e
{ "end_byte": 6641, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/iterable_differs.ts" }
angular/packages/core/src/change_detection/differs/iterable_differs.ts_6642_9116
port class IterableDiffers { /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: IterableDiffers, providedIn: 'root', factory: defaultIterableDiffersFactory, }); constructor(private factories: IterableDifferFactory[]) {} static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers { if (parent != null) { const copied = parent.factories.slice(); factories = factories.concat(copied); } return new IterableDiffers(factories); } /** * Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the * inherited {@link IterableDiffers} instance with the provided factories and return a new * {@link IterableDiffers} instance. * * @usageNotes * ### Example * * The following example shows how to extend an existing list of factories, * which will only be applied to the injector for this component and its children. * This step is all that's required to make a new {@link IterableDiffer} available. * * ``` * @Component({ * viewProviders: [ * IterableDiffers.extend([new ImmutableListDiffer()]) * ] * }) * ``` */ static extend(factories: IterableDifferFactory[]): StaticProvider { return { provide: IterableDiffers, useFactory: (parent: IterableDiffers | null) => { // if parent is null, it means that we are in the root injector and we have just overridden // the default injection mechanism for IterableDiffers, in such a case just assume // `defaultIterableDiffersFactory`. return IterableDiffers.create(factories, parent || defaultIterableDiffersFactory()); }, // Dependency technically isn't optional, but we can provide a better error message this way. deps: [[IterableDiffers, new SkipSelf(), new Optional()]], }; } find(iterable: any): IterableDifferFactory { const factory = this.factories.find((f) => f.supports(iterable)); if (factory != null) { return factory; } else { throw new RuntimeError( RuntimeErrorCode.NO_SUPPORTING_DIFFER_FACTORY, ngDevMode && `Cannot find a differ supporting object '${iterable}' of type '${getTypeNameForDebugging( iterable, )}'`, ); } } } export function getTypeNameForDebugging(type: any): string { return type['name'] || typeof type; }
{ "end_byte": 9116, "start_byte": 6642, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/iterable_differs.ts" }
angular/packages/core/src/change_detection/differs/default_iterable_differ.ts_0_1054
/** * @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 {RuntimeError, RuntimeErrorCode} from '../../errors'; import {Writable} from '../../interface/type'; import {isListLikeIterable, iterateListLike} from '../../util/iterable'; import {stringify} from '../../util/stringify'; import { IterableChangeRecord, IterableChanges, IterableDiffer, IterableDifferFactory, NgIterable, TrackByFunction, } from './iterable_differs'; export class DefaultIterableDifferFactory implements IterableDifferFactory { constructor() {} supports(obj: Object | null | undefined): boolean { return isListLikeIterable(obj); } create<V>(trackByFn?: TrackByFunction<V>): DefaultIterableDiffer<V> { return new DefaultIterableDiffer<V>(trackByFn); } } const trackByIdentity = (index: number, item: any) => item; /** * @deprecated v4.0.0 - Should not be part of public API. * @publicApi */
{ "end_byte": 1054, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_iterable_differ.ts" }
angular/packages/core/src/change_detection/differs/default_iterable_differ.ts_1055_9039
export class DefaultIterableDiffer<V> implements IterableDiffer<V>, IterableChanges<V> { public readonly length: number = 0; // TODO: confirm the usage of `collection` as it's unused, readonly and on a non public API. public readonly collection!: V[] | Iterable<V> | null; // Keeps track of the used records at any point in time (during & across `_check()` calls) private _linkedRecords: _DuplicateMap<V> | null = null; // Keeps track of the removed records at any point in time during `_check()` calls. private _unlinkedRecords: _DuplicateMap<V> | null = null; private _previousItHead: IterableChangeRecord_<V> | null = null; private _itHead: IterableChangeRecord_<V> | null = null; private _itTail: IterableChangeRecord_<V> | null = null; private _additionsHead: IterableChangeRecord_<V> | null = null; private _additionsTail: IterableChangeRecord_<V> | null = null; private _movesHead: IterableChangeRecord_<V> | null = null; private _movesTail: IterableChangeRecord_<V> | null = null; private _removalsHead: IterableChangeRecord_<V> | null = null; private _removalsTail: IterableChangeRecord_<V> | null = null; // Keeps track of records where custom track by is the same, but item identity has changed private _identityChangesHead: IterableChangeRecord_<V> | null = null; private _identityChangesTail: IterableChangeRecord_<V> | null = null; private _trackByFn: TrackByFunction<V>; constructor(trackByFn?: TrackByFunction<V>) { this._trackByFn = trackByFn || trackByIdentity; } forEachItem(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._itHead; record !== null; record = record._next) { fn(record); } } forEachOperation( fn: ( item: IterableChangeRecord<V>, previousIndex: number | null, currentIndex: number | null, ) => void, ) { let nextIt = this._itHead; let nextRemove = this._removalsHead; let addRemoveOffset = 0; let moveOffsets: number[] | null = null; while (nextIt || nextRemove) { // Figure out which is the next record to process // Order: remove, add, move const record: IterableChangeRecord<V> = !nextRemove || (nextIt && nextIt.currentIndex! < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets)) ? nextIt! : nextRemove; const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets); const currentIndex = record.currentIndex; // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary if (record === nextRemove) { addRemoveOffset--; nextRemove = nextRemove._nextRemoved; } else { nextIt = nextIt!._next; if (record.previousIndex == null) { addRemoveOffset++; } else { // INVARIANT: currentIndex < previousIndex if (!moveOffsets) moveOffsets = []; const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset; const localCurrentIndex = currentIndex! - addRemoveOffset; if (localMovePreviousIndex != localCurrentIndex) { for (let i = 0; i < localMovePreviousIndex; i++) { const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0); const index = offset + i; if (localCurrentIndex <= index && index < localMovePreviousIndex) { moveOffsets[i] = offset + 1; } } const previousIndex = record.previousIndex; moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex; } } } if (adjPreviousIndex !== currentIndex) { fn(record, adjPreviousIndex, currentIndex); } } } forEachPreviousItem(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._previousItHead; record !== null; record = record._nextPrevious) { fn(record); } } forEachAddedItem(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._additionsHead; record !== null; record = record._nextAdded) { fn(record); } } forEachMovedItem(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._movesHead; record !== null; record = record._nextMoved) { fn(record); } } forEachRemovedItem(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._removalsHead; record !== null; record = record._nextRemoved) { fn(record); } } forEachIdentityChange(fn: (record: IterableChangeRecord_<V>) => void) { let record: IterableChangeRecord_<V> | null; for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) { fn(record); } } diff(collection: NgIterable<V> | null | undefined): DefaultIterableDiffer<V> | null { if (collection == null) collection = []; if (!isListLikeIterable(collection)) { throw new RuntimeError( RuntimeErrorCode.INVALID_DIFFER_INPUT, ngDevMode && `Error trying to diff '${stringify(collection)}'. Only arrays and iterables are allowed`, ); } if (this.check(collection)) { return this; } else { return null; } } onDestroy() {} check(collection: NgIterable<V>): boolean { this._reset(); let record: IterableChangeRecord_<V> | null = this._itHead; let mayBeDirty: boolean = false; let index: number; let item: V; let itemTrackBy: any; if (Array.isArray(collection)) { (this as Writable<this>).length = collection.length; for (let index = 0; index < this.length; index++) { item = collection[index]; itemTrackBy = this._trackByFn(index, item); if (record === null || !Object.is(record.trackById, itemTrackBy)) { record = this._mismatch(record, item, itemTrackBy, index); mayBeDirty = true; } else { if (mayBeDirty) { // TODO(misko): can we limit this to duplicates only? record = this._verifyReinsertion(record, item, itemTrackBy, index); } if (!Object.is(record.item, item)) this._addIdentityChange(record, item); } record = record._next; } } else { index = 0; iterateListLike(collection, (item: V) => { itemTrackBy = this._trackByFn(index, item); if (record === null || !Object.is(record.trackById, itemTrackBy)) { record = this._mismatch(record, item, itemTrackBy, index); mayBeDirty = true; } else { if (mayBeDirty) { // TODO(misko): can we limit this to duplicates only? record = this._verifyReinsertion(record, item, itemTrackBy, index); } if (!Object.is(record.item, item)) this._addIdentityChange(record, item); } record = record._next; index++; }); (this as Writable<this>).length = index; } this._truncate(record); (this as Writable<this>).collection = collection; return this.isDirty; } /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity * changes. */ get isDirty(): boolean { return ( this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null || this._identityChangesHead !== null ); } /** * Reset the state of the change objects to show no changes. This means set previousKey to * currentKey, and clear all of the queues (additions, moves, removals). * Set the previousIndexes of moved and added items to their currentIndexes * Reset the list of additions, moves and removals * * @internal */
{ "end_byte": 9039, "start_byte": 1055, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_iterable_differ.ts" }
angular/packages/core/src/change_detection/differs/default_iterable_differ.ts_9042_16343
_reset() { if (this.isDirty) { let record: IterableChangeRecord_<V> | null; for (record = this._previousItHead = this._itHead; record !== null; record = record._next) { record._nextPrevious = record._next; } for (record = this._additionsHead; record !== null; record = record._nextAdded) { record.previousIndex = record.currentIndex; } this._additionsHead = this._additionsTail = null; for (record = this._movesHead; record !== null; record = record._nextMoved) { record.previousIndex = record.currentIndex; } this._movesHead = this._movesTail = null; this._removalsHead = this._removalsTail = null; this._identityChangesHead = this._identityChangesTail = null; // TODO(vicb): when assert gets supported // assert(!this.isDirty); } } /** * This is the core function which handles differences between collections. * * - `record` is the record which we saw at this position last time. If null then it is a new * item. * - `item` is the current item in the collection * - `index` is the position of the item in the collection * * @internal */ _mismatch( record: IterableChangeRecord_<V> | null, item: V, itemTrackBy: any, index: number, ): IterableChangeRecord_<V> { // The previous record after which we will append the current one. let previousRecord: IterableChangeRecord_<V> | null; if (record === null) { previousRecord = this._itTail; } else { previousRecord = record._prev; // Remove the record from the collection since we know it does not match the item. this._remove(record); } // See if we have evicted the item, which used to be at some anterior position of _itHead list. record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); if (record !== null) { // It is an item which we have evicted earlier: reinsert it back into the list. // But first we need to check if identity changed, so we can update in view if necessary. if (!Object.is(record.item, item)) this._addIdentityChange(record, item); this._reinsertAfter(record, previousRecord, index); } else { // Attempt to see if the item is at some posterior position of _itHead list. record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index); if (record !== null) { // We have the item in _itHead at/after `index` position. We need to move it forward in the // collection. // But first we need to check if identity changed, so we can update in view if necessary. if (!Object.is(record.item, item)) this._addIdentityChange(record, item); this._moveAfter(record, previousRecord, index); } else { // It is a new item: add it. record = this._addAfter( new IterableChangeRecord_<V>(item, itemTrackBy), previousRecord, index, ); } } return record; } /** * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty) * * Use case: `[a, a]` => `[b, a, a]` * * If we did not have this check then the insertion of `b` would: * 1) evict first `a` * 2) insert `b` at `0` index. * 3) leave `a` at index `1` as is. <-- this is wrong! * 3) reinsert `a` at index 2. <-- this is wrong! * * The correct behavior is: * 1) evict first `a` * 2) insert `b` at `0` index. * 3) reinsert `a` at index 1. * 3) move `a` at from `1` to `2`. * * * Double check that we have not evicted a duplicate item. We need to check if the item type may * have already been removed: * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a' * at the end. * * @internal */ _verifyReinsertion( record: IterableChangeRecord_<V>, item: V, itemTrackBy: any, index: number, ): IterableChangeRecord_<V> { let reinsertRecord: IterableChangeRecord_<V> | null = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); if (reinsertRecord !== null) { record = this._reinsertAfter(reinsertRecord, record._prev!, index); } else if (record.currentIndex != index) { record.currentIndex = index; this._addToMoves(record, index); } return record; } /** * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection * * - `record` The first excess {@link IterableChangeRecord_}. * * @internal */ _truncate(record: IterableChangeRecord_<V> | null) { // Anything after that needs to be removed; while (record !== null) { const nextRecord: IterableChangeRecord_<V> | null = record._next; this._addToRemovals(this._unlink(record)); record = nextRecord; } if (this._unlinkedRecords !== null) { this._unlinkedRecords.clear(); } if (this._additionsTail !== null) { this._additionsTail._nextAdded = null; } if (this._movesTail !== null) { this._movesTail._nextMoved = null; } if (this._itTail !== null) { this._itTail._next = null; } if (this._removalsTail !== null) { this._removalsTail._nextRemoved = null; } if (this._identityChangesTail !== null) { this._identityChangesTail._nextIdentityChange = null; } } /** @internal */ _reinsertAfter( record: IterableChangeRecord_<V>, prevRecord: IterableChangeRecord_<V> | null, index: number, ): IterableChangeRecord_<V> { if (this._unlinkedRecords !== null) { this._unlinkedRecords.remove(record); } const prev = record._prevRemoved; const next = record._nextRemoved; if (prev === null) { this._removalsHead = next; } else { prev._nextRemoved = next; } if (next === null) { this._removalsTail = prev; } else { next._prevRemoved = prev; } this._insertAfter(record, prevRecord, index); this._addToMoves(record, index); return record; } /** @internal */ _moveAfter( record: IterableChangeRecord_<V>, prevRecord: IterableChangeRecord_<V> | null, index: number, ): IterableChangeRecord_<V> { this._unlink(record); this._insertAfter(record, prevRecord, index); this._addToMoves(record, index); return record; } /** @internal */ _addAfter( record: IterableChangeRecord_<V>, prevRecord: IterableChangeRecord_<V> | null, index: number, ): IterableChangeRecord_<V> { this._insertAfter(record, prevRecord, index); if (this._additionsTail === null) { // TODO(vicb): // assert(this._additionsHead === null); this._additionsTail = this._additionsHead = record; } else { // TODO(vicb): // assert(_additionsTail._nextAdded === null); // assert(record._nextAdded === null); this._additionsTail = this._additionsTail._nextAdded = record; } return record; } /** @internal */
{ "end_byte": 16343, "start_byte": 9042, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_iterable_differ.ts" }
angular/packages/core/src/change_detection/differs/default_iterable_differ.ts_16346_23010
_insertAfter( record: IterableChangeRecord_<V>, prevRecord: IterableChangeRecord_<V> | null, index: number, ): IterableChangeRecord_<V> { // TODO(vicb): // assert(record != prevRecord); // assert(record._next === null); // assert(record._prev === null); const next: IterableChangeRecord_<V> | null = prevRecord === null ? this._itHead : prevRecord._next; // TODO(vicb): // assert(next != record); // assert(prevRecord != record); record._next = next; record._prev = prevRecord; if (next === null) { this._itTail = record; } else { next._prev = record; } if (prevRecord === null) { this._itHead = record; } else { prevRecord._next = record; } if (this._linkedRecords === null) { this._linkedRecords = new _DuplicateMap<V>(); } this._linkedRecords.put(record); record.currentIndex = index; return record; } /** @internal */ _remove(record: IterableChangeRecord_<V>): IterableChangeRecord_<V> { return this._addToRemovals(this._unlink(record)); } /** @internal */ _unlink(record: IterableChangeRecord_<V>): IterableChangeRecord_<V> { if (this._linkedRecords !== null) { this._linkedRecords.remove(record); } const prev = record._prev; const next = record._next; // TODO(vicb): // assert((record._prev = null) === null); // assert((record._next = null) === null); if (prev === null) { this._itHead = next; } else { prev._next = next; } if (next === null) { this._itTail = prev; } else { next._prev = prev; } return record; } /** @internal */ _addToMoves(record: IterableChangeRecord_<V>, toIndex: number): IterableChangeRecord_<V> { // TODO(vicb): // assert(record._nextMoved === null); if (record.previousIndex === toIndex) { return record; } if (this._movesTail === null) { // TODO(vicb): // assert(_movesHead === null); this._movesTail = this._movesHead = record; } else { // TODO(vicb): // assert(_movesTail._nextMoved === null); this._movesTail = this._movesTail._nextMoved = record; } return record; } private _addToRemovals(record: IterableChangeRecord_<V>): IterableChangeRecord_<V> { if (this._unlinkedRecords === null) { this._unlinkedRecords = new _DuplicateMap<V>(); } this._unlinkedRecords.put(record); record.currentIndex = null; record._nextRemoved = null; if (this._removalsTail === null) { // TODO(vicb): // assert(_removalsHead === null); this._removalsTail = this._removalsHead = record; record._prevRemoved = null; } else { // TODO(vicb): // assert(_removalsTail._nextRemoved === null); // assert(record._nextRemoved === null); record._prevRemoved = this._removalsTail; this._removalsTail = this._removalsTail._nextRemoved = record; } return record; } /** @internal */ _addIdentityChange(record: IterableChangeRecord_<V>, item: V) { record.item = item; if (this._identityChangesTail === null) { this._identityChangesTail = this._identityChangesHead = record; } else { this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record; } return record; } } export class IterableChangeRecord_<V> implements IterableChangeRecord<V> { currentIndex: number | null = null; previousIndex: number | null = null; /** @internal */ _nextPrevious: IterableChangeRecord_<V> | null = null; /** @internal */ _prev: IterableChangeRecord_<V> | null = null; /** @internal */ _next: IterableChangeRecord_<V> | null = null; /** @internal */ _prevDup: IterableChangeRecord_<V> | null = null; /** @internal */ _nextDup: IterableChangeRecord_<V> | null = null; /** @internal */ _prevRemoved: IterableChangeRecord_<V> | null = null; /** @internal */ _nextRemoved: IterableChangeRecord_<V> | null = null; /** @internal */ _nextAdded: IterableChangeRecord_<V> | null = null; /** @internal */ _nextMoved: IterableChangeRecord_<V> | null = null; /** @internal */ _nextIdentityChange: IterableChangeRecord_<V> | null = null; constructor( public item: V, public trackById: any, ) {} } // A linked list of IterableChangeRecords with the same IterableChangeRecord_.item class _DuplicateItemRecordList<V> { /** @internal */ _head: IterableChangeRecord_<V> | null = null; /** @internal */ _tail: IterableChangeRecord_<V> | null = null; /** * Append the record to the list of duplicates. * * Note: by design all records in the list of duplicates hold the same value in record.item. */ add(record: IterableChangeRecord_<V>): void { if (this._head === null) { this._head = this._tail = record; record._nextDup = null; record._prevDup = null; } else { // TODO(vicb): // assert(record.item == _head.item || // record.item is num && record.item.isNaN && _head.item is num && _head.item.isNaN); this._tail!._nextDup = record; record._prevDup = this._tail; record._nextDup = null; this._tail = record; } } // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and // IterableChangeRecord_.currentIndex >= atOrAfterIndex get(trackById: any, atOrAfterIndex: number | null): IterableChangeRecord_<V> | null { let record: IterableChangeRecord_<V> | null; for (record = this._head; record !== null; record = record._nextDup) { if ( (atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex!) && Object.is(record.trackById, trackById) ) { return record; } } return null; } /** * Remove one {@link IterableChangeRecord_} from the list of duplicates. * * Returns whether the list of duplicates is empty. */ remove(record: IterableChangeRecord_<V>): boolean { // TODO(vicb): // assert(() { // // verify that the record being removed is in the list. // for (IterableChangeRecord_ cursor = _head; cursor != null; cursor = cursor._nextDup) { // if (identical(cursor, record)) return true; // } // return false; //}); const prev: IterableChangeRecord_<V> | null = record._prevDup; const next: IterableChangeRecord_<V> | null = record._nextDup; if (prev === null) { this._head = next; } else { prev._nextDup = next; } if (next === null) { this._tail = prev; } else { next._prevDup = prev; } return this._head === null; } }
{ "end_byte": 23010, "start_byte": 16346, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_iterable_differ.ts" }
angular/packages/core/src/change_detection/differs/default_iterable_differ.ts_23012_24946
class _DuplicateMap<V> { map = new Map<any, _DuplicateItemRecordList<V>>(); put(record: IterableChangeRecord_<V>) { const key = record.trackById; let duplicates = this.map.get(key); if (!duplicates) { duplicates = new _DuplicateItemRecordList<V>(); this.map.set(key, duplicates); } duplicates.add(record); } /** * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there. * * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we * have any more `a`s needs to return the second `a`. */ get(trackById: any, atOrAfterIndex: number | null): IterableChangeRecord_<V> | null { const key = trackById; const recordList = this.map.get(key); return recordList ? recordList.get(trackById, atOrAfterIndex) : null; } /** * Removes a {@link IterableChangeRecord_} from the list of duplicates. * * The list of duplicates also is removed from the map if it gets empty. */ remove(record: IterableChangeRecord_<V>): IterableChangeRecord_<V> { const key = record.trackById; const recordList: _DuplicateItemRecordList<V> = this.map.get(key)!; // Remove the list of duplicates when it gets empty if (recordList.remove(record)) { this.map.delete(key); } return record; } get isEmpty(): boolean { return this.map.size === 0; } clear() { this.map.clear(); } } function getPreviousIndex( item: any, addRemoveOffset: number, moveOffsets: number[] | null, ): number { const previousIndex = item.previousIndex; if (previousIndex === null) return previousIndex; let moveOffset = 0; if (moveOffsets && previousIndex < moveOffsets.length) { moveOffset = moveOffsets[previousIndex]; } return previousIndex + addRemoveOffset + moveOffset; }
{ "end_byte": 24946, "start_byte": 23012, "url": "https://github.com/angular/angular/blob/main/packages/core/src/change_detection/differs/default_iterable_differ.ts" }
angular/packages/core/src/hydration/node_lookup_utils.ts_0_7509
/** * @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 {TNode, TNodeType} from '../render3/interfaces/node'; import {RElement, RNode} from '../render3/interfaces/renderer_dom'; import { DECLARATION_COMPONENT_VIEW, HEADER_OFFSET, HOST, LView, TView, } from '../render3/interfaces/view'; import {getFirstNativeNode} from '../render3/node_manipulation'; import {ɵɵresolveBody} from '../render3/util/misc_utils'; import {renderStringify} from '../render3/util/stringify_utils'; import {getNativeByTNode, unwrapRNode} from '../render3/util/view_utils'; import {assertDefined} from '../util/assert'; import {compressNodeLocation, decompressNodeLocation} from './compression'; import { nodeNotFoundAtPathError, nodeNotFoundError, validateSiblingNodeExists, } from './error_handling'; import { DehydratedView, NodeNavigationStep, NODES, REFERENCE_NODE_BODY, REFERENCE_NODE_HOST, } from './interfaces'; import {calcSerializedContainerSize, getSegmentHead} from './utils'; /** Whether current TNode is a first node in an <ng-container>. */ function isFirstElementInNgContainer(tNode: TNode): boolean { return !tNode.prev && tNode.parent?.type === TNodeType.ElementContainer; } /** Returns an instruction index (subtracting HEADER_OFFSET). */ function getNoOffsetIndex(tNode: TNode): number { return tNode.index - HEADER_OFFSET; } /** * Check whether a given node exists, but is disconnected from the DOM. */ export function isDisconnectedNode(tNode: TNode, lView: LView) { return ( !(tNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)) && !!lView[tNode.index] && isDisconnectedRNode(unwrapRNode(lView[tNode.index])) ); } /** * Check whether the given node exists, but is disconnected from the DOM. * * Note: we leverage the fact that we have this information available in the DOM emulation * layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and * only use internal data structures and state to compute this information. */ export function isDisconnectedRNode(rNode: RNode | null) { return !!rNode && !(rNode as Node).isConnected; } /** * Locate a node in an i18n tree that corresponds to a given instruction index. * * @param hydrationInfo The hydration annotation data * @param noOffsetIndex the instruction index * @returns an RNode that corresponds to the instruction index */ export function locateI18nRNodeByIndex<T extends RNode>( hydrationInfo: DehydratedView, noOffsetIndex: number, ): T | null | undefined { const i18nNodes = hydrationInfo.i18nNodes; if (i18nNodes) { return i18nNodes.get(noOffsetIndex) as T | null | undefined; } return undefined; } /** * Attempt to locate an RNode by a path, if it exists. * * @param hydrationInfo The hydration annotation data * @param lView the current lView * @param noOffsetIndex the instruction index * @returns an RNode that corresponds to the instruction index or null if no path exists */ export function tryLocateRNodeByPath( hydrationInfo: DehydratedView, lView: LView<unknown>, noOffsetIndex: number, ): RNode | null { const nodes = hydrationInfo.data[NODES]; const path = nodes?.[noOffsetIndex]; return path ? locateRNodeByPath(path, lView) : null; } /** * Locate a node in DOM tree that corresponds to a given TNode. * * @param hydrationInfo The hydration annotation data * @param tView the current tView * @param lView the current lView * @param tNode the current tNode * @returns an RNode that represents a given tNode */ export function locateNextRNode<T extends RNode>( hydrationInfo: DehydratedView, tView: TView, lView: LView<unknown>, tNode: TNode, ): T | null { const noOffsetIndex = getNoOffsetIndex(tNode); let native = locateI18nRNodeByIndex(hydrationInfo, noOffsetIndex); if (native === undefined) { const nodes = hydrationInfo.data[NODES]; if (nodes?.[noOffsetIndex]) { // We know the exact location of the node. native = locateRNodeByPath(nodes[noOffsetIndex], lView); } else if (tView.firstChild === tNode) { // We create a first node in this view, so we use a reference // to the first child in this DOM segment. native = hydrationInfo.firstChild; } else { // Locate a node based on a previous sibling or a parent node. const previousTNodeParent = tNode.prev === null; const previousTNode = (tNode.prev ?? tNode.parent)!; ngDevMode && assertDefined( previousTNode, 'Unexpected state: current TNode does not have a connection ' + 'to the previous node or a parent node.', ); if (isFirstElementInNgContainer(tNode)) { const noOffsetParentIndex = getNoOffsetIndex(tNode.parent!); native = getSegmentHead(hydrationInfo, noOffsetParentIndex); } else { let previousRElement = getNativeByTNode(previousTNode, lView); if (previousTNodeParent) { native = (previousRElement as RElement).firstChild; } else { // If the previous node is an element, but it also has container info, // this means that we are processing a node like `<div #vcrTarget>`, which is // represented in the DOM as `<div></div>...<!--container-->`. // In this case, there are nodes *after* this element and we need to skip // all of them to reach an element that we are looking for. const noOffsetPrevSiblingIndex = getNoOffsetIndex(previousTNode); const segmentHead = getSegmentHead(hydrationInfo, noOffsetPrevSiblingIndex); if (previousTNode.type === TNodeType.Element && segmentHead) { const numRootNodesToSkip = calcSerializedContainerSize( hydrationInfo, noOffsetPrevSiblingIndex, ); // `+1` stands for an anchor comment node after all the views in this container. const nodesToSkip = numRootNodesToSkip + 1; // First node after this segment. native = siblingAfter(nodesToSkip, segmentHead); } else { native = previousRElement.nextSibling; } } } } } return native as T; } /** * Skips over a specified number of nodes and returns the next sibling node after that. */ export function siblingAfter<T extends RNode>(skip: number, from: RNode): T | null { let currentNode = from; for (let i = 0; i < skip; i++) { ngDevMode && validateSiblingNodeExists(currentNode); currentNode = currentNode.nextSibling!; } return currentNode as T; } /** * Helper function to produce a string representation of the navigation steps * (in terms of `nextSibling` and `firstChild` navigations). Used in error * messages in dev mode. */ function stringifyNavigationInstructions(instructions: (number | NodeNavigationStep)[]): string { const container = []; for (let i = 0; i < instructions.length; i += 2) { const step = instructions[i]; const repeat = instructions[i + 1] as number; for (let r = 0; r < repeat; r++) { container.push(step === NodeNavigationStep.FirstChild ? 'firstChild' : 'nextSibling'); } } return container.join('.'); } /** * Helper function that navigates from a starting point node (the `from` node) * using provided set of navigation instructions (within `path` argument). */ f
{ "end_byte": 7509, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/node_lookup_utils.ts" }
angular/packages/core/src/hydration/node_lookup_utils.ts_7510_15251
nction navigateToNode(from: Node, instructions: (number | NodeNavigationStep)[]): RNode { let node = from; for (let i = 0; i < instructions.length; i += 2) { const step = instructions[i]; const repeat = instructions[i + 1] as number; for (let r = 0; r < repeat; r++) { if (ngDevMode && !node) { throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions)); } switch (step) { case NodeNavigationStep.FirstChild: node = node.firstChild!; break; case NodeNavigationStep.NextSibling: node = node.nextSibling!; break; } } } if (ngDevMode && !node) { throw nodeNotFoundAtPathError(from, stringifyNavigationInstructions(instructions)); } return node as RNode; } /** * Locates an RNode given a set of navigation instructions (which also contains * a starting point node info). */ function locateRNodeByPath(path: string, lView: LView): RNode { const [referenceNode, ...navigationInstructions] = decompressNodeLocation(path); let ref: Element; if (referenceNode === REFERENCE_NODE_HOST) { ref = lView[DECLARATION_COMPONENT_VIEW][HOST] as unknown as Element; } else if (referenceNode === REFERENCE_NODE_BODY) { ref = ɵɵresolveBody( lView[DECLARATION_COMPONENT_VIEW][HOST] as RElement & {ownerDocument: Document}, ); } else { const parentElementId = Number(referenceNode); ref = unwrapRNode((lView as any)[parentElementId + HEADER_OFFSET]) as Element; } return navigateToNode(ref, navigationInstructions); } /** * Generate a list of DOM navigation operations to get from node `start` to node `finish`. * * Note: assumes that node `start` occurs before node `finish` in an in-order traversal of the DOM * tree. That is, we should be able to get from `start` to `finish` purely by using `.firstChild` * and `.nextSibling` operations. */ export function navigateBetween(start: Node, finish: Node): NodeNavigationStep[] | null { if (start === finish) { return []; } else if (start.parentElement == null || finish.parentElement == null) { return null; } else if (start.parentElement === finish.parentElement) { return navigateBetweenSiblings(start, finish); } else { // `finish` is a child of its parent, so the parent will always have a child. const parent = finish.parentElement!; const parentPath = navigateBetween(start, parent); const childPath = navigateBetween(parent.firstChild!, finish); if (!parentPath || !childPath) return null; return [ // First navigate to `finish`'s parent ...parentPath, // Then to its first child. NodeNavigationStep.FirstChild, // And finally from that node to `finish` (maybe a no-op if we're already there). ...childPath, ]; } } /** * Calculates a path between 2 sibling nodes (generates a number of `NextSibling` navigations). * Returns `null` if no such path exists between the given nodes. */ function navigateBetweenSiblings(start: Node, finish: Node): NodeNavigationStep[] | null { const nav: NodeNavigationStep[] = []; let node: Node | null = null; for (node = start; node != null && node !== finish; node = node.nextSibling) { nav.push(NodeNavigationStep.NextSibling); } // If the `node` becomes `null` or `undefined` at the end, that means that we // didn't find the `end` node, thus return `null` (which would trigger serialization // error to be produced). return node == null ? null : nav; } /** * Calculates a path between 2 nodes in terms of `nextSibling` and `firstChild` * navigations: * - the `from` node is a known node, used as an starting point for the lookup * (the `fromNodeName` argument is a string representation of the node). * - the `to` node is a node that the runtime logic would be looking up, * using the path generated by this function. */ export function calcPathBetween(from: Node, to: Node, fromNodeName: string): string | null { const path = navigateBetween(from, to); return path === null ? null : compressNodeLocation(fromNodeName, path); } /** * Invoked at serialization time (on the server) when a set of navigation * instructions needs to be generated for a TNode. */ export function calcPathForNode( tNode: TNode, lView: LView, excludedParentNodes: Set<number> | null, ): string { let parentTNode = tNode.parent; let parentIndex: number | string; let parentRNode: RNode; let referenceNodeName: string; // Skip over all parent nodes that are disconnected from the DOM, such nodes // can not be used as anchors. // // This might happen in certain content projection-based use-cases, where // a content of an element is projected and used, when a parent element // itself remains detached from DOM. In this scenario we try to find a parent // element that is attached to DOM and can act as an anchor instead. // // It can also happen that the parent node should be excluded, for example, // because it belongs to an i18n block, which requires paths which aren't // relative to other views in an i18n block. while ( parentTNode !== null && (isDisconnectedNode(parentTNode, lView) || excludedParentNodes?.has(parentTNode.index)) ) { parentTNode = parentTNode.parent; } if (parentTNode === null || !(parentTNode.type & TNodeType.AnyRNode)) { // If there is no parent TNode or a parent TNode does not represent an RNode // (i.e. not a DOM node), use component host element as a reference node. parentIndex = referenceNodeName = REFERENCE_NODE_HOST; parentRNode = lView[DECLARATION_COMPONENT_VIEW][HOST]!; } else { // Use parent TNode as a reference node. parentIndex = parentTNode.index; parentRNode = unwrapRNode(lView[parentIndex]); referenceNodeName = renderStringify(parentIndex - HEADER_OFFSET); } let rNode = unwrapRNode(lView[tNode.index]); if (tNode.type & (TNodeType.AnyContainer | TNodeType.Icu)) { // For <ng-container> nodes, instead of serializing a reference // to the anchor comment node, serialize a location of the first // DOM element. Paired with the container size (serialized as a part // of `ngh.containers`), it should give enough information for runtime // to hydrate nodes in this container. const firstRNode = getFirstNativeNode(lView, tNode); // If container is not empty, use a reference to the first element, // otherwise, rNode would point to an anchor comment node. if (firstRNode) { rNode = firstRNode; } } let path: string | null = calcPathBetween(parentRNode as Node, rNode as Node, referenceNodeName); if (path === null && parentRNode !== rNode) { // Searching for a path between elements within a host node failed. // Trying to find a path to an element starting from the `document.body` instead. // // Important note: this type of reference is relatively unstable, since Angular // may not be able to control parts of the page that the runtime logic navigates // through. This is mostly needed to cover "portals" use-case (like menus, dialog boxes, // etc), where nodes are content-projected (including direct DOM manipulations) outside // of the host node. The better solution is to provide APIs to work with "portals", // at which point this code path would not be needed. const body = (parentRNode as Node).ownerDocument!.body as Node; path = calcPathBetween(body, rNode as Node, REFERENCE_NODE_BODY); if (path === null) { // If the path is still empty, it's likely that this node is detached and // won't be found during hydration. throw nodeNotFoundError(lView, tNode); } } return path!; }
{ "end_byte": 15251, "start_byte": 7510, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/node_lookup_utils.ts" }
angular/packages/core/src/hydration/incremental.ts_0_7845
/** * @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 {TransferState} from '../transfer_state'; import {onIdle} from '../defer/idle_scheduler'; import {DeferBlockTrigger} from '../defer/interfaces'; import {DeferBlockRegistry} from '../defer/registry'; import {onTimer} from '../defer/timer_scheduler'; import {Injector} from '../di'; import {assertDefined} from '../util/assert'; import {incrementallyHydrateFromBlockName} from './blocks'; import { DEFER_HYDRATE_TRIGGERS, NUM_ROOT_NODES, SerializedDeferBlock, SerializedTriggerDetails, } from './interfaces'; import {NGH_DEFER_BLOCKS_KEY} from './utils'; import {onViewport} from '../defer/dom_triggers'; import {fetchAndRenderDeferBlock} from './event_replay'; export function bootstrapIncrementalHydration(doc: Document, injector: Injector) { const deferBlockData = processBlockData(injector); const commentsByBlockId = gatherDeferBlocksCommentNodes(doc, doc.body); processAndInitTriggers(injector, deferBlockData, commentsByBlockId); } interface BlockSummary { data: SerializedDeferBlock; hydrate: {idle: boolean; immediate: boolean; viewport: boolean; timer: boolean}; } interface ElementTrigger { el: HTMLElement; blockName: string; delay?: number; } function isTimerTrigger(triggerInfo: DeferBlockTrigger | SerializedTriggerDetails): boolean { return typeof triggerInfo === 'object' && triggerInfo.trigger === DeferBlockTrigger.Timer; } function hasHydrateTimerTrigger(blockData: SerializedDeferBlock): boolean { return (blockData[DEFER_HYDRATE_TRIGGERS]?.filter((t) => isTimerTrigger(t)) ?? []).length > 0; } function hasHydrateTrigger(blockData: SerializedDeferBlock, trigger: DeferBlockTrigger): boolean { return blockData[DEFER_HYDRATE_TRIGGERS]?.includes(trigger) ?? false; } function createBlockSummary(blockInfo: SerializedDeferBlock): BlockSummary { return { data: blockInfo, hydrate: { idle: hasHydrateTrigger(blockInfo, DeferBlockTrigger.Idle), immediate: hasHydrateTrigger(blockInfo, DeferBlockTrigger.Immediate), timer: hasHydrateTimerTrigger(blockInfo), viewport: hasHydrateTrigger(blockInfo, DeferBlockTrigger.Viewport), }, }; } function processBlockData(injector: Injector): Map<string, BlockSummary> { const blockData = retrieveDeferBlockData(injector); let blockDetails = new Map<string, BlockSummary>(); for (let blockId in blockData) { blockDetails.set(blockId, createBlockSummary(blockData[blockId])); } return blockDetails; } function gatherDeferBlocksCommentNodes(doc: Document, node?: HTMLElement): Map<string, Comment> { const commentNodesIterator = doc.createNodeIterator(node ?? doc.body, NodeFilter.SHOW_COMMENT, { acceptNode(node) { return node.textContent?.match('ngh=') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; }, }); let currentNode: Comment; const nodesByBlockId = new Map<string, Comment>(); while ((currentNode = commentNodesIterator.nextNode() as Comment)) { const result = currentNode?.textContent?.match('d[0-9]+'); if (result?.length === 1) { nodesByBlockId.set(result[0], currentNode); } } return nodesByBlockId; } function getTimerDelay(summary: BlockSummary): number { const hydrateTrigger = summary.data[DEFER_HYDRATE_TRIGGERS]!.find((t) => isTimerTrigger(t), ) as SerializedTriggerDetails; return hydrateTrigger.delay!; } function processAndInitTriggers( injector: Injector, blockData: Map<string, BlockSummary>, nodes: Map<string, Comment>, ) { const idleElements: ElementTrigger[] = []; const timerElements: ElementTrigger[] = []; const viewportElements: ElementTrigger[] = []; const immediateElements: ElementTrigger[] = []; for (let [blockId, blockSummary] of blockData) { const commentNode = nodes.get(blockId); if (commentNode !== undefined) { const numRootNodes = blockSummary.data[NUM_ROOT_NODES]; let currentNode: Comment | HTMLElement = commentNode; for (let i = 0; i < numRootNodes; i++) { currentNode = currentNode.previousSibling as HTMLElement; if (currentNode.nodeType !== Node.ELEMENT_NODE) { continue; } const et: ElementTrigger = {el: currentNode, blockName: blockId}; // hydrate if (blockSummary.hydrate.idle) { idleElements.push(et); } if (blockSummary.hydrate.immediate) { immediateElements.push(et); } if (blockSummary.hydrate.timer) { et.delay = getTimerDelay(blockSummary); timerElements.push(et); } if (blockSummary.hydrate.viewport) { viewportElements.push(et); } } } } setIdleTriggers(injector, idleElements); setImmediateTriggers(injector, immediateElements); setViewportTriggers(injector, viewportElements); setTimerTriggers(injector, timerElements); } async function setIdleTriggers(injector: Injector, ets: ElementTrigger[]) { for (const elementTrigger of ets) { const registry = injector.get(DeferBlockRegistry); const onInvoke = () => incrementallyHydrateFromBlockName( injector, elementTrigger.blockName, fetchAndRenderDeferBlock, ); const cleanupFn = onIdle(onInvoke, injector); registry.addCleanupFn(elementTrigger.blockName, cleanupFn); } } async function setViewportTriggers(injector: Injector, ets: ElementTrigger[]) { for (let et of ets) { onViewport( et.el, async () => { await incrementallyHydrateFromBlockName(injector, et.blockName, fetchAndRenderDeferBlock); }, injector, ); } } async function setTimerTriggers(injector: Injector, ets: ElementTrigger[]) { for (const elementTrigger of ets) { const registry = injector.get(DeferBlockRegistry); const onInvoke = async () => await incrementallyHydrateFromBlockName( injector, elementTrigger.blockName, fetchAndRenderDeferBlock, ); const timerFn = onTimer(elementTrigger.delay!); const cleanupFn = timerFn(onInvoke, injector); registry.addCleanupFn(elementTrigger.blockName, cleanupFn); } } async function setImmediateTriggers(injector: Injector, ets: ElementTrigger[]) { for (const elementTrigger of ets) { await incrementallyHydrateFromBlockName( injector, elementTrigger.blockName, fetchAndRenderDeferBlock, ); } } /** * Retrieves defer block hydration information from the TransferState. * * @param injector Injector that this component has access to. */ let _retrieveDeferBlockDataImpl: typeof retrieveDeferBlockDataImpl = () => { return {}; }; export function retrieveDeferBlockDataImpl(injector: Injector): { [key: string]: SerializedDeferBlock; } { const transferState = injector.get(TransferState, null, {optional: true}); if (transferState !== null) { const nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {}); // If the `ngh` attribute exists and has a non-empty value, // the hydration info *must* be present in the TransferState. // If there is no data for some reasons, this is an error. ngDevMode && assertDefined(nghDeferData, 'Unable to retrieve defer block info from the TransferState.'); return nghDeferData; } return {}; } /** * Sets the implementation for the `retrieveDeferBlockData` function. */ export function enableRetrieveDeferBlockDataImpl() { _retrieveDeferBlockDataImpl = retrieveDeferBlockDataImpl; } /** * Retrieves defer block data from TransferState storage */ export function retrieveDeferBlockData(injector: Injector): {[key: string]: SerializedDeferBlock} { return _retrieveDeferBlockDataImpl(injector); }
{ "end_byte": 7845, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/incremental.ts" }
angular/packages/core/src/hydration/views.ts_0_4005
/** * @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 {DEHYDRATED_VIEWS, LContainer} from '../render3/interfaces/container'; import {RNode} from '../render3/interfaces/renderer_dom'; import {removeDehydratedViews} from './cleanup'; import { DehydratedContainerView, MULTIPLIER, NUM_ROOT_NODES, SerializedContainerView, TEMPLATE_ID, } from './interfaces'; import {siblingAfter} from './node_lookup_utils'; /** * Given a current DOM node and a serialized information about the views * in a container, walks over the DOM structure, collecting the list of * dehydrated views. */ export function locateDehydratedViewsInContainer( currentRNode: RNode, serializedViews: SerializedContainerView[], ): [RNode, DehydratedContainerView[]] { const dehydratedViews: DehydratedContainerView[] = []; for (const serializedView of serializedViews) { // Repeats a view multiple times as needed, based on the serialized information // (for example, for *ngFor-produced views). for (let i = 0; i < (serializedView[MULTIPLIER] ?? 1); i++) { const view: DehydratedContainerView = { data: serializedView, firstChild: null, }; if (serializedView[NUM_ROOT_NODES] > 0) { // Keep reference to the first node in this view, // so it can be accessed while invoking template instructions. view.firstChild = currentRNode as HTMLElement; // Move over to the next node after this view, which can // either be a first node of the next view or an anchor comment // node after the last view in a container. currentRNode = siblingAfter(serializedView[NUM_ROOT_NODES], currentRNode)!; } dehydratedViews.push(view); } } return [currentRNode, dehydratedViews]; } /** * Reference to a function that searches for a matching dehydrated views * stored on a given lContainer. * Returns `null` by default, when hydration is not enabled. */ let _findMatchingDehydratedViewImpl: typeof findMatchingDehydratedViewImpl = () => null; /** * Retrieves the next dehydrated view from the LContainer and verifies that * it matches a given template id (from the TView that was used to create this * instance of a view). If the id doesn't match, that means that we are in an * unexpected state and can not complete the reconciliation process. Thus, * all dehydrated views from this LContainer are removed (including corresponding * DOM nodes) and the rendering is performed as if there were no dehydrated views * in this container. */ function findMatchingDehydratedViewImpl( lContainer: LContainer, template: string | null, ): DehydratedContainerView | null { const views = lContainer[DEHYDRATED_VIEWS]; if (!template || views === null || views.length === 0) { return null; } const view = views[0]; // Verify whether the first dehydrated view in the container matches // the template id passed to this function (that originated from a TView // that was used to create an instance of an embedded or component views. if (view.data[TEMPLATE_ID] === template) { // If the template id matches - extract the first view and return it. return views.shift()!; } else { // Otherwise, we are at the state when reconciliation can not be completed, // thus we remove all dehydrated views within this container (remove them // from internal data structures as well as delete associated elements from // the DOM tree). removeDehydratedViews(lContainer); return null; } } export function enableFindMatchingDehydratedViewImpl() { _findMatchingDehydratedViewImpl = findMatchingDehydratedViewImpl; } export function findMatchingDehydratedView( lContainer: LContainer, template: string | null, ): DehydratedContainerView | null { return _findMatchingDehydratedViewImpl(lContainer, template); }
{ "end_byte": 4005, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/views.ts" }
angular/packages/core/src/hydration/blocks.ts_0_4774
/** * @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 {DeferBlockRegistry} from '../defer/registry'; import {DEFER_PARENT_BLOCK_ID} from './interfaces'; import {NGH_DEFER_BLOCKS_KEY} from './utils'; import {Injector} from '../di'; import {TransferState} from '../transfer_state'; import {removeListenersFromBlocks} from '../event_delegation_utils'; import {cleanupLContainer} from './cleanup'; import {DeferBlock} from '../defer/interfaces'; import {whenStable, ApplicationRef} from '../application/application_ref'; /** * Finds first hydrated parent `@defer` block for a given block id. * If there are any dehydrated `@defer` blocks found along the way, * they are also stored and returned from the function (as a list of ids). * Note: This is utilizing serialized information to navigate up the tree */ export function findFirstHydratedParentDeferBlock(deferBlockId: string, injector: Injector) { const deferBlockRegistry = injector.get(DeferBlockRegistry); const transferState = injector.get(TransferState); const deferBlockParents = transferState.get(NGH_DEFER_BLOCKS_KEY, {}); const dehydratedBlocks: string[] = []; let deferBlock = deferBlockRegistry.get(deferBlockId); let currentBlockId: string | null = deferBlockId; // at each level we check if the registry has the given defer block id // - if it does, we know it was already hydrated and can stop here // - if it does not, we continue on while (!deferBlock) { dehydratedBlocks.unshift(currentBlockId); currentBlockId = deferBlockParents[currentBlockId][DEFER_PARENT_BLOCK_ID]; if (!currentBlockId) break; deferBlock = deferBlockRegistry.get(currentBlockId); } return {blockId: currentBlockId, deferBlock, dehydratedBlocks}; } /** * The core mechanism for incremental hydration. This recursively triggers * hydration for all the blocks in the tree that need to be hydrated and keeps * track of all those blocks that were hydrated along the way. * * @param injector * @param blockName * @param onTriggerFn The function that triggers the block and fetches deps * @param hydratedBlocks The set of blocks currently being hydrated in the tree * @returns */ export async function hydrateFromBlockName( injector: Injector, blockName: string, onTriggerFn: (deferBlock: DeferBlock) => void, hydratedBlocks: Set<string> = new Set(), ): Promise<{ deferBlock: DeferBlock | null; hydratedBlocks: Set<string>; }> { const deferBlockRegistry = injector.get(DeferBlockRegistry); // Make sure we don't hydrate/trigger the same thing multiple times if (deferBlockRegistry.hydrating.has(blockName)) return {deferBlock: null, hydratedBlocks}; const {blockId, deferBlock, dehydratedBlocks} = findFirstHydratedParentDeferBlock( blockName, injector, ); if (deferBlock && blockId) { // Step 2: Add the current block to the tracking sets to prevent // attempting to trigger hydration on a block more than once // simulataneously. hydratedBlocks.add(blockId); deferBlockRegistry.hydrating.add(blockId); // Step 3: Run the actual trigger function to fetch dependencies await onTriggerFn(deferBlock); // Step 4: Recursively trigger, fetch, and hydrate from the top of the hierarchy down let hydratedBlock: DeferBlock | null = deferBlock; for (const dehydratedBlock of dehydratedBlocks) { const hydratedInfo = await hydrateFromBlockName( injector, dehydratedBlock, onTriggerFn, hydratedBlocks, ); hydratedBlock = hydratedInfo.deferBlock; } // TODO(incremental-hydration): this is likely where we want to do Step 5: some cleanup work in the // DeferBlockRegistry. return {deferBlock: hydratedBlock, hydratedBlocks}; } else { // TODO(incremental-hydration): this is likely an error, consider producing a `console.error`. return {deferBlock: null, hydratedBlocks}; } } export async function incrementallyHydrateFromBlockName( injector: Injector, blockName: string, triggerFn: (deferBlock: DeferBlock) => void, ): Promise<void> { const {deferBlock, hydratedBlocks} = await hydrateFromBlockName(injector, blockName, triggerFn); if (deferBlock !== null) { // hydratedBlocks is a set, and needs to be converted to an array // for removing listeners removeListenersFromBlocks([...hydratedBlocks], injector); cleanupLContainer(deferBlock.lContainer); // we need to wait for app stability here so we don't continue before // the hydration process has finished, which could result in problems await whenStable(injector.get(ApplicationRef)); } }
{ "end_byte": 4774, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/blocks.ts" }
angular/packages/core/src/hydration/i18n.ts_0_7134
/** * @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 {inject, Injector} from '../di'; import {isRootTemplateMessage} from '../render3/i18n/i18n_util'; import {createIcuIterator} from '../render3/instructions/i18n_icu_container_visitor'; import {I18nNode, I18nNodeKind, I18nPlaceholderType, TI18n, TIcu} from '../render3/interfaces/i18n'; import {isTNodeShape, TNode, TNodeType} from '../render3/interfaces/node'; import type {Renderer} from '../render3/interfaces/renderer'; import type {RNode} from '../render3/interfaces/renderer_dom'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView, TVIEW} from '../render3/interfaces/view'; import {getFirstNativeNode, nativeRemoveNode} from '../render3/node_manipulation'; import {unwrapRNode} from '../render3/util/view_utils'; import {assertDefined, assertNotEqual} from '../util/assert'; import type {HydrationContext} from './annotate'; import {DehydratedIcuData, DehydratedView, I18N_DATA} from './interfaces'; import {isDisconnectedRNode, locateNextRNode, tryLocateRNodeByPath} from './node_lookup_utils'; import {isI18nInSkipHydrationBlock} from './skip_hydration'; import {IS_I18N_HYDRATION_ENABLED} from './tokens'; import { getNgContainerSize, initDisconnectedNodes, isDisconnectedNode, isSerializedElementContainer, processTextNodeBeforeSerialization, } from './utils'; let _isI18nHydrationSupportEnabled = false; let _prepareI18nBlockForHydrationImpl: typeof prepareI18nBlockForHydrationImpl = () => { // noop unless `enablePrepareI18nBlockForHydrationImpl` is invoked. }; export function setIsI18nHydrationSupportEnabled(enabled: boolean) { _isI18nHydrationSupportEnabled = enabled; } export function isI18nHydrationSupportEnabled() { return _isI18nHydrationSupportEnabled; } /** * Prepares an i18n block and its children, located at the given * view and instruction index, for hydration. * * @param lView lView with the i18n block * @param index index of the i18n block in the lView * @param parentTNode TNode of the parent of the i18n block * @param subTemplateIndex sub-template index, or -1 for the main template */ export function prepareI18nBlockForHydration( lView: LView, index: number, parentTNode: TNode | null, subTemplateIndex: number, ): void { _prepareI18nBlockForHydrationImpl(lView, index, parentTNode, subTemplateIndex); } export function enablePrepareI18nBlockForHydrationImpl() { _prepareI18nBlockForHydrationImpl = prepareI18nBlockForHydrationImpl; } export function isI18nHydrationEnabled(injector?: Injector) { injector = injector ?? inject(Injector); return injector.get(IS_I18N_HYDRATION_ENABLED, false); } /** * Collects, if not already cached, all of the indices in the * given TView which are children of an i18n block. * * Since i18n blocks don't introduce a parent TNode, this is necessary * in order to determine which indices in a LView are translated. */ export function getOrComputeI18nChildren( tView: TView, context: HydrationContext, ): Set<number> | null { let i18nChildren = context.i18nChildren.get(tView); if (i18nChildren === undefined) { i18nChildren = collectI18nChildren(tView); context.i18nChildren.set(tView, i18nChildren); } return i18nChildren; } function collectI18nChildren(tView: TView): Set<number> | null { const children = new Set<number>(); function collectI18nViews(node: I18nNode) { children.add(node.index); switch (node.kind) { case I18nNodeKind.ELEMENT: case I18nNodeKind.PLACEHOLDER: { for (const childNode of node.children) { collectI18nViews(childNode); } break; } case I18nNodeKind.ICU: { for (const caseNodes of node.cases) { for (const caseNode of caseNodes) { collectI18nViews(caseNode); } } break; } } } // Traverse through the AST of each i18n block in the LView, // and collect every instruction index. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { const tI18n = tView.data[i] as TI18n | undefined; if (!tI18n || !tI18n.ast) { continue; } for (const node of tI18n.ast) { collectI18nViews(node); } } return children.size === 0 ? null : children; } /** * Resulting data from serializing an i18n block. */ export interface SerializedI18nBlock { /** * A queue of active ICU cases from a depth-first traversal * of the i18n AST. This is serialized to the client in order * to correctly associate DOM nodes with i18n nodes during * hydration. */ caseQueue: Array<number>; /** * A set of indices in the lView of the block for nodes * that are disconnected from the DOM. In i18n, this can * happen when using content projection but some nodes are * not selected by an <ng-content />. */ disconnectedNodes: Set<number>; /** * A set of indices in the lView of the block for nodes * considered "disjoint", indicating that we need to serialize * a path to the node in order to hydrate it. * * A node is considered disjoint when its RNode does not * directly follow the RNode of the previous i18n node, for * example, because of content projection. */ disjointNodes: Set<number>; } /** * Attempts to serialize i18n data for an i18n block, located at * the given view and instruction index. * * @param lView lView with the i18n block * @param index index of the i18n block in the lView * @param context the hydration context * @returns the i18n data, or null if there is no relevant data */ export function trySerializeI18nBlock( lView: LView, index: number, context: HydrationContext, ): SerializedI18nBlock | null { if (!context.isI18nHydrationEnabled) { return null; } const tView = lView[TVIEW]; const tI18n = tView.data[index] as TI18n | undefined; if (!tI18n || !tI18n.ast) { return null; } const parentTNode = tView.data[tI18n.parentTNodeIndex] as TNode; if (parentTNode && isI18nInSkipHydrationBlock(parentTNode)) { return null; } const serializedI18nBlock: SerializedI18nBlock = { caseQueue: [], disconnectedNodes: new Set(), disjointNodes: new Set(), }; serializeI18nBlock(lView, serializedI18nBlock, context, tI18n.ast); return serializedI18nBlock.caseQueue.length === 0 && serializedI18nBlock.disconnectedNodes.size === 0 && serializedI18nBlock.disjointNodes.size === 0 ? null : serializedI18nBlock; } function serializeI18nBlock( lView: LView, serializedI18nBlock: SerializedI18nBlock, context: HydrationContext, nodes: I18nNode[], ): Node | null { let prevRNode = null; for (const node of nodes) { const nextRNode = serializeI18nNode(lView, serializedI18nBlock, context, node); if (nextRNode) { if (isDisjointNode(prevRNode, nextRNode)) { serializedI18nBlock.disjointNodes.add(node.index - HEADER_OFFSET); } prevRNode = nextRNode; } } return prevRNode; }
{ "end_byte": 7134, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/i18n.ts" }
angular/packages/core/src/hydration/i18n.ts_7136_12657
/** * Helper to determine whether the given nodes are "disjoint". * * The i18n hydration process walks through the DOM and i18n nodes * at the same time. It expects the sibling DOM node of the previous * i18n node to be the first node of the next i18n node. * * In cases of content projection, this won't always be the case. So * when we detect that, we mark the node as "disjoint", ensuring that * we will serialize the path to the node. This way, when we hydrate the * i18n node, we will be able to find the correct place to start. */ function isDisjointNode(prevNode: Node | null, nextNode: Node) { return prevNode && prevNode.nextSibling !== nextNode; } /** * Process the given i18n node for serialization. * Returns the first RNode for the i18n node to begin hydration. */ function serializeI18nNode( lView: LView, serializedI18nBlock: SerializedI18nBlock, context: HydrationContext, node: I18nNode, ): Node | null { const maybeRNode = unwrapRNode(lView[node.index]!); if (!maybeRNode || isDisconnectedRNode(maybeRNode)) { serializedI18nBlock.disconnectedNodes.add(node.index - HEADER_OFFSET); return null; } const rNode = maybeRNode as Node; switch (node.kind) { case I18nNodeKind.TEXT: { processTextNodeBeforeSerialization(context, rNode); break; } case I18nNodeKind.ELEMENT: case I18nNodeKind.PLACEHOLDER: { serializeI18nBlock(lView, serializedI18nBlock, context, node.children); break; } case I18nNodeKind.ICU: { const currentCase = lView[node.currentCaseLViewIndex] as number | null; if (currentCase != null) { // i18n uses a negative value to signal a change to a new case, so we // need to invert it to get the proper value. const caseIdx = currentCase < 0 ? ~currentCase : currentCase; serializedI18nBlock.caseQueue.push(caseIdx); serializeI18nBlock(lView, serializedI18nBlock, context, node.cases[caseIdx]); } break; } } return getFirstNativeNodeForI18nNode(lView, node) as Node | null; } /** * Helper function to get the first native node to begin hydrating * the given i18n node. */ function getFirstNativeNodeForI18nNode(lView: LView, node: I18nNode) { const tView = lView[TVIEW]; const maybeTNode = tView.data[node.index]; if (isTNodeShape(maybeTNode)) { // If the node is backed by an actual TNode, we can simply delegate. return getFirstNativeNode(lView, maybeTNode); } else if (node.kind === I18nNodeKind.ICU) { // A nested ICU container won't have an actual TNode. In that case, we can use // an iterator to find the first child. const icuIterator = createIcuIterator(maybeTNode as TIcu, lView); let rNode: RNode | null = icuIterator(); // If the ICU container has no nodes, then we use the ICU anchor as the node. return rNode ?? unwrapRNode(lView[node.index]); } else { // Otherwise, the node is a text or trivial element in an ICU container, // and we can just use the RNode directly. return unwrapRNode(lView[node.index]) ?? null; } } /** * Describes shared data available during the hydration process. */ interface I18nHydrationContext { hydrationInfo: DehydratedView; lView: LView; i18nNodes: Map<number, RNode | null>; disconnectedNodes: Set<number>; caseQueue: number[]; dehydratedIcuData: Map<number, DehydratedIcuData>; } /** * Describes current hydration state. */ interface I18nHydrationState { // The current node currentNode: Node | null; /** * Whether the tree should be connected. * * During hydration, it can happen that we expect to have a * current RNode, but we don't. In such cases, we still need * to propagate the expectation to the corresponding LViews, * so that the proper downstream error handling can provide * the correct context for the error. */ isConnected: boolean; } function setCurrentNode(state: I18nHydrationState, node: Node | null) { state.currentNode = node; } /** * Marks the current RNode as the hydration root for the given * AST node. */ function appendI18nNodeToCollection( context: I18nHydrationContext, state: I18nHydrationState, astNode: I18nNode, ) { const noOffsetIndex = astNode.index - HEADER_OFFSET; const {disconnectedNodes} = context; const currentNode = state.currentNode; if (state.isConnected) { context.i18nNodes.set(noOffsetIndex, currentNode); // We expect the node to be connected, so ensure that it // is not in the set, regardless of whether we found it, // so that the downstream error handling can provide the // proper context. disconnectedNodes.delete(noOffsetIndex); } else { disconnectedNodes.add(noOffsetIndex); } return currentNode; } /** * Skip over some sibling nodes during hydration. * * Note: we use this instead of `siblingAfter` as it's expected that * sometimes we might encounter null nodes. In those cases, we want to * defer to downstream error handling to provide proper context. */ function skipSiblingNodes(state: I18nHydrationState, skip: number) { let currentNode = state.currentNode; for (let i = 0; i < skip; i++) { if (!currentNode) { break; } currentNode = currentNode?.nextSibling ?? null; } return currentNode; } /** * Fork the given state into a new state for hydrating children. */ function forkHydrationState(state: I18nHydrationState, nextNode: Node | null) { return {currentNode: nextNode, isConnected: state.isConnected}; }
{ "end_byte": 12657, "start_byte": 7136, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/i18n.ts" }
angular/packages/core/src/hydration/i18n.ts_12659_15407
function prepareI18nBlockForHydrationImpl( lView: LView, index: number, parentTNode: TNode | null, subTemplateIndex: number, ) { const hydrationInfo = lView[HYDRATION]; if (!hydrationInfo) { return; } if ( !isI18nHydrationSupportEnabled() || (parentTNode && (isI18nInSkipHydrationBlock(parentTNode) || isDisconnectedNode(hydrationInfo, parentTNode.index - HEADER_OFFSET))) ) { return; } const tView = lView[TVIEW]; const tI18n = tView.data[index] as TI18n; ngDevMode && assertDefined(tI18n, 'Expected i18n data to be present in a given TView slot during hydration'); function findHydrationRoot() { if (isRootTemplateMessage(subTemplateIndex)) { // This is the root of an i18n block. In this case, our hydration root will // depend on where our parent TNode (i.e. the block with i18n applied) is // in the DOM. ngDevMode && assertDefined(parentTNode, 'Expected parent TNode while hydrating i18n root'); const rootNode = locateNextRNode(hydrationInfo!, tView, lView, parentTNode!) as Node; // If this i18n block is attached to an <ng-container>, then we want to begin // hydrating directly with the RNode. Otherwise, for a TNode with a physical DOM // element, we want to recurse into the first child and begin there. return parentTNode!.type & TNodeType.ElementContainer ? rootNode : rootNode.firstChild; } // This is a nested template in an i18n block. In this case, the entire view // is translated, and part of a dehydrated view in a container. This means that // we can simply begin hydration with the first dehydrated child. return hydrationInfo?.firstChild as Node; } const currentNode = findHydrationRoot(); ngDevMode && assertDefined(currentNode, 'Expected root i18n node during hydration'); const disconnectedNodes = initDisconnectedNodes(hydrationInfo) ?? new Set(); const i18nNodes = (hydrationInfo.i18nNodes ??= new Map<number, RNode | null>()); const caseQueue = hydrationInfo.data[I18N_DATA]?.[index - HEADER_OFFSET] ?? []; const dehydratedIcuData = (hydrationInfo.dehydratedIcuData ??= new Map< number, DehydratedIcuData >()); collectI18nNodesFromDom( {hydrationInfo, lView, i18nNodes, disconnectedNodes, caseQueue, dehydratedIcuData}, {currentNode, isConnected: true}, tI18n.ast, ); // Nodes from inactive ICU cases should be considered disconnected. We track them above // because they aren't (and shouldn't be) serialized. Since we may mutate or create a // new set, we need to be sure to write the expected value back to the DehydratedView. hydrationInfo.disconnectedNodes = disconnectedNodes.size === 0 ? null : disconnectedNodes; }
{ "end_byte": 15407, "start_byte": 12659, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/i18n.ts" }
angular/packages/core/src/hydration/i18n.ts_15409_23381
function collectI18nNodesFromDom( context: I18nHydrationContext, state: I18nHydrationState, nodeOrNodes: I18nNode | I18nNode[], ) { if (Array.isArray(nodeOrNodes)) { let nextState = state; for (const node of nodeOrNodes) { // Whenever a node doesn't directly follow the previous RNode, it // is given a path. We need to resume collecting nodes from that location // until and unless we find another disjoint node. const targetNode = tryLocateRNodeByPath( context.hydrationInfo, context.lView, node.index - HEADER_OFFSET, ); if (targetNode) { nextState = forkHydrationState(state, targetNode as Node); } collectI18nNodesFromDom(context, nextState, node); } } else { if (context.disconnectedNodes.has(nodeOrNodes.index - HEADER_OFFSET)) { // i18n nodes can be considered disconnected if e.g. they were projected. // In that case, we have to make sure to skip over them. return; } switch (nodeOrNodes.kind) { case I18nNodeKind.TEXT: { // Claim a text node for hydration const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes); setCurrentNode(state, currentNode?.nextSibling ?? null); break; } case I18nNodeKind.ELEMENT: { // Recurse into the current element's children... collectI18nNodesFromDom( context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children, ); // And claim the parent element itself. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes); setCurrentNode(state, currentNode?.nextSibling ?? null); break; } case I18nNodeKind.PLACEHOLDER: { const noOffsetIndex = nodeOrNodes.index - HEADER_OFFSET; const {hydrationInfo} = context; const containerSize = getNgContainerSize(hydrationInfo, noOffsetIndex); switch (nodeOrNodes.type) { case I18nPlaceholderType.ELEMENT: { // Hydration expects to find the head of the element. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes); // A TNode for the node may not yet if we're hydrating during the first pass, // so use the serialized data to determine if this is an <ng-container>. if (isSerializedElementContainer(hydrationInfo, noOffsetIndex)) { // An <ng-container> doesn't have a physical DOM node, so we need to // continue hydrating from siblings. collectI18nNodesFromDom(context, state, nodeOrNodes.children); // Skip over the anchor element. It will be claimed by the // downstream container hydration. const nextNode = skipSiblingNodes(state, 1); setCurrentNode(state, nextNode); } else { // Non-container elements represent an actual node in the DOM, so we // need to continue hydration with the children, and claim the node. collectI18nNodesFromDom( context, forkHydrationState(state, state.currentNode?.firstChild ?? null), nodeOrNodes.children, ); setCurrentNode(state, currentNode?.nextSibling ?? null); // Elements can also be the anchor of a view container, so there may // be elements after this node that we need to skip. if (containerSize !== null) { // `+1` stands for an anchor node after all of the views in the container. const nextNode = skipSiblingNodes(state, containerSize + 1); setCurrentNode(state, nextNode); } } break; } case I18nPlaceholderType.SUBTEMPLATE: { ngDevMode && assertNotEqual( containerSize, null, 'Expected a container size while hydrating i18n subtemplate', ); // Hydration expects to find the head of the template. appendI18nNodeToCollection(context, state, nodeOrNodes); // Skip over all of the template children, as well as the anchor // node, since the template itself will handle them instead. const nextNode = skipSiblingNodes(state, containerSize! + 1); setCurrentNode(state, nextNode); break; } } break; } case I18nNodeKind.ICU: { // If the current node is connected, we need to pop the next case from the // queue, so that the active case is also considered connected. const selectedCase = state.isConnected ? context.caseQueue.shift()! : null; const childState = {currentNode: null, isConnected: false}; // We traverse through each case, even if it's not active, // so that we correctly populate disconnected nodes. for (let i = 0; i < nodeOrNodes.cases.length; i++) { collectI18nNodesFromDom( context, i === selectedCase ? state : childState, nodeOrNodes.cases[i], ); } if (selectedCase !== null) { // ICUs represent a branching state, and the selected case could be different // than what it was on the server. In that case, we need to be able to clean // up the nodes from the original case. To do that, we store the selected case. context.dehydratedIcuData.set(nodeOrNodes.index, {case: selectedCase, node: nodeOrNodes}); } // Hydration expects to find the ICU anchor element. const currentNode = appendI18nNodeToCollection(context, state, nodeOrNodes); setCurrentNode(state, currentNode?.nextSibling ?? null); break; } } } } let _claimDehydratedIcuCaseImpl: typeof claimDehydratedIcuCaseImpl = () => { // noop unless `enableClaimDehydratedIcuCaseImpl` is invoked }; /** * Mark the case for the ICU node at the given index in the view as claimed, * allowing its nodes to be hydrated and not cleaned up. */ export function claimDehydratedIcuCase(lView: LView, icuIndex: number, caseIndex: number) { _claimDehydratedIcuCaseImpl(lView, icuIndex, caseIndex); } export function enableClaimDehydratedIcuCaseImpl() { _claimDehydratedIcuCaseImpl = claimDehydratedIcuCaseImpl; } function claimDehydratedIcuCaseImpl(lView: LView, icuIndex: number, caseIndex: number) { const dehydratedIcuDataMap = lView[HYDRATION]?.dehydratedIcuData; if (dehydratedIcuDataMap) { const dehydratedIcuData = dehydratedIcuDataMap.get(icuIndex); if (dehydratedIcuData?.case === caseIndex) { // If the case we're attempting to claim matches the dehydrated one, // we remove it from the map to mark it as "claimed." dehydratedIcuDataMap.delete(icuIndex); } } } /** * Clean up all i18n hydration data associated with the given view. */ export function cleanupI18nHydrationData(lView: LView) { const hydrationInfo = lView[HYDRATION]; if (hydrationInfo) { const {i18nNodes, dehydratedIcuData: dehydratedIcuDataMap} = hydrationInfo; if (i18nNodes && dehydratedIcuDataMap) { const renderer = lView[RENDERER]; for (const dehydratedIcuData of dehydratedIcuDataMap.values()) { cleanupDehydratedIcuData(renderer, i18nNodes, dehydratedIcuData); } } hydrationInfo.i18nNodes = undefined; hydrationInfo.dehydratedIcuData = undefined; } } function cleanupDehydratedIcuData( renderer: Renderer, i18nNodes: Map<number, RNode | null>, dehydratedIcuData: DehydratedIcuData, ) { for (const node of dehydratedIcuData.node.cases[dehydratedIcuData.case]) { const rNode = i18nNodes.get(node.index - HEADER_OFFSET); if (rNode) { nativeRemoveNode(renderer, rNode, false); } } }
{ "end_byte": 23381, "start_byte": 15409, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/i18n.ts" }
angular/packages/core/src/hydration/utils.ts_0_8034
/** * @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 {Injector} from '../di/injector'; import type {ViewRef} from '../linker/view_ref'; import {getComponent} from '../render3/util/discovery_utils'; import {LContainer} from '../render3/interfaces/container'; import {getDocument} from '../render3/interfaces/document'; import {RElement, RNode} from '../render3/interfaces/renderer_dom'; import {isRootView} from '../render3/interfaces/type_checks'; import {HEADER_OFFSET, LView, TVIEW, TViewType} from '../render3/interfaces/view'; import {makeStateKey, TransferState} from '../transfer_state'; import {assertDefined} from '../util/assert'; import type {HydrationContext} from './annotate'; import { CONTAINERS, DehydratedView, DISCONNECTED_NODES, ELEMENT_CONTAINERS, MULTIPLIER, NUM_ROOT_NODES, SerializedContainerView, SerializedDeferBlock, SerializedView, } from './interfaces'; import {IS_INCREMENTAL_HYDRATION_ENABLED} from './tokens'; /** * The name of the key used in the TransferState collection, * where hydration information is located. */ const TRANSFER_STATE_TOKEN_ID = '__nghData__'; /** * Lookup key used to reference DOM hydration data (ngh) in `TransferState`. */ export const NGH_DATA_KEY = makeStateKey<Array<SerializedView>>(TRANSFER_STATE_TOKEN_ID); /** * The name of the key used in the TransferState collection, * where serialized defer block information is located. */ export const TRANSFER_STATE_DEFER_BLOCKS_INFO = '__nghDeferData__'; /** * Lookup key used to retrieve defer block datain `TransferState`. */ export const NGH_DEFER_BLOCKS_KEY = makeStateKey<{[key: string]: SerializedDeferBlock}>( TRANSFER_STATE_DEFER_BLOCKS_INFO, ); /** * The name of the attribute that would be added to host component * nodes and contain a reference to a particular slot in transferred * state that contains the necessary hydration info for this component. */ export const NGH_ATTR_NAME = 'ngh'; /** * Marker used in a comment node to ensure hydration content integrity */ export const SSR_CONTENT_INTEGRITY_MARKER = 'nghm'; export const enum TextNodeMarker { /** * The contents of the text comment added to nodes that would otherwise be * empty when serialized by the server and passed to the client. The empty * node is lost when the browser parses it otherwise. This comment node will * be replaced during hydration in the client to restore the lost empty text * node. */ EmptyNode = 'ngetn', /** * The contents of the text comment added in the case of adjacent text nodes. * When adjacent text nodes are serialized by the server and sent to the * client, the browser loses reference to the amount of nodes and assumes * just one text node. This separator is replaced during hydration to restore * the proper separation and amount of text nodes that should be present. */ Separator = 'ngtns', } /** * Reference to a function that reads `ngh` attribute value from a given RNode * and retrieves hydration information from the TransferState using that value * as an index. Returns `null` by default, when hydration is not enabled. * * @param rNode Component's host element. * @param injector Injector that this component has access to. * @param isRootView Specifies whether we trying to read hydration info for the root view. */ let _retrieveHydrationInfoImpl: typeof retrieveHydrationInfoImpl = () => null; export function retrieveHydrationInfoImpl( rNode: RElement, injector: Injector, isRootView = false, ): DehydratedView | null { let nghAttrValue = rNode.getAttribute(NGH_ATTR_NAME); if (nghAttrValue == null) return null; // For cases when a root component also acts as an anchor node for a ViewContainerRef // (for example, when ViewContainerRef is injected in a root component), there is a need // to serialize information about the component itself, as well as an LContainer that // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info: // (1) hydration info for the root component itself and (2) hydration info for the // ViewContainerRef instance (an LContainer). Each piece of information is included into // the hydration data (in the TransferState object) separately, thus we end up with 2 ids. // Since we only have 1 root element, we encode both bits of info into a single string: // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view // and 25 is the `ngh` for a root view which holds LContainer). const [componentViewNgh, rootViewNgh] = nghAttrValue.split('|'); nghAttrValue = isRootView ? rootViewNgh : componentViewNgh; if (!nghAttrValue) return null; // We've read one of the ngh ids, keep the remaining one, so that // we can set it back on the DOM element. const rootNgh = rootViewNgh ? `|${rootViewNgh}` : ''; const remainingNgh = isRootView ? componentViewNgh : rootNgh; let data: SerializedView = {}; let nghDeferData: {[key: string]: SerializedDeferBlock} | undefined; // An element might have an empty `ngh` attribute value (e.g. `<comp ngh="" />`), // which means that no special annotations are required. Do not attempt to read // from the TransferState in this case. if (nghAttrValue !== '') { const transferState = injector.get(TransferState, null, {optional: true}); if (transferState !== null) { const nghData = transferState.get(NGH_DATA_KEY, []); nghDeferData = transferState.get(NGH_DEFER_BLOCKS_KEY, {}); // The nghAttrValue is always a number referencing an index // in the hydration TransferState data. data = nghData[Number(nghAttrValue)]; // If the `ngh` attribute exists and has a non-empty value, // the hydration info *must* be present in the TransferState. // If there is no data for some reasons, this is an error. ngDevMode && assertDefined(data, 'Unable to retrieve hydration info from the TransferState.'); } } const dehydratedView: DehydratedView = { data, firstChild: rNode.firstChild ?? null, }; if (nghDeferData) { dehydratedView.dehydratedDeferBlockData = nghDeferData; } if (isRootView) { // If there is hydration info present for the root view, it means that there was // a ViewContainerRef injected in the root component. The root component host element // acted as an anchor node in this scenario. As a result, the DOM nodes that represent // embedded views in this ViewContainerRef are located as siblings to the host node, // i.e. `<app-root /><#VIEW1><#VIEW2>...<!--container-->`. In this case, the current // node becomes the first child of this root view and the next sibling is the first // element in the DOM segment. dehydratedView.firstChild = rNode; // We use `0` here, since this is the slot (right after the HEADER_OFFSET) // where a component LView or an LContainer is located in a root LView. setSegmentHead(dehydratedView, 0, rNode.nextSibling); } if (remainingNgh) { // If we have only used one of the ngh ids, store the remaining one // back on this RNode. rNode.setAttribute(NGH_ATTR_NAME, remainingNgh); } else { // The `ngh` attribute is cleared from the DOM node now // that the data has been retrieved for all indices. rNode.removeAttribute(NGH_ATTR_NAME); } // Note: don't check whether this node was claimed for hydration, // because this node might've been previously claimed while processing // template instructions. ngDevMode && markRNodeAsClaimedByHydration(rNode, /* checkIfAlreadyClaimed */ false); ngDevMode && ngDevMode.hydratedComponents++; return dehydratedView; } /** * Sets the implementation for the `retrieveHydrationInfo` function. */ export function enableRetrieveHydrationInfoImpl() { _retrieveHydrationInfoImpl = retrieveHydrationInfoImpl; }
{ "end_byte": 8034, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/utils.ts" }
angular/packages/core/src/hydration/utils.ts_8036_15926
/** * Retrieves hydration info by reading the value from the `ngh` attribute * and accessing a corresponding slot in TransferState storage. */ export function retrieveHydrationInfo( rNode: RElement, injector: Injector, isRootView = false, ): DehydratedView | null { return _retrieveHydrationInfoImpl(rNode, injector, isRootView); } /** * Retrieves the necessary object from a given ViewRef to serialize: * - an LView for component views * - an LContainer for cases when component acts as a ViewContainerRef anchor * - `null` in case of an embedded view */ export function getLNodeForHydration(viewRef: ViewRef): LView | LContainer | null { // Reading an internal field from `ViewRef` instance. let lView = (viewRef as any)._lView as LView; const tView = lView[TVIEW]; // A registered ViewRef might represent an instance of an // embedded view, in which case we do not need to annotate it. if (tView.type === TViewType.Embedded) { return null; } // Check if it's a root view and if so, retrieve component's // LView from the first slot after the header. if (isRootView(lView)) { lView = lView[HEADER_OFFSET]; } return lView; } function getTextNodeContent(node: Node): string | undefined { return node.textContent?.replace(/\s/gm, ''); } /** * Restores text nodes and separators into the DOM that were lost during SSR * serialization. The hydration process replaces empty text nodes and text * nodes that are immediately adjacent to other text nodes with comment nodes * that this method filters on to restore those missing nodes that the * hydration process is expecting to be present. * * @param node The app's root HTML Element */ export function processTextNodeMarkersBeforeHydration(node: HTMLElement) { const doc = getDocument(); const commentNodesIterator = doc.createNodeIterator(node, NodeFilter.SHOW_COMMENT, { acceptNode(node) { const content = getTextNodeContent(node); const isTextNodeMarker = content === TextNodeMarker.EmptyNode || content === TextNodeMarker.Separator; return isTextNodeMarker ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; }, }); let currentNode: Comment; // We cannot modify the DOM while using the commentIterator, // because it throws off the iterator state. // So we collect all marker nodes first and then follow up with // applying the changes to the DOM: either inserting an empty node // or just removing the marker if it was used as a separator. const nodes = []; while ((currentNode = commentNodesIterator.nextNode() as Comment)) { nodes.push(currentNode); } for (const node of nodes) { if (node.textContent === TextNodeMarker.EmptyNode) { node.replaceWith(doc.createTextNode('')); } else { node.remove(); } } } /** * Internal type that represents a claimed node. * Only used in dev mode. */ export enum HydrationStatus { Hydrated = 'hydrated', Skipped = 'skipped', Mismatched = 'mismatched', } export type HydrationInfo = | { status: HydrationStatus.Hydrated | HydrationStatus.Skipped; } | { status: HydrationStatus.Mismatched; actualNodeDetails: string | null; expectedNodeDetails: string | null; }; const HYDRATION_INFO_KEY = '__ngDebugHydrationInfo__'; export type HydratedNode = { [HYDRATION_INFO_KEY]?: HydrationInfo; }; function patchHydrationInfo(node: RNode, info: HydrationInfo) { (node as HydratedNode)[HYDRATION_INFO_KEY] = info; } export function readHydrationInfo(node: RNode): HydrationInfo | null { return (node as HydratedNode)[HYDRATION_INFO_KEY] ?? null; } /** * Marks a node as "claimed" by hydration process. * This is needed to make assessments in tests whether * the hydration process handled all nodes. */ export function markRNodeAsClaimedByHydration(node: RNode, checkIfAlreadyClaimed = true) { if (!ngDevMode) { throw new Error( 'Calling `markRNodeAsClaimedByHydration` in prod mode ' + 'is not supported and likely a mistake.', ); } if (checkIfAlreadyClaimed && isRNodeClaimedForHydration(node)) { throw new Error('Trying to claim a node, which was claimed already.'); } patchHydrationInfo(node, {status: HydrationStatus.Hydrated}); ngDevMode.hydratedNodes++; } export function markRNodeAsSkippedByHydration(node: RNode) { if (!ngDevMode) { throw new Error( 'Calling `markRNodeAsSkippedByHydration` in prod mode ' + 'is not supported and likely a mistake.', ); } patchHydrationInfo(node, {status: HydrationStatus.Skipped}); ngDevMode.componentsSkippedHydration++; } export function markRNodeAsHavingHydrationMismatch( node: RNode, expectedNodeDetails: string | null = null, actualNodeDetails: string | null = null, ) { if (!ngDevMode) { throw new Error( 'Calling `markRNodeAsMismatchedByHydration` in prod mode ' + 'is not supported and likely a mistake.', ); } // The RNode can be a standard HTMLElement (not an Angular component or directive) // The devtools component tree only displays Angular components & directives // Therefore we attach the debug info to the closest component/directive while (node && !getComponent(node as Element)) { node = node?.parentNode as RNode; } if (node) { patchHydrationInfo(node, { status: HydrationStatus.Mismatched, expectedNodeDetails, actualNodeDetails, }); } } export function isRNodeClaimedForHydration(node: RNode): boolean { return readHydrationInfo(node)?.status === HydrationStatus.Hydrated; } export function setSegmentHead( hydrationInfo: DehydratedView, index: number, node: RNode | null, ): void { hydrationInfo.segmentHeads ??= {}; hydrationInfo.segmentHeads[index] = node; } export function getSegmentHead(hydrationInfo: DehydratedView, index: number): RNode | null { return hydrationInfo.segmentHeads?.[index] ?? null; } export function isIncrementalHydrationEnabled(injector: Injector): boolean { return injector.get(IS_INCREMENTAL_HYDRATION_ENABLED, false, { optional: true, }); } /** * Returns the size of an <ng-container>, using either the information * serialized in `ELEMENT_CONTAINERS` (element container size) or by * computing the sum of root nodes in all dehydrated views in a given * container (in case this `<ng-container>` was also used as a view * container host node, e.g. <ng-container *ngIf>). */ export function getNgContainerSize(hydrationInfo: DehydratedView, index: number): number | null { const data = hydrationInfo.data; let size = data[ELEMENT_CONTAINERS]?.[index] ?? null; // If there is no serialized information available in the `ELEMENT_CONTAINERS` slot, // check if we have info about view containers at this location (e.g. // `<ng-container *ngIf>`) and use container size as a number of root nodes in this // element container. if (size === null && data[CONTAINERS]?.[index]) { size = calcSerializedContainerSize(hydrationInfo, index); } return size; } export function isSerializedElementContainer( hydrationInfo: DehydratedView, index: number, ): boolean { return hydrationInfo.data[ELEMENT_CONTAINERS]?.[index] !== undefined; } export function getSerializedContainerViews( hydrationInfo: DehydratedView, index: number, ): SerializedContainerView[] | null { return hydrationInfo.data[CONTAINERS]?.[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. */ export function calcSerializedContainerSize(hydrationInfo: DehydratedView, index: number): number { const views = getSerializedContainerViews(hydrationInfo, index) ?? []; let numNodes = 0; for (let view of views) { numNodes += view[NUM_ROOT_NODES] * (view[MULTIPLIER] ?? 1); } return numNodes; }
{ "end_byte": 15926, "start_byte": 8036, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/utils.ts" }
angular/packages/core/src/hydration/utils.ts_15928_19845
/** * Attempt to initialize the `disconnectedNodes` field of the given * `DehydratedView`. Returns the initialized value. */ export function initDisconnectedNodes(hydrationInfo: DehydratedView): Set<number> | null { // Check if we are processing disconnected info for the first time. if (typeof hydrationInfo.disconnectedNodes === 'undefined') { const nodeIds = hydrationInfo.data[DISCONNECTED_NODES]; hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null; } return hydrationInfo.disconnectedNodes; } /** * Checks whether a node is annotated as "disconnected", i.e. not present * in the DOM at serialization time. We should not attempt hydration for * such nodes and instead, use a regular "creation mode". */ export function isDisconnectedNode(hydrationInfo: DehydratedView, index: number): boolean { // Check if we are processing disconnected info for the first time. if (typeof hydrationInfo.disconnectedNodes === 'undefined') { const nodeIds = hydrationInfo.data[DISCONNECTED_NODES]; hydrationInfo.disconnectedNodes = nodeIds ? new Set(nodeIds) : null; } return !!initDisconnectedNodes(hydrationInfo)?.has(index); } /** * Helper function to prepare text nodes for serialization by ensuring * that seperate logical text blocks in the DOM remain separate after * serialization. */ export function processTextNodeBeforeSerialization(context: HydrationContext, node: RNode) { // Handle cases where text nodes can be lost after DOM serialization: // 1. When there is an *empty text node* in DOM: in this case, this // node would not make it into the serialized string and as a result, // this node wouldn't be created in a browser. This would result in // a mismatch during the hydration, where the runtime logic would expect // a text node to be present in live DOM, but no text node would exist. // Example: `<span>{{ name }}</span>` when the `name` is an empty string. // This would result in `<span></span>` string after serialization and // in a browser only the `span` element would be created. To resolve that, // an extra comment node is appended in place of an empty text node and // that special comment node is replaced with an empty text node *before* // hydration. // 2. When there are 2 consecutive text nodes present in the DOM. // Example: `<div>Hello <ng-container *ngIf="true">world</ng-container></div>`. // In this scenario, the live DOM would look like this: // <div>#text('Hello ') #text('world') #comment('container')</div> // Serialized string would look like this: `<div>Hello world<!--container--></div>`. // The live DOM in a browser after that would be: // <div>#text('Hello world') #comment('container')</div> // Notice how 2 text nodes are now "merged" into one. This would cause hydration // logic to fail, since it'd expect 2 text nodes being present, not one. // To fix this, we insert a special comment node in between those text nodes, so // serialized representation is: `<div>Hello <!--ngtns-->world<!--container--></div>`. // This forces browser to create 2 text nodes separated by a comment node. // Before running a hydration process, this special comment node is removed, so the // live DOM has exactly the same state as it was before serialization. // Collect this node as required special annotation only when its // contents is empty. Otherwise, such text node would be present on // the client after server-side rendering and no special handling needed. const el = node as HTMLElement; const corruptedTextNodes = context.corruptedTextNodes; if (el.textContent === '') { corruptedTextNodes.set(el, TextNodeMarker.EmptyNode); } else if (el.nextSibling?.nodeType === Node.TEXT_NODE) { corruptedTextNodes.set(el, TextNodeMarker.Separator); } }
{ "end_byte": 19845, "start_byte": 15928, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/utils.ts" }
angular/packages/core/src/hydration/api.ts_0_7215
/** * @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 {APP_BOOTSTRAP_LISTENER, ApplicationRef, whenStable} from '../application/application_ref'; import {Console} from '../console'; import { ENVIRONMENT_INITIALIZER, EnvironmentProviders, Injector, makeEnvironmentProviders, Provider, } from '../di'; import {inject} from '../di/injector_compatibility'; import {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../errors'; import {enableLocateOrCreateContainerRefImpl} from '../linker/view_container_ref'; import {enableLocateOrCreateI18nNodeImpl} from '../render3/i18n/i18n_apply'; import {enableLocateOrCreateElementNodeImpl} from '../render3/instructions/element'; import {enableLocateOrCreateElementContainerNodeImpl} from '../render3/instructions/element_container'; import {enableApplyRootElementTransformImpl} from '../render3/instructions/shared'; import {enableLocateOrCreateContainerAnchorImpl} from '../render3/instructions/template'; import {enableLocateOrCreateTextNodeImpl} from '../render3/instructions/text'; import {getDocument} from '../render3/interfaces/document'; import {isPlatformBrowser} from '../render3/util/misc_utils'; import {TransferState} from '../transfer_state'; import {performanceMarkFeature} from '../util/performance'; import {NgZone} from '../zone'; import {appendDeferBlocksToJSActionMap, withEventReplay} from './event_replay'; import {cleanupDehydratedViews} from './cleanup'; import { enableClaimDehydratedIcuCaseImpl, enablePrepareI18nBlockForHydrationImpl, setIsI18nHydrationSupportEnabled, } from './i18n'; import { IS_HYDRATION_DOM_REUSE_ENABLED, IS_I18N_HYDRATION_ENABLED, IS_INCREMENTAL_HYDRATION_ENABLED, PRESERVE_HOST_CONTENT, } from './tokens'; import {enableRetrieveHydrationInfoImpl, NGH_DATA_KEY, SSR_CONTENT_INTEGRITY_MARKER} from './utils'; import {enableFindMatchingDehydratedViewImpl} from './views'; import {bootstrapIncrementalHydration, enableRetrieveDeferBlockDataImpl} from './incremental'; /** * Indicates whether the hydration-related code was added, * prevents adding it multiple times. */ let isHydrationSupportEnabled = false; /** * Indicates whether the i18n-related code was added, * prevents adding it multiple times. * * Note: This merely controls whether the code is loaded, * while `setIsI18nHydrationSupportEnabled` determines * whether i18n blocks are serialized or hydrated. */ let isI18nHydrationRuntimeSupportEnabled = false; /** * Indicates whether the incremental hydration code was added, * prevents adding it multiple times. */ let isIncrementalHydrationRuntimeSupportEnabled = false; /** * Defines a period of time that Angular waits for the `ApplicationRef.isStable` to emit `true`. * If there was no event with the `true` value during this time, Angular reports a warning. */ const APPLICATION_IS_STABLE_TIMEOUT = 10_000; /** * Brings the necessary hydration code in tree-shakable manner. * The code is only present when the `provideClientHydration` is * invoked. Otherwise, this code is tree-shaken away during the * build optimization step. * * This technique allows us to swap implementations of methods so * tree shaking works appropriately when hydration is disabled or * enabled. It brings in the appropriate version of the method that * supports hydration only when enabled. */ function enableHydrationRuntimeSupport() { if (!isHydrationSupportEnabled) { isHydrationSupportEnabled = true; enableRetrieveHydrationInfoImpl(); enableLocateOrCreateElementNodeImpl(); enableLocateOrCreateTextNodeImpl(); enableLocateOrCreateElementContainerNodeImpl(); enableLocateOrCreateContainerAnchorImpl(); enableLocateOrCreateContainerRefImpl(); enableFindMatchingDehydratedViewImpl(); enableApplyRootElementTransformImpl(); } } /** * Brings the necessary i18n hydration code in tree-shakable manner. * Similar to `enableHydrationRuntimeSupport`, the code is only * present when `withI18nSupport` is invoked. */ function enableI18nHydrationRuntimeSupport() { if (!isI18nHydrationRuntimeSupportEnabled) { isI18nHydrationRuntimeSupportEnabled = true; enableLocateOrCreateI18nNodeImpl(); enablePrepareI18nBlockForHydrationImpl(); enableClaimDehydratedIcuCaseImpl(); } } /** * Brings the necessary incremental hydration code in tree-shakable manner. * Similar to `enableHydrationRuntimeSupport`, the code is only * present when `enableIncrementalHydrationRuntimeSupport` is invoked. */ function enableIncrementalHydrationRuntimeSupport() { if (!isIncrementalHydrationRuntimeSupportEnabled) { isIncrementalHydrationRuntimeSupportEnabled = true; enableRetrieveDeferBlockDataImpl(); } } /** * Outputs a message with hydration stats into a console. */ function printHydrationStats(injector: Injector) { const console = injector.get(Console); const message = `Angular hydrated ${ngDevMode!.hydratedComponents} component(s) ` + `and ${ngDevMode!.hydratedNodes} node(s), ` + `${ngDevMode!.componentsSkippedHydration} component(s) were skipped. ` + `Learn more at https://angular.dev/guide/hydration.`; // tslint:disable-next-line:no-console console.log(message); } /** * Returns a Promise that is resolved when an application becomes stable. */ function whenStableWithTimeout(appRef: ApplicationRef, injector: Injector): Promise<void> { const whenStablePromise = whenStable(appRef); if (typeof ngDevMode !== 'undefined' && ngDevMode) { const timeoutTime = APPLICATION_IS_STABLE_TIMEOUT; const console = injector.get(Console); const ngZone = injector.get(NgZone); // The following call should not and does not prevent the app to become stable // We cannot use RxJS timer here because the app would remain unstable. // This also avoids an extra change detection cycle. const timeoutId = ngZone.runOutsideAngular(() => { return setTimeout(() => logWarningOnStableTimedout(timeoutTime, console), timeoutTime); }); whenStablePromise.finally(() => clearTimeout(timeoutId)); } return whenStablePromise; } /** * Defines a name of an attribute that is added to the <body> tag * in the `index.html` file in case a given route was configured * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode". */ export const CLIENT_RENDER_MODE_FLAG = 'ngcm'; /** * Checks whether the `RenderMode.Client` was defined for the current route. */ function isClientRenderModeEnabled(): boolean { const doc = getDocument(); return isPlatformBrowser() && doc.body.hasAttribute(CLIENT_RENDER_MODE_FLAG); } /** * Returns a set of providers required to setup hydration support * for an application that is server side rendered. This function is * included into the `provideClientHydration` public API function from * the `platform-browser` package. * * The function sets up an internal flag that would be recognized during * the server side rendering time as well, so there is no need to * configure or change anything in NgUniversal to enable the feature. */
{ "end_byte": 7215, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/api.ts" }
angular/packages/core/src/hydration/api.ts_7216_14551
export function withDomHydration(): EnvironmentProviders { return makeEnvironmentProviders([ { provide: IS_HYDRATION_DOM_REUSE_ENABLED, useFactory: () => { let isEnabled = true; if (isPlatformBrowser()) { // On the client, verify that the server response contains // hydration annotations. Otherwise, keep hydration disabled. const transferState = inject(TransferState, {optional: true}); isEnabled = !!transferState?.get(NGH_DATA_KEY, null); } if (isEnabled) { performanceMarkFeature('NgHydration'); } return isEnabled; }, }, { provide: ENVIRONMENT_INITIALIZER, useValue: () => { // i18n support is enabled by calling withI18nSupport(), but there's // no way to turn it off (e.g. for tests), so we turn it off by default. setIsI18nHydrationSupportEnabled(false); if (!isPlatformBrowser()) { // Since this function is used across both server and client, // make sure that the runtime code is only added when invoked // on the client (see the `enableHydrationRuntimeSupport` function // call below). return; } if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) { verifySsrContentsIntegrity(); enableHydrationRuntimeSupport(); } else if (typeof ngDevMode !== 'undefined' && ngDevMode && !isClientRenderModeEnabled()) { const console = inject(Console); const message = formatRuntimeError( RuntimeErrorCode.MISSING_HYDRATION_ANNOTATIONS, 'Angular hydration was requested on the client, but there was no ' + 'serialized information present in the server response, ' + 'thus hydration was not enabled. ' + 'Make sure the `provideClientHydration()` is included into the list ' + 'of providers in the server part of the application configuration.', ); // tslint:disable-next-line:no-console console.warn(message); } }, multi: true, }, { provide: PRESERVE_HOST_CONTENT, useFactory: () => { // Preserve host element content only in a browser // environment and when hydration is configured properly. // On a server, an application is rendered from scratch, // so the host content needs to be empty. return isPlatformBrowser() && inject(IS_HYDRATION_DOM_REUSE_ENABLED); }, }, { provide: APP_BOOTSTRAP_LISTENER, useFactory: () => { if (isPlatformBrowser() && inject(IS_HYDRATION_DOM_REUSE_ENABLED)) { const appRef = inject(ApplicationRef); const injector = inject(Injector); return () => { // Wait until an app becomes stable and cleanup all views that // were not claimed during the application bootstrap process. // The timing is similar to when we start the serialization process // on the server. // // Note: the cleanup task *MUST* be scheduled within the Angular zone in Zone apps // to ensure that change detection is properly run afterward. whenStableWithTimeout(appRef, injector).then(() => { cleanupDehydratedViews(appRef); if (typeof ngDevMode !== 'undefined' && ngDevMode) { printHydrationStats(injector); } }); }; } return () => {}; // noop }, multi: true, }, ]); } /** * Returns a set of providers required to setup support for i18n hydration. * Requires hydration to be enabled separately. */ export function withI18nSupport(): Provider[] { return [ { provide: IS_I18N_HYDRATION_ENABLED, useFactory: () => inject(IS_HYDRATION_DOM_REUSE_ENABLED), }, { provide: ENVIRONMENT_INITIALIZER, useValue: () => { if (inject(IS_HYDRATION_DOM_REUSE_ENABLED)) { enableI18nHydrationRuntimeSupport(); setIsI18nHydrationSupportEnabled(true); performanceMarkFeature('NgI18nHydration'); } }, multi: true, }, ]; } /** * Returns a set of providers required to setup support for incremental hydration. * Requires hydration to be enabled separately. * Enabling incremental hydration also enables event replay for the entire app. * * @developerPreview */ export function withIncrementalHydration(): Provider[] { return [ withEventReplay(), { provide: IS_INCREMENTAL_HYDRATION_ENABLED, useValue: true, }, { provide: ENVIRONMENT_INITIALIZER, useValue: () => { enableIncrementalHydrationRuntimeSupport(); }, multi: true, }, { provide: APP_BOOTSTRAP_LISTENER, useFactory: () => { if (isPlatformBrowser()) { const injector = inject(Injector); const doc = getDocument(); return () => { bootstrapIncrementalHydration(doc, injector); appendDeferBlocksToJSActionMap(doc, injector); }; } return () => {}; // noop for the server code }, multi: true, }, ]; } /** * * @param time The time in ms until the stable timedout warning message is logged */ function logWarningOnStableTimedout(time: number, console: Console): void { const message = `Angular hydration expected the ApplicationRef.isStable() to emit \`true\`, but it ` + `didn't happen within ${time}ms. Angular hydration logic depends on the application becoming stable ` + `as a signal to complete hydration process.`; console.warn(formatRuntimeError(RuntimeErrorCode.HYDRATION_STABLE_TIMEDOUT, message)); } /** * Verifies whether the DOM contains a special marker added during SSR time to make sure * there is no SSR'ed contents transformations happen after SSR is completed. Typically that * happens either by CDN or during the build process as an optimization to remove comment nodes. * Hydration process requires comment nodes produced by Angular to locate correct DOM segments. * When this special marker is *not* present - throw an error and do not proceed with hydration, * since it will not be able to function correctly. * * Note: this function is invoked only on the client, so it's safe to use DOM APIs. */ function verifySsrContentsIntegrity(): void { const doc = getDocument(); let hydrationMarker: Node | undefined; for (const node of doc.body.childNodes) { if ( node.nodeType === Node.COMMENT_NODE && node.textContent?.trim() === SSR_CONTENT_INTEGRITY_MARKER ) { hydrationMarker = node; break; } } if (!hydrationMarker) { throw new RuntimeError( RuntimeErrorCode.MISSING_SSR_CONTENT_INTEGRITY_MARKER, typeof ngDevMode !== 'undefined' && ngDevMode && 'Angular hydration logic detected that HTML content of this page was modified after it ' + 'was produced during server side rendering. Make sure that there are no optimizations ' + 'that remove comment nodes from HTML enabled on your CDN. Angular hydration ' + 'relies on HTML produced by the server, including whitespaces and comment nodes.', ); } }
{ "end_byte": 14551, "start_byte": 7216, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/api.ts" }
angular/packages/core/src/hydration/error_handling.ts_0_7952
/** * @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 {RuntimeError, RuntimeErrorCode} from '../errors'; import {getDeclarationComponentDef} from '../render3/instructions/element_validation'; import {TNode, TNodeType} from '../render3/interfaces/node'; import {RNode} from '../render3/interfaces/renderer_dom'; import {HOST, LView, TVIEW} from '../render3/interfaces/view'; import {getParentRElement} from '../render3/node_manipulation'; import {unwrapRNode} from '../render3/util/view_utils'; import {markRNodeAsHavingHydrationMismatch} from './utils'; const AT_THIS_LOCATION = '<-- AT THIS LOCATION'; /** * Retrieves a user friendly string for a given TNodeType for use in * friendly error messages * * @param tNodeType * @returns */ function getFriendlyStringFromTNodeType(tNodeType: TNodeType): string { switch (tNodeType) { case TNodeType.Container: return 'view container'; case TNodeType.Element: return 'element'; case TNodeType.ElementContainer: return 'ng-container'; case TNodeType.Icu: return 'icu'; case TNodeType.Placeholder: return 'i18n'; case TNodeType.Projection: return 'projection'; case TNodeType.Text: return 'text'; case TNodeType.LetDeclaration: return '@let'; default: // This should not happen as we cover all possible TNode types above. return '<unknown>'; } } /** * Validates that provided nodes match during the hydration process. */ export function validateMatchingNode( node: RNode | null, nodeType: number, tagName: string | null, lView: LView, tNode: TNode, isViewContainerAnchor = false, ): void { if ( !node || (node as Node).nodeType !== nodeType || ((node as Node).nodeType === Node.ELEMENT_NODE && (node as HTMLElement).tagName.toLowerCase() !== tagName?.toLowerCase()) ) { const expectedNode = shortRNodeDescription(nodeType, tagName, null); let header = `During hydration Angular expected ${expectedNode} but `; const hostComponentDef = getDeclarationComponentDef(lView); const componentClassName = hostComponentDef?.type?.name; const expectedDom = describeExpectedDom(lView, tNode, isViewContainerAnchor); const expected = `Angular expected this DOM:\n\n${expectedDom}\n\n`; let actual = ''; const componentHostElement = unwrapRNode(lView[HOST]!); if (!node) { // No node found during hydration. header += `the node was not found.\n\n`; // Since the node is missing, we use the closest node to attach the error to markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom); } else { const actualNode = shortRNodeDescription( (node as Node).nodeType, (node as HTMLElement).tagName ?? null, (node as HTMLElement).textContent ?? null, ); header += `found ${actualNode}.\n\n`; const actualDom = describeDomFromNode(node); actual = `Actual DOM is:\n\n${actualDom}\n\n`; // DevTools only report hydration issues on the component level, so we attach extra debug // info to a component host element to make it available to DevTools. markRNodeAsHavingHydrationMismatch(componentHostElement, expectedDom, actualDom); } const footer = getHydrationErrorFooter(componentClassName); const message = header + expected + actual + getHydrationAttributeNote() + footer; throw new RuntimeError(RuntimeErrorCode.HYDRATION_NODE_MISMATCH, message); } } /** * Validates that a given node has sibling nodes */ export function validateSiblingNodeExists(node: RNode | null): void { validateNodeExists(node); if (!node!.nextSibling) { const header = 'During hydration Angular expected more sibling nodes to be present.\n\n'; const actual = `Actual DOM is:\n\n${describeDomFromNode(node!)}\n\n`; const footer = getHydrationErrorFooter(); const message = header + actual + footer; markRNodeAsHavingHydrationMismatch(node!, '', actual); throw new RuntimeError(RuntimeErrorCode.HYDRATION_MISSING_SIBLINGS, message); } } /** * Validates that a node exists or throws */ export function validateNodeExists( node: RNode | null, lView: LView | null = null, tNode: TNode | null = null, ): void { if (!node) { const header = 'During hydration, Angular expected an element to be present at this location.\n\n'; let expected = ''; let footer = ''; if (lView !== null && tNode !== null) { expected = describeExpectedDom(lView, tNode, false); footer = getHydrationErrorFooter(); // Since the node is missing, we use the closest node to attach the error to markRNodeAsHavingHydrationMismatch(unwrapRNode(lView[HOST]!), expected, ''); } throw new RuntimeError( RuntimeErrorCode.HYDRATION_MISSING_NODE, `${header}${expected}\n\n${footer}`, ); } } /** * Builds the hydration error message when a node is not found * * @param lView the LView where the node exists * @param tNode the TNode */ export function nodeNotFoundError(lView: LView, tNode: TNode): Error { const header = 'During serialization, Angular was unable to find an element in the DOM:\n\n'; const expected = `${describeExpectedDom(lView, tNode, false)}\n\n`; const footer = getHydrationErrorFooter(); throw new RuntimeError(RuntimeErrorCode.HYDRATION_MISSING_NODE, header + expected + footer); } /** * Builds a hydration error message when a node is not found at a path location * * @param host the Host Node * @param path the path to the node */ export function nodeNotFoundAtPathError(host: Node, path: string): Error { const header = `During hydration Angular was unable to locate a node ` + `using the "${path}" path, starting from the ${describeRNode(host)} node.\n\n`; const footer = getHydrationErrorFooter(); markRNodeAsHavingHydrationMismatch(host); throw new RuntimeError(RuntimeErrorCode.HYDRATION_MISSING_NODE, header + footer); } /** * Builds the hydration error message in the case that dom nodes are created outside of * the Angular context and are being used as projected nodes * * @param lView the LView * @param tNode the TNode * @returns an error */ export function unsupportedProjectionOfDomNodes(rNode: RNode): Error { const header = 'During serialization, Angular detected DOM nodes ' + 'that were created outside of Angular context and provided as projectable nodes ' + '(likely via `ViewContainerRef.createComponent` or `createComponent` APIs). ' + 'Hydration is not supported for such cases, consider refactoring the code to avoid ' + 'this pattern or using `ngSkipHydration` on the host element of the component.\n\n'; const actual = `${describeDomFromNode(rNode)}\n\n`; const message = header + actual + getHydrationAttributeNote(); return new RuntimeError(RuntimeErrorCode.UNSUPPORTED_PROJECTION_DOM_NODES, message); } /** * Builds the hydration error message in the case that ngSkipHydration was used on a * node that is not a component host element or host binding * * @param rNode the HTML Element * @returns an error */ export function invalidSkipHydrationHost(rNode: RNode): Error { const header = 'The `ngSkipHydration` flag is applied on a node ' + "that doesn't act as a component host. Hydration can be " + 'skipped only on per-component basis.\n\n'; const actual = `${describeDomFromNode(rNode)}\n\n`; const footer = 'Please move the `ngSkipHydration` attribute to the component host element.\n\n'; const message = header + actual + footer; return new RuntimeError(RuntimeErrorCode.INVALID_SKIP_HYDRATION_HOST, message); } // Stringification methods /** * Stringifies a given TNode's attributes * * @param tNode a provided TNode * @returns string */
{ "end_byte": 7952, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/error_handling.ts" }
angular/packages/core/src/hydration/error_handling.ts_7953_14858
function stringifyTNodeAttrs(tNode: TNode): string { const results = []; if (tNode.attrs) { for (let i = 0; i < tNode.attrs.length; ) { const attrName = tNode.attrs[i++]; // Once we reach the first flag, we know that the list of // attributes is over. if (typeof attrName == 'number') { break; } const attrValue = tNode.attrs[i++]; results.push(`${attrName}="${shorten(attrValue as string)}"`); } } return results.join(' '); } /** * The list of internal attributes that should be filtered out while * producing an error message. */ const internalAttrs = new Set(['ngh', 'ng-version', 'ng-server-context']); /** * Stringifies an HTML Element's attributes * * @param rNode an HTML Element * @returns string */ function stringifyRNodeAttrs(rNode: HTMLElement): string { const results = []; for (let i = 0; i < rNode.attributes.length; i++) { const attr = rNode.attributes[i]; if (internalAttrs.has(attr.name)) continue; results.push(`${attr.name}="${shorten(attr.value)}"`); } return results.join(' '); } // Methods for Describing the DOM /** * Converts a tNode to a helpful readable string value for use in error messages * * @param tNode a given TNode * @param innerContent the content of the node * @returns string */ function describeTNode(tNode: TNode, innerContent: string = '…'): string { switch (tNode.type) { case TNodeType.Text: const content = tNode.value ? `(${tNode.value})` : ''; return `#text${content}`; case TNodeType.Element: const attrs = stringifyTNodeAttrs(tNode); const tag = tNode.value.toLowerCase(); return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`; case TNodeType.ElementContainer: return '<!-- ng-container -->'; case TNodeType.Container: return '<!-- container -->'; default: const typeAsString = getFriendlyStringFromTNodeType(tNode.type); return `#node(${typeAsString})`; } } /** * Converts an RNode to a helpful readable string value for use in error messages * * @param rNode a given RNode * @param innerContent the content of the node * @returns string */ function describeRNode(rNode: RNode, innerContent: string = '…'): string { const node = rNode as HTMLElement; switch (node.nodeType) { case Node.ELEMENT_NODE: const tag = node.tagName!.toLowerCase(); const attrs = stringifyRNodeAttrs(node); return `<${tag}${attrs ? ' ' + attrs : ''}>${innerContent}</${tag}>`; case Node.TEXT_NODE: const content = node.textContent ? shorten(node.textContent) : ''; return `#text${content ? `(${content})` : ''}`; case Node.COMMENT_NODE: return `<!-- ${shorten(node.textContent ?? '')} -->`; default: return `#node(${node.nodeType})`; } } /** * Builds the string containing the expected DOM present given the LView and TNode * values for a readable error message * * @param lView the lView containing the DOM * @param tNode the tNode * @param isViewContainerAnchor boolean * @returns string */ function describeExpectedDom(lView: LView, tNode: TNode, isViewContainerAnchor: boolean): string { const spacer = ' '; let content = ''; if (tNode.prev) { content += spacer + '…\n'; content += spacer + describeTNode(tNode.prev) + '\n'; } else if (tNode.type && tNode.type & TNodeType.AnyContainer) { content += spacer + '…\n'; } if (isViewContainerAnchor) { content += spacer + describeTNode(tNode) + '\n'; content += spacer + `<!-- container --> ${AT_THIS_LOCATION}\n`; } else { content += spacer + describeTNode(tNode) + ` ${AT_THIS_LOCATION}\n`; } content += spacer + '…\n'; const parentRNode = tNode.type ? getParentRElement(lView[TVIEW], tNode, lView) : null; if (parentRNode) { content = describeRNode(parentRNode as unknown as Node, '\n' + content); } return content; } /** * Builds the string containing the DOM present around a given RNode for a * readable error message * * @param node the RNode * @returns string */ function describeDomFromNode(node: RNode): string { const spacer = ' '; let content = ''; const currentNode = node as HTMLElement; if (currentNode.previousSibling) { content += spacer + '…\n'; content += spacer + describeRNode(currentNode.previousSibling) + '\n'; } content += spacer + describeRNode(currentNode) + ` ${AT_THIS_LOCATION}\n`; if (node.nextSibling) { content += spacer + '…\n'; } if (node.parentNode) { content = describeRNode(currentNode.parentNode as Node, '\n' + content); } return content; } /** * Shortens the description of a given RNode by its type for readability * * @param nodeType the type of node * @param tagName the node tag name * @param textContent the text content in the node * @returns string */ function shortRNodeDescription( nodeType: number, tagName: string | null, textContent: string | null, ): string { switch (nodeType) { case Node.ELEMENT_NODE: return `<${tagName!.toLowerCase()}>`; case Node.TEXT_NODE: const content = textContent ? ` (with the "${shorten(textContent)}" content)` : ''; return `a text node${content}`; case Node.COMMENT_NODE: return 'a comment node'; default: return `#node(nodeType=${nodeType})`; } } /** * Builds the footer hydration error message * * @param componentClassName the name of the component class * @returns string */ function getHydrationErrorFooter(componentClassName?: string): string { const componentInfo = componentClassName ? `the "${componentClassName}"` : 'corresponding'; return ( `To fix this problem:\n` + ` * check ${componentInfo} component for hydration-related issues\n` + ` * check to see if your template has valid HTML structure\n` + ` * or skip hydration by adding the \`ngSkipHydration\` attribute ` + `to its host node in a template\n\n` ); } /** * An attribute related note for hydration errors */ function getHydrationAttributeNote(): string { return ( 'Note: attributes are only displayed to better represent the DOM' + ' but have no effect on hydration mismatches.\n\n' ); } // Node string utility functions /** * Strips all newlines out of a given string * * @param input a string to be cleared of new line characters * @returns */ function stripNewlines(input: string): string { return input.replace(/\s+/gm, ''); } /** * Reduces a string down to a maximum length of characters with ellipsis for readability * * @param input a string input * @param maxLength a maximum length in characters * @returns string */ function shorten(input: string | null, maxLength = 50): string { if (!input) { return ''; } input = stripNewlines(input); return input.length > maxLength ? `${input.substring(0, maxLength - 1)}…` : input; }
{ "end_byte": 14858, "start_byte": 7953, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/error_handling.ts" }
angular/packages/core/src/hydration/event_replay.ts_0_8303
/** * @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 { isEarlyEventType, isCaptureEventType, EventContractContainer, EventContract, EventDispatcher, registerDispatcher, getAppScopedQueuedEventInfos, clearAppScopedEarlyEventContract, EventPhase, } from '@angular/core/primitives/event-dispatch'; import {APP_BOOTSTRAP_LISTENER, ApplicationRef, whenStable} from '../application/application_ref'; import {ENVIRONMENT_INITIALIZER, Injector} from '../di'; import {inject} from '../di/injector_compatibility'; import {Provider} from '../di/interface/provider'; import {setStashFn} from '../render3/instructions/listener'; import {RElement} from '../render3/interfaces/renderer_dom'; import {CLEANUP, LView, TView} from '../render3/interfaces/view'; import {isPlatformBrowser} from '../render3/util/misc_utils'; import {unwrapRNode} from '../render3/util/view_utils'; import {BLOCK_ELEMENT_MAP, EVENT_REPLAY_ENABLED_DEFAULT, IS_EVENT_REPLAY_ENABLED} from './tokens'; import { sharedStashFunction, sharedMapFunction, DEFER_BLOCK_SSR_ID_ATTRIBUTE, EventContractDetails, JSACTION_EVENT_CONTRACT, removeListenersFromBlocks, } from '../event_delegation_utils'; import {APP_ID} from '../application/application_tokens'; import {performanceMarkFeature} from '../util/performance'; import {hydrateFromBlockName, findFirstHydratedParentDeferBlock} from './blocks'; import {DeferBlock, DeferBlockTrigger, HydrateTriggerDetails} from '../defer/interfaces'; import {triggerAndWaitForCompletion} from '../defer/instructions'; import {cleanupDehydratedViews, cleanupLContainer} from './cleanup'; import {hoverEventNames, interactionEventNames} from '../defer/dom_triggers'; import {DeferBlockRegistry} from '../defer/registry'; /** Apps in which we've enabled event replay. * This is to prevent initializing event replay more than once per app. */ const appsWithEventReplay = new WeakSet<ApplicationRef>(); /** * A list of block events that need to be replayed */ let blockEventQueue: {event: Event; currentTarget: Element}[] = []; /** * Determines whether Event Replay feature should be activated on the client. */ function shouldEnableEventReplay(injector: Injector) { return injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT); } /** * Returns a set of providers required to setup support for event replay. * Requires hydration to be enabled separately. */ export function withEventReplay(): Provider[] { return [ { provide: IS_EVENT_REPLAY_ENABLED, useFactory: () => { let isEnabled = true; if (isPlatformBrowser()) { // Note: globalThis[CONTRACT_PROPERTY] may be undefined in case Event Replay feature // is enabled, but there are no events configured in this application, in which case // we don't activate this feature, since there are no events to replay. const appId = inject(APP_ID); isEnabled = !!window._ejsas?.[appId]; } if (isEnabled) { performanceMarkFeature('NgEventReplay'); } return isEnabled; }, }, { provide: ENVIRONMENT_INITIALIZER, useValue: () => { const injector = inject(Injector); // We have to check for the appRef here due to the possibility of multiple apps // being present on the same page. We only want to enable event replay for the // apps that actually want it. const appRef = injector.get(ApplicationRef); if (!appsWithEventReplay.has(appRef)) { const jsActionMap = inject(BLOCK_ELEMENT_MAP); if (isPlatformBrowser(injector) && shouldEnableEventReplay(injector)) { setStashFn((rEl: RElement, eventName: string, listenerFn: VoidFunction) => { sharedStashFunction(rEl, eventName, listenerFn); sharedMapFunction(rEl, jsActionMap); }); } } }, multi: true, }, { provide: APP_BOOTSTRAP_LISTENER, useFactory: () => { if (isPlatformBrowser()) { const injector = inject(Injector); const appRef = inject(ApplicationRef); return () => { if (!shouldEnableEventReplay(injector)) { return; } // We have to check for the appRef here due to the possibility of multiple apps // being present on the same page. We only want to enable event replay for the // apps that actually want it. if (!appsWithEventReplay.has(appRef)) { appsWithEventReplay.add(appRef); appRef.onDestroy(() => appsWithEventReplay.delete(appRef)); // Kick off event replay logic once hydration for the initial part // of the application is completed. This timing is similar to the unclaimed // dehydrated views cleanup timing. whenStable(appRef).then(() => { const eventContractDetails = injector.get(JSACTION_EVENT_CONTRACT); initEventReplay(eventContractDetails, injector); removeListenersFromBlocks([''], injector); }); } }; } return () => {}; // noop for the server code }, multi: true, }, ]; } const initEventReplay = (eventDelegation: EventContractDetails, injector: Injector) => { const appId = injector.get(APP_ID); // This is set in packages/platform-server/src/utils.ts const earlyJsactionData = window._ejsas![appId]!; const eventContract = (eventDelegation.instance = new EventContract( new EventContractContainer(earlyJsactionData.c), )); for (const et of earlyJsactionData.et) { eventContract.addEvent(et); } for (const et of earlyJsactionData.etc) { eventContract.addEvent(et); } const eventInfos = getAppScopedQueuedEventInfos(appId); eventContract.replayEarlyEventInfos(eventInfos); clearAppScopedEarlyEventContract(appId); const dispatcher = new EventDispatcher((event) => { invokeRegisteredReplayListeners(injector, event, event.currentTarget as Element); }); registerDispatcher(eventContract, dispatcher); }; /** * Extracts information about all DOM events (added in a template) registered on elements in a give * LView. Maps collected events to a corresponding DOM element (an element is used as a key). */ export function collectDomEventsInfo( tView: TView, lView: LView, eventTypesToReplay: {regular: Set<string>; capture: Set<string>}, ): Map<Element, string[]> { const domEventsInfo = new Map<Element, string[]>(); const lCleanup = lView[CLEANUP]; const tCleanup = tView.cleanup; if (!tCleanup || !lCleanup) { return domEventsInfo; } for (let i = 0; i < tCleanup.length; ) { const firstParam = tCleanup[i++]; const secondParam = tCleanup[i++]; if (typeof firstParam !== 'string') { continue; } const eventType = firstParam; if (!isEarlyEventType(eventType)) { continue; } if (isCaptureEventType(eventType)) { eventTypesToReplay.capture.add(eventType); } else { eventTypesToReplay.regular.add(eventType); } const listenerElement = unwrapRNode(lView[secondParam]) as any as Element; i++; // move the cursor to the next position (location of the listener idx) const useCaptureOrIndx = tCleanup[i++]; // if useCaptureOrIndx is boolean then report it as is. // if useCaptureOrIndx is positive number then it in unsubscribe method // if useCaptureOrIndx is negative number then it is a Subscription const isDomEvent = typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0; if (!isDomEvent) { continue; } if (!domEventsInfo.has(listenerElement)) { domEventsInfo.set(listenerElement, [eventType]); } else { domEventsInfo.get(listenerElement)!.push(eventType); } } return domEventsInfo; } function invokeListeners(event: Event, currentTarget: Element | null) { const handlerFns = currentTarget?.__jsaction_fns?.get(event.type); if (!handlerFns) { return; } for (const handler of handlerFns) { handler(event); } }
{ "end_byte": 8303, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/event_replay.ts" }
angular/packages/core/src/hydration/event_replay.ts_8305_11755
export function invokeRegisteredReplayListeners( injector: Injector, event: Event, currentTarget: Element | null, ) { const blockName = (currentTarget && currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE)) ?? ''; if (/d\d+/.test(blockName)) { hydrateAndInvokeBlockListeners(blockName, injector, event, currentTarget!); } else if (event.eventPhase === EventPhase.REPLAY) { invokeListeners(event, currentTarget); } } async function hydrateAndInvokeBlockListeners( blockName: string, injector: Injector, event: Event, currentTarget: Element, ) { blockEventQueue.push({event, currentTarget}); const {deferBlock, hydratedBlocks} = await hydrateFromBlockName( injector, blockName, fetchAndRenderDeferBlock, ); if (deferBlock !== null) { // TODO(incremental-hydration): extract this work into a post // hydration cleanup function const deferBlockRegistry = injector.get(DeferBlockRegistry); deferBlockRegistry.hydrating.delete(blockName); hydratedBlocks.add(blockName); const appRef = injector.get(ApplicationRef); await appRef.whenStable(); replayQueuedBlockEvents(hydratedBlocks, injector); cleanupLContainer(deferBlock.lContainer); } } export async function fetchAndRenderDeferBlock(deferBlock: DeferBlock): Promise<DeferBlock> { await triggerAndWaitForCompletion(deferBlock); return deferBlock; } function replayQueuedBlockEvents(hydratedBlocks: Set<string>, injector: Injector) { // clone the queue const queue = [...blockEventQueue]; // empty it blockEventQueue = []; for (let {event, currentTarget} of queue) { const blockName = currentTarget.getAttribute(DEFER_BLOCK_SSR_ID_ATTRIBUTE)!; if (hydratedBlocks.has(blockName)) { invokeListeners(event, currentTarget); } else { // requeue events that weren't yet hydrated blockEventQueue.push({event, currentTarget}); } } cleanupDehydratedViews(injector.get(ApplicationRef)); removeListenersFromBlocks([...hydratedBlocks], injector); } export function convertHydrateTriggersToJsAction( triggers: Map<DeferBlockTrigger, HydrateTriggerDetails | null> | null, ): string[] { let actionList: string[] = []; if (triggers !== null) { if (triggers.has(DeferBlockTrigger.Hover)) { actionList.push(...hoverEventNames); } if (triggers.has(DeferBlockTrigger.Interaction)) { actionList.push(...interactionEventNames); } } return actionList; } export function appendBlocksToJSActionMap(el: RElement, injector: Injector) { const jsActionMap = injector.get(BLOCK_ELEMENT_MAP); sharedMapFunction(el, jsActionMap); } function gatherDeferBlocksByJSActionAttribute(doc: Document): Set<HTMLElement> { const jsactionNodes = doc.body.querySelectorAll('[jsaction]'); const blockMap = new Set<HTMLElement>(); for (let node of jsactionNodes) { const attr = node.getAttribute('jsaction'); const blockId = node.getAttribute('ngb'); const eventTypes = [...hoverEventNames.join(':;'), ...interactionEventNames.join(':;')].join( '|', ); if (attr?.match(eventTypes) && blockId !== null) { blockMap.add(node as HTMLElement); } } return blockMap; } export function appendDeferBlocksToJSActionMap(doc: Document, injector: Injector) { const blockMap = gatherDeferBlocksByJSActionAttribute(doc); for (let rNode of blockMap) { appendBlocksToJSActionMap(rNode as RElement, injector); } }
{ "end_byte": 11755, "start_byte": 8305, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/event_replay.ts" }
angular/packages/core/src/hydration/annotate.ts_0_6367
/** * @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 {ApplicationRef} from '../application/application_ref'; import {APP_ID} from '../application/application_tokens'; import { DEFER_BLOCK_STATE as CURRENT_DEFER_BLOCK_STATE, DeferBlockTrigger, HydrateTriggerDetails, TDeferBlockDetails, } from '../defer/interfaces'; import {getLDeferBlockDetails, getTDeferBlockDetails, isDeferBlock} from '../defer/utils'; import {isDetachedByI18n} from '../i18n/utils'; import {ViewEncapsulation} from '../metadata'; import {Renderer2} from '../render'; import {assertTNode} from '../render3/assert'; import {collectNativeNodes, collectNativeNodesInLContainer} from '../render3/collect_native_nodes'; import {getComponentDef} from '../render3/def_getters'; import {CONTAINER_HEADER_OFFSET, LContainer} from '../render3/interfaces/container'; import {isLetDeclaration, isTNodeShape, TNode, TNodeType} from '../render3/interfaces/node'; import {RComment, RElement} from '../render3/interfaces/renderer_dom'; import { hasI18n, isComponentHost, isLContainer, isProjectionTNode, isRootView, } from '../render3/interfaces/type_checks'; import { CONTEXT, HEADER_OFFSET, HOST, INJECTOR, LView, PARENT, RENDERER, TView, TVIEW, TViewType, } from '../render3/interfaces/view'; import {unwrapLView, unwrapRNode} from '../render3/util/view_utils'; import {TransferState} from '../transfer_state'; import { unsupportedProjectionOfDomNodes, validateMatchingNode, validateNodeExists, } from './error_handling'; import {collectDomEventsInfo, convertHydrateTriggersToJsAction} from './event_replay'; import {setJSActionAttributes} from '../event_delegation_utils'; import { getOrComputeI18nChildren, isI18nHydrationEnabled, isI18nHydrationSupportEnabled, trySerializeI18nBlock, } from './i18n'; import { CONTAINERS, DEFER_BLOCK_ID, DEFER_BLOCK_STATE, DEFER_HYDRATE_TRIGGERS, DEFER_PARENT_BLOCK_ID, DISCONNECTED_NODES, ELEMENT_CONTAINERS, I18N_DATA, MULTIPLIER, NODES, NUM_ROOT_NODES, SerializedContainerView, SerializedDeferBlock, SerializedTriggerDetails, SerializedView, TEMPLATE_ID, TEMPLATES, } from './interfaces'; import {calcPathForNode, isDisconnectedNode} from './node_lookup_utils'; import {isInSkipHydrationBlock, SKIP_HYDRATION_ATTR_NAME} from './skip_hydration'; import {EVENT_REPLAY_ENABLED_DEFAULT, IS_EVENT_REPLAY_ENABLED} from './tokens'; import { getLNodeForHydration, isIncrementalHydrationEnabled, NGH_ATTR_NAME, NGH_DATA_KEY, NGH_DEFER_BLOCKS_KEY, processTextNodeBeforeSerialization, TextNodeMarker, } from './utils'; import {Injector} from '../di'; /** * A collection that tracks all serialized views (`ngh` DOM annotations) * to avoid duplication. An attempt to add a duplicate view results in the * collection returning the index of the previously collected serialized view. * This reduces the number of annotations needed for a given page. */ class SerializedViewCollection { private views: SerializedView[] = []; private indexByContent = new Map<string, number>(); add(serializedView: SerializedView): number { const viewAsString = JSON.stringify(serializedView); if (!this.indexByContent.has(viewAsString)) { const index = this.views.length; this.views.push(serializedView); this.indexByContent.set(viewAsString, index); return index; } return this.indexByContent.get(viewAsString)!; } getAll(): SerializedView[] { return this.views; } } /** * Global counter that is used to generate a unique id for TViews * during the serialization process. */ let tViewSsrId = 0; /** * Generates a unique id for a given TView and returns this id. * The id is also stored on this instance of a TView and reused in * subsequent calls. * * This id is needed to uniquely identify and pick up dehydrated views * at runtime. */ function getSsrId(tView: TView): string { if (!tView.ssrId) { tView.ssrId = `t${tViewSsrId++}`; } return tView.ssrId; } /** * Describes a context available during the serialization * process. The context is used to share and collect information * during the serialization. */ export interface HydrationContext { serializedViewCollection: SerializedViewCollection; corruptedTextNodes: Map<HTMLElement, TextNodeMarker>; isI18nHydrationEnabled: boolean; isIncrementalHydrationEnabled: boolean; i18nChildren: Map<TView, Set<number> | null>; eventTypesToReplay: {regular: Set<string>; capture: Set<string>}; shouldReplayEvents: boolean; appId: string; // the value of `APP_ID` deferBlocks: Map<string /* defer block id, e.g. `d0` */, SerializedDeferBlock>; } /** * Computes the number of root nodes in a given view * (or child nodes in a given container if a tNode is provided). */ function calcNumRootNodes(tView: TView, lView: LView, tNode: TNode | null): number { const rootNodes: unknown[] = []; collectNativeNodes(tView, lView, tNode, rootNodes); return rootNodes.length; } /** * Computes the number of root nodes in all views in a given LContainer. */ function calcNumRootNodesInLContainer(lContainer: LContainer): number { const rootNodes: unknown[] = []; collectNativeNodesInLContainer(lContainer, rootNodes); return rootNodes.length; } /** * Annotates root level component's LView for hydration, * see `annotateHostElementForHydration` for additional information. */ function annotateComponentLViewForHydration( lView: LView, context: HydrationContext, injector: Injector, ): number | null { const hostElement = lView[HOST]; // Root elements might also be annotated with the `ngSkipHydration` attribute, // check if it's present before starting the serialization process. if (hostElement && !(hostElement as HTMLElement).hasAttribute(SKIP_HYDRATION_ATTR_NAME)) { return annotateHostElementForHydration(hostElement as HTMLElement, lView, null, context); } return null; } /** * Annotates root level LContainer for hydration. This happens when a root component * injects ViewContainerRef, thus making the component an anchor for a view container. * This function serializes the component itself as well as all views from the view * container. */
{ "end_byte": 6367, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/annotate.ts_6368_11665
function annotateLContainerForHydration( lContainer: LContainer, context: HydrationContext, injector: Injector, ) { const componentLView = unwrapLView(lContainer[HOST]) as LView<unknown>; // Serialize the root component itself. const componentLViewNghIndex = annotateComponentLViewForHydration( componentLView, context, injector, ); if (componentLViewNghIndex === null) { // Component was not serialized (for example, if hydration was skipped by adding // the `ngSkipHydration` attribute or this component uses i18n blocks in the template, // but `withI18nSupport()` was not added), avoid annotating host element with the `ngh` // attribute. return; } const hostElement = unwrapRNode(componentLView[HOST]!) as HTMLElement; // Serialize all views within this view container. const rootLView = lContainer[PARENT]; const rootLViewNghIndex = annotateHostElementForHydration(hostElement, rootLView, null, context); const renderer = componentLView[RENDERER] as Renderer2; // For cases when a root component also acts as an anchor node for a ViewContainerRef // (for example, when ViewContainerRef is injected in a root component), there is a need // to serialize information about the component itself, as well as an LContainer that // represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info: // (1) hydration info for the root component itself and (2) hydration info for the // ViewContainerRef instance (an LContainer). Each piece of information is included into // the hydration data (in the TransferState object) separately, thus we end up with 2 ids. // Since we only have 1 root element, we encode both bits of info into a single string: // ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view // and 25 is the `ngh` for a root view which holds LContainer). const finalIndex = `${componentLViewNghIndex}|${rootLViewNghIndex}`; renderer.setAttribute(hostElement, NGH_ATTR_NAME, finalIndex); } /** * Annotates all components bootstrapped in a given ApplicationRef * with info needed for hydration. * * @param appRef An instance of an ApplicationRef. * @param doc A reference to the current Document instance. * @return event types that need to be replayed */ export function annotateForHydration(appRef: ApplicationRef, doc: Document) { const injector = appRef.injector; const isI18nHydrationEnabledVal = isI18nHydrationEnabled(injector); const isIncrementalHydrationEnabledVal = isIncrementalHydrationEnabled(injector); const serializedViewCollection = new SerializedViewCollection(); const corruptedTextNodes = new Map<HTMLElement, TextNodeMarker>(); const viewRefs = appRef._views; const shouldReplayEvents = injector.get(IS_EVENT_REPLAY_ENABLED, EVENT_REPLAY_ENABLED_DEFAULT); const eventTypesToReplay = { regular: new Set<string>(), capture: new Set<string>(), }; const deferBlocks = new Map<string, SerializedDeferBlock>(); const appId = appRef.injector.get(APP_ID); for (const viewRef of viewRefs) { const lNode = getLNodeForHydration(viewRef); // An `lView` might be `null` if a `ViewRef` represents // an embedded view (not a component view). if (lNode !== null) { const context: HydrationContext = { serializedViewCollection, corruptedTextNodes, isI18nHydrationEnabled: isI18nHydrationEnabledVal, isIncrementalHydrationEnabled: isIncrementalHydrationEnabledVal, i18nChildren: new Map(), eventTypesToReplay, shouldReplayEvents, appId, deferBlocks, }; if (isLContainer(lNode)) { annotateLContainerForHydration(lNode, context, injector); } else { annotateComponentLViewForHydration(lNode, context, injector); } insertCorruptedTextNodeMarkers(corruptedTextNodes, doc); } } // Note: we *always* include hydration info key and a corresponding value // into the TransferState, even if the list of serialized views is empty. // This is needed as a signal to the client that the server part of the // hydration logic was setup and enabled correctly. Otherwise, if a client // hydration doesn't find a key in the transfer state - an error is produced. const serializedViews = serializedViewCollection.getAll(); const transferState = injector.get(TransferState); transferState.set(NGH_DATA_KEY, serializedViews); if (deferBlocks.size > 0) { const blocks: {[key: string]: SerializedDeferBlock} = {}; // TODO(incremental-hydration): we should probably have an object here instead of a Map? for (const [id, info] of deferBlocks.entries()) { blocks[id] = info; } transferState.set(NGH_DEFER_BLOCKS_KEY, blocks); } return eventTypesToReplay; } /** * Serializes the lContainer data into a list of SerializedView objects, * that represent views within this lContainer. * * @param lContainer the lContainer we are serializing * @param tNode the TNode that contains info about this LContainer * @param lView that hosts this LContainer * @param parentDeferBlockId the defer block id of the parent if it exists * @param context the hydration context * @returns an array of the `SerializedView` objects */
{ "end_byte": 11665, "start_byte": 6368, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/annotate.ts_11666_19716
function serializeLContainer( lContainer: LContainer, tNode: TNode, lView: LView, parentDeferBlockId: string | null, context: HydrationContext, ): SerializedContainerView[] { const views: SerializedContainerView[] = []; let lastViewAsString = ''; for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) { let childLView = lContainer[i] as LView; let template: string; let numRootNodes: number; let serializedView: SerializedContainerView | undefined; if (isRootView(childLView)) { // If this is a root view, get an LView for the underlying component, // because it contains information about the view to serialize. childLView = childLView[HEADER_OFFSET]; // If we have an LContainer at this position, this indicates that the // host element was used as a ViewContainerRef anchor (e.g. a `ViewContainerRef` // was injected within the component class). This case requires special handling. if (isLContainer(childLView)) { // Calculate the number of root nodes in all views in a given container // and increment by one to account for an anchor node itself, i.e. in this // scenario we'll have a layout that would look like this: // `<app-root /><#VIEW1><#VIEW2>...<!--container-->` // The `+1` is to capture the `<app-root />` element. numRootNodes = calcNumRootNodesInLContainer(childLView) + 1; annotateLContainerForHydration(childLView, context, lView[INJECTOR]!); const componentLView = unwrapLView(childLView[HOST]) as LView<unknown>; serializedView = { [TEMPLATE_ID]: componentLView[TVIEW].ssrId!, [NUM_ROOT_NODES]: numRootNodes, }; } } if (!serializedView) { const childTView = childLView[TVIEW]; if (childTView.type === TViewType.Component) { template = childTView.ssrId!; // This is a component view, thus it has only 1 root node: the component // host node itself (other nodes would be inside that host node). numRootNodes = 1; } else { template = getSsrId(childTView); numRootNodes = calcNumRootNodes(childTView, childLView, childTView.firstChild); } serializedView = { [TEMPLATE_ID]: template, [NUM_ROOT_NODES]: numRootNodes, }; let isHydrateNeverBlock = false; // If this is a defer block, serialize extra info. if (isDeferBlock(lView[TVIEW], tNode)) { const lDetails = getLDeferBlockDetails(lView, tNode); if (context.isIncrementalHydrationEnabled) { const deferBlockId = `d${context.deferBlocks.size}`; const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode); if (tDetails.hydrateTriggers?.has(DeferBlockTrigger.Never)) { isHydrateNeverBlock = true; } let rootNodes: any[] = []; collectNativeNodesInLContainer(lContainer, rootNodes); // Add defer block into info context.deferBlocks const deferBlockInfo: SerializedDeferBlock = { [DEFER_PARENT_BLOCK_ID]: parentDeferBlockId, [NUM_ROOT_NODES]: rootNodes.length, [DEFER_BLOCK_STATE]: lDetails[CURRENT_DEFER_BLOCK_STATE], [DEFER_HYDRATE_TRIGGERS]: serializeHydrateTriggers(tDetails.hydrateTriggers), }; context.deferBlocks.set(deferBlockId, deferBlockInfo); const node = unwrapRNode(lContainer); if (node !== undefined) { if ((node as Node).nodeType === Node.COMMENT_NODE) { annotateDeferBlockAnchorForHydration(node as RComment, deferBlockId); } } else { ngDevMode && validateNodeExists(node, childLView, tNode); ngDevMode && validateMatchingNode(node, Node.COMMENT_NODE, null, childLView, tNode, true); annotateDeferBlockAnchorForHydration(node as RComment, deferBlockId); } if (!isHydrateNeverBlock) { // Add JSAction attributes for root nodes that use some hydration triggers annotateDeferBlockRootNodesWithJsAction(tDetails, rootNodes, deferBlockId, context); } // Use current block id as parent for nested routes. parentDeferBlockId = deferBlockId; // Serialize extra info into the view object. // TODO(incremental-hydration): this should be serialized and included at a different level // (not at the view level). serializedView[DEFER_BLOCK_ID] = deferBlockId; } // DEFER_BLOCK_STATE is used for reconciliation in hydration, both regular and incremental. // We need to know which template is rendered when hydrating. So we serialize this state // regardless of hydration type. serializedView[DEFER_BLOCK_STATE] = lDetails[CURRENT_DEFER_BLOCK_STATE]; } if (!isHydrateNeverBlock) { // TODO(incremental-hydration): avoid copying of an object here serializedView = { ...serializedView, ...serializeLView(lContainer[i] as LView, parentDeferBlockId, context), }; } } // Check if the previous view has the same shape (for example, it was // produced by the *ngFor), in which case bump the counter on the previous // view instead of including the same information again. const currentViewAsString = JSON.stringify(serializedView); if (views.length > 0 && currentViewAsString === lastViewAsString) { const previousView = views[views.length - 1]; previousView[MULTIPLIER] ??= 1; previousView[MULTIPLIER]++; } else { // Record this view as most recently added. lastViewAsString = currentViewAsString; views.push(serializedView); } } return views; } function serializeHydrateTriggers( triggerMap: Map<DeferBlockTrigger, HydrateTriggerDetails | null> | null, ): (DeferBlockTrigger | SerializedTriggerDetails)[] | null { if (triggerMap === null) { return null; } const serializableDeferBlockTrigger = new Set<DeferBlockTrigger>([ DeferBlockTrigger.Idle, DeferBlockTrigger.Immediate, DeferBlockTrigger.Viewport, DeferBlockTrigger.Timer, ]); let triggers = []; for (let [trigger, details] of triggerMap) { if (serializableDeferBlockTrigger.has(trigger)) { if (details === null) { triggers.push(trigger); } else { triggers.push({trigger, details}); } } } return triggers; } /** * Helper function to produce a node path (which navigation steps runtime logic * needs to take to locate a node) and stores it in the `NODES` section of the * current serialized view. */ function appendSerializedNodePath( ngh: SerializedView, tNode: TNode, lView: LView, excludedParentNodes: Set<number> | null, ) { const noOffsetIndex = tNode.index - HEADER_OFFSET; ngh[NODES] ??= {}; // Ensure we don't calculate the path multiple times. ngh[NODES][noOffsetIndex] ??= calcPathForNode(tNode, lView, excludedParentNodes); } /** * Helper function to append information about a disconnected node. * This info is needed at runtime to avoid DOM lookups for this element * and instead, the element would be created from scratch. */ function appendDisconnectedNodeIndex(ngh: SerializedView, tNodeOrNoOffsetIndex: TNode | number) { const noOffsetIndex = typeof tNodeOrNoOffsetIndex === 'number' ? tNodeOrNoOffsetIndex : tNodeOrNoOffsetIndex.index - HEADER_OFFSET; ngh[DISCONNECTED_NODES] ??= []; if (!ngh[DISCONNECTED_NODES].includes(noOffsetIndex)) { ngh[DISCONNECTED_NODES].push(noOffsetIndex); } } /** * Serializes the lView data into a SerializedView object that will later be added * to the TransferState storage and referenced using the `ngh` attribute on a host * element. * * @param lView the lView we are serializing * @param context the hydration context * @returns the `SerializedView` object containing the data to be added to the host node */
{ "end_byte": 19716, "start_byte": 11666, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/annotate.ts_19717_19848
function serializeLView( lView: LView, parentDeferBlockId: string | null = null, context: HydrationContext, ): SerializedView
{ "end_byte": 19848, "start_byte": 19717, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/annotate.ts_19849_28216
{ const ngh: SerializedView = {}; const tView = lView[TVIEW]; const i18nChildren = getOrComputeI18nChildren(tView, context); const nativeElementsToEventTypes = context.shouldReplayEvents ? collectDomEventsInfo(tView, lView, context.eventTypesToReplay) : null; // Iterate over DOM element references in an LView. for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { const tNode = tView.data[i]; const noOffsetIndex = i - HEADER_OFFSET; // Attempt to serialize any i18n data for the given slot. We do this first, as i18n // has its own process for serialization. const i18nData = trySerializeI18nBlock(lView, i, context); if (i18nData) { ngh[I18N_DATA] ??= {}; ngh[I18N_DATA][noOffsetIndex] = i18nData.caseQueue; for (const nodeNoOffsetIndex of i18nData.disconnectedNodes) { appendDisconnectedNodeIndex(ngh, nodeNoOffsetIndex); } for (const nodeNoOffsetIndex of i18nData.disjointNodes) { const tNode = tView.data[nodeNoOffsetIndex + HEADER_OFFSET] as TNode; ngDevMode && assertTNode(tNode); appendSerializedNodePath(ngh, tNode, lView, i18nChildren); } continue; } // Skip processing of a given slot in the following cases: // - Local refs (e.g. <div #localRef>) take up an extra slot in LViews // to store the same element. In this case, there is no information in // a corresponding slot in TNode data structure. // - When a slot contains something other than a TNode. For example, there // might be some metadata information about a defer block or a control flow block. if (!isTNodeShape(tNode)) { continue; } // Skip any nodes that are in an i18n block but are considered detached (i.e. not // present in the template). These nodes are disconnected from the DOM tree, and // so we don't want to serialize any information about them. if (isDetachedByI18n(tNode)) { continue; } // Check if a native node that represents a given TNode is disconnected from the DOM tree. // Such nodes must be excluded from the hydration (since the hydration won't be able to // find them), so the TNode ids are collected and used at runtime to skip the hydration. // // This situation may happen during the content projection, when some nodes don't make it // into one of the content projection slots (for example, when there is no default // <ng-content /> slot in projector component's template). if (isDisconnectedNode(tNode, lView) && isContentProjectedNode(tNode)) { appendDisconnectedNodeIndex(ngh, tNode); continue; } if (Array.isArray(tNode.projection)) { for (const projectionHeadTNode of tNode.projection) { // We may have `null`s in slots with no projected content. if (!projectionHeadTNode) continue; if (!Array.isArray(projectionHeadTNode)) { // If we process re-projected content (i.e. `<ng-content>` // appears at projection location), skip annotations for this content // since all DOM nodes in this projection were handled while processing // a parent lView, which contains those nodes. if ( !isProjectionTNode(projectionHeadTNode) && !isInSkipHydrationBlock(projectionHeadTNode) ) { if (isDisconnectedNode(projectionHeadTNode, lView)) { // Check whether this node is connected, since we may have a TNode // in the data structure as a projection segment head, but the // content projection slot might be disabled (e.g. // <ng-content *ngIf="false" />). appendDisconnectedNodeIndex(ngh, projectionHeadTNode); } else { appendSerializedNodePath(ngh, projectionHeadTNode, lView, i18nChildren); } } } else { // If a value is an array, it means that we are processing a projection // where projectable nodes were passed in as DOM nodes (for example, when // calling `ViewContainerRef.createComponent(CmpA, {projectableNodes: [...]})`). // // In this scenario, nodes can come from anywhere (either created manually, // accessed via `document.querySelector`, etc) and may be in any state // (attached or detached from the DOM tree). As a result, we can not reliably // restore the state for such cases during hydration. throw unsupportedProjectionOfDomNodes(unwrapRNode(lView[i])); } } } conditionallyAnnotateNodePath(ngh, tNode, lView, i18nChildren); if (isLContainer(lView[i])) { // Serialize information about a template. const embeddedTView = tNode.tView; if (embeddedTView !== null) { ngh[TEMPLATES] ??= {}; ngh[TEMPLATES][noOffsetIndex] = getSsrId(embeddedTView); } // Serialize views within this LContainer. const hostNode = lView[i][HOST]!; // host node of this container // LView[i][HOST] can be of 2 different types: // - either a DOM node // - or an array that represents an LView of a component if (Array.isArray(hostNode)) { // This is a component, serialize info about it. const targetNode = unwrapRNode(hostNode as LView) as RElement; if (!(targetNode as HTMLElement).hasAttribute(SKIP_HYDRATION_ATTR_NAME)) { annotateHostElementForHydration( targetNode, hostNode as LView, parentDeferBlockId, context, ); } } ngh[CONTAINERS] ??= {}; ngh[CONTAINERS][noOffsetIndex] = serializeLContainer( lView[i], tNode, lView, parentDeferBlockId, context, ); } else if (Array.isArray(lView[i]) && !isLetDeclaration(tNode)) { // This is a component, annotate the host node with an `ngh` attribute. // Note: Let declarations that return an array are also storing an array in the LView, // we need to exclude them. const targetNode = unwrapRNode(lView[i][HOST]!); if (!(targetNode as HTMLElement).hasAttribute(SKIP_HYDRATION_ATTR_NAME)) { annotateHostElementForHydration( targetNode as RElement, lView[i], parentDeferBlockId, context, ); } } else { // <ng-container> case if (tNode.type & TNodeType.ElementContainer) { // An <ng-container> is represented by the number of // top-level nodes. This information is needed to skip over // those nodes to reach a corresponding anchor node (comment node). ngh[ELEMENT_CONTAINERS] ??= {}; ngh[ELEMENT_CONTAINERS][noOffsetIndex] = calcNumRootNodes(tView, lView, tNode.child); } else if (tNode.type & (TNodeType.Projection | TNodeType.LetDeclaration)) { // Current TNode represents an `<ng-content>` slot or `@let` declaration, // thus it has no DOM elements associated with it, so the **next sibling** // node would not be able to find an anchor. In this case, use full path instead. let nextTNode = tNode.next; // Skip over all `<ng-content>` slots and `@let` declarations in a row. while ( nextTNode !== null && nextTNode.type & (TNodeType.Projection | TNodeType.LetDeclaration) ) { nextTNode = nextTNode.next; } if (nextTNode && !isInSkipHydrationBlock(nextTNode)) { // Handle a tNode after the `<ng-content>` slot. appendSerializedNodePath(ngh, nextTNode, lView, i18nChildren); } } else if (tNode.type & TNodeType.Text) { const rNode = unwrapRNode(lView[i]); processTextNodeBeforeSerialization(context, rNode); } } // 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, ); } } } return ngh; }
{ "end_byte": 28216, "start_byte": 19849, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/annotate.ts_28218_34234
/** * Serializes node location in cases when it's needed, specifically: * * 1. If `tNode.projectionNext` is different from `tNode.next` - it means that * the next `tNode` after projection is different from the one in the original * template. Since hydration relies on `tNode.next`, this serialized info * is required to help runtime code find the node at the correct location. * 2. In certain content projection-based use-cases, it's possible that only * a content of a projected element is rendered. In this case, content nodes * require an extra annotation, since runtime logic can't rely on parent-child * connection to identify the location of a node. */ function conditionallyAnnotateNodePath( ngh: SerializedView, tNode: TNode, lView: LView<unknown>, excludedParentNodes: Set<number> | null, ) { if (isProjectionTNode(tNode)) { // Do not annotate projection nodes (<ng-content />), since // they don't have a corresponding DOM node representing them. return; } // Handle case #1 described above. if ( tNode.projectionNext && tNode.projectionNext !== tNode.next && !isInSkipHydrationBlock(tNode.projectionNext) ) { appendSerializedNodePath(ngh, tNode.projectionNext, lView, excludedParentNodes); } // Handle case #2 described above. // Note: we only do that for the first node (i.e. when `tNode.prev === null`), // the rest of the nodes would rely on the current node location, so no extra // annotation is needed. if ( tNode.prev === null && tNode.parent !== null && isDisconnectedNode(tNode.parent, lView) && !isDisconnectedNode(tNode, lView) ) { appendSerializedNodePath(ngh, tNode, lView, excludedParentNodes); } } /** * Determines whether a component instance that is represented * by a given LView uses `ViewEncapsulation.ShadowDom`. */ function componentUsesShadowDomEncapsulation(lView: LView): boolean { const instance = lView[CONTEXT]; return instance?.constructor ? getComponentDef(instance.constructor)?.encapsulation === ViewEncapsulation.ShadowDom : false; } /** * Annotates component host element for hydration: * - by either adding the `ngh` attribute and collecting hydration-related info * for the serialization and transferring to the client * - or by adding the `ngSkipHydration` attribute in case Angular detects that * component contents is not compatible with hydration. * * @param element The Host element to be annotated * @param lView The associated LView * @param context The hydration context * @returns An index of serialized view from the transfer state object * or `null` when a given component can not be serialized. */ function annotateHostElementForHydration( element: RElement, lView: LView, parentDeferBlockId: string | null, context: HydrationContext, ): number | null { const renderer = lView[RENDERER]; if ( (hasI18n(lView) && !isI18nHydrationSupportEnabled()) || componentUsesShadowDomEncapsulation(lView) ) { // Attach the skip hydration attribute if this component: // - either has i18n blocks, since hydrating such blocks is not yet supported // - or uses ShadowDom view encapsulation, since Domino doesn't support // shadow DOM, so we can not guarantee that client and server representations // would exactly match renderer.setAttribute(element, SKIP_HYDRATION_ATTR_NAME, ''); return null; } else { const ngh = serializeLView(lView, parentDeferBlockId, context); const index = context.serializedViewCollection.add(ngh); renderer.setAttribute(element, NGH_ATTR_NAME, index.toString()); return index; } } /** * Annotates defer block comment node for hydration: * * @param comment The Host element to be annotated * @param deferBlockId the id of the target defer block */ function annotateDeferBlockAnchorForHydration(comment: RComment, deferBlockId: string): void { comment.textContent = `ngh=${deferBlockId}`; } /** * Physically inserts the comment nodes to ensure empty text nodes and adjacent * text node separators are preserved after server serialization of the DOM. * These get swapped back for empty text nodes or separators once hydration happens * on the client. * * @param corruptedTextNodes The Map of text nodes to be replaced with comments * @param doc The document */ function insertCorruptedTextNodeMarkers( corruptedTextNodes: Map<HTMLElement, string>, doc: Document, ) { for (const [textNode, marker] of corruptedTextNodes) { textNode.after(doc.createComment(marker)); } } /** * Detects whether a given TNode represents a node that * is being content projected. */ function isContentProjectedNode(tNode: TNode): boolean { let currentTNode = tNode; while (currentTNode != null) { // If we come across a component host node in parent nodes - // this TNode is in the content projection section. if (isComponentHost(currentTNode)) { return true; } currentTNode = currentTNode.parent as TNode; } return false; } /** * Incremental hydration requires that any defer block root node * with interaction or hover triggers have all of their root nodes * trigger hydration with those events. So we need to make sure all * the root nodes of that block have the proper jsaction attribute * to ensure hydration is triggered, since the content is dehydrated */ function annotateDeferBlockRootNodesWithJsAction( tDetails: TDeferBlockDetails, rootNodes: any[], parentDeferBlockId: string, context: HydrationContext, ) { const actionList = convertHydrateTriggersToJsAction(tDetails.hydrateTriggers); for (let et of actionList) { context.eventTypesToReplay.regular.add(et); } if (actionList.length > 0) { const elementNodes = (rootNodes as HTMLElement[]).filter( (rn) => rn.nodeType === Node.ELEMENT_NODE, ); for (let rNode of elementNodes) { setJSActionAttributes(rNode, actionList, parentDeferBlockId); } } }
{ "end_byte": 34234, "start_byte": 28218, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/annotate.ts" }
angular/packages/core/src/hydration/cleanup.ts_0_4588
/** * @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 {ApplicationRef} from '../application/application_ref'; import { CONTAINER_HEADER_OFFSET, DEHYDRATED_VIEWS, LContainer, } from '../render3/interfaces/container'; import {Renderer} from '../render3/interfaces/renderer'; import {RNode} from '../render3/interfaces/renderer_dom'; import {isLContainer, isLView} from '../render3/interfaces/type_checks'; import {HEADER_OFFSET, HOST, LView, PARENT, RENDERER, TVIEW} from '../render3/interfaces/view'; import {nativeRemoveNode} from '../render3/node_manipulation'; import {validateSiblingNodeExists} from './error_handling'; import {cleanupI18nHydrationData} from './i18n'; import {DEFER_BLOCK_ID, DehydratedContainerView, NUM_ROOT_NODES} from './interfaces'; import {getLNodeForHydration} from './utils'; /** * Removes all dehydrated views from a given LContainer: * both in internal data structure, as well as removing * corresponding DOM nodes that belong to that dehydrated view. */ export function removeDehydratedViews(lContainer: LContainer) { const views = lContainer[DEHYDRATED_VIEWS] ?? []; const parentLView = lContainer[PARENT]; const renderer = parentLView[RENDERER]; const retainedViews = []; for (const view of views) { // Do not clean up contents of `@defer` blocks. // The cleanup for this content would happen once a given block // is triggered and hydrated. if (view.data[DEFER_BLOCK_ID] !== undefined) { retainedViews.push(view); } else { removeDehydratedView(view, renderer); ngDevMode && ngDevMode.dehydratedViewsRemoved++; } } // Reset the value to an array to indicate that no // further processing of dehydrated views is needed for // this view container (i.e. do not trigger the lookup process // once again in case a `ViewContainerRef` is created later). lContainer[DEHYDRATED_VIEWS] = retainedViews; } /** * Helper function to remove all nodes from a dehydrated view. */ function removeDehydratedView(dehydratedView: DehydratedContainerView, renderer: Renderer) { let nodesRemoved = 0; let currentRNode = dehydratedView.firstChild; if (currentRNode) { const numNodes = dehydratedView.data[NUM_ROOT_NODES]; while (nodesRemoved < numNodes) { ngDevMode && validateSiblingNodeExists(currentRNode); const nextSibling: RNode = currentRNode.nextSibling!; nativeRemoveNode(renderer, currentRNode, false); currentRNode = nextSibling; nodesRemoved++; } } } /** * Walks over all views within this LContainer invokes dehydrated views * cleanup function for each one. */ export function cleanupLContainer(lContainer: LContainer) { removeDehydratedViews(lContainer); // The host could be an LView if this container is on a component node. // In this case, descend into host LView for further cleanup. See also // LContainer[HOST] docs for additional information. const hostLView = lContainer[HOST]; if (isLView(hostLView)) { cleanupLView(hostLView); } for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) { cleanupLView(lContainer[i] as LView); } } /** * Walks over `LContainer`s and components registered within * this LView and invokes dehydrated views cleanup function for each one. */ function cleanupLView(lView: LView) { cleanupI18nHydrationData(lView); const tView = lView[TVIEW]; for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { if (isLContainer(lView[i])) { const lContainer = lView[i]; cleanupLContainer(lContainer); } else if (isLView(lView[i])) { // This is a component, enter the `cleanupLView` recursively. cleanupLView(lView[i]); } } } /** * Walks over all views registered within the ApplicationRef and removes * all dehydrated views from all `LContainer`s along the way. */ export function cleanupDehydratedViews(appRef: ApplicationRef) { const viewRefs = appRef._views; for (const viewRef of viewRefs) { const lNode = getLNodeForHydration(viewRef); // An `lView` might be `null` if a `ViewRef` represents // an embedded view (not a component view). if (lNode !== null && lNode[HOST] !== null) { if (isLView(lNode)) { cleanupLView(lNode); } else { // Cleanup in all views within this view container cleanupLContainer(lNode); } ngDevMode && ngDevMode.dehydratedViewsCleanupRuns++; } } }
{ "end_byte": 4588, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/cleanup.ts" }
angular/packages/core/src/hydration/tokens.ts_0_2171
/** * @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 {InjectionToken} from '../di/injection_token'; /** * Internal token that specifies whether DOM reuse logic * during hydration is enabled. */ export const IS_HYDRATION_DOM_REUSE_ENABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_HYDRATION_DOM_REUSE_ENABLED' : '', ); // By default (in client rendering mode), we remove all the contents // of the host element and render an application after that. export const PRESERVE_HOST_CONTENT_DEFAULT = false; /** * Internal token that indicates whether host element content should be * retained during the bootstrap. */ export const PRESERVE_HOST_CONTENT = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || !!ngDevMode ? 'PRESERVE_HOST_CONTENT' : '', { providedIn: 'root', factory: () => PRESERVE_HOST_CONTENT_DEFAULT, }, ); /** * Internal token that indicates whether hydration support for i18n * is enabled. */ export const IS_I18N_HYDRATION_ENABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_I18N_HYDRATION_ENABLED' : '', ); /** * Internal token that indicates whether event replay support for SSR * is enabled. */ export const IS_EVENT_REPLAY_ENABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_EVENT_REPLAY_ENABLED' : '', ); export const EVENT_REPLAY_ENABLED_DEFAULT = false; /** * Internal token that indicates whether incremental hydration support * is enabled. */ export const IS_INCREMENTAL_HYDRATION_ENABLED = new InjectionToken<boolean>( typeof ngDevMode === 'undefined' || !!ngDevMode ? 'IS_INCREMENTAL_HYDRATION_ENABLED' : '', ); /** * A map of DOM elements with `jsaction` attributes grouped by action names. */ export const BLOCK_ELEMENT_MAP = new InjectionToken<Map<string, Set<Element>>>( ngDevMode ? 'BLOCK_ELEMENT_MAP' : '', { providedIn: 'root', factory: () => new Map<string, Set<Element>>(), }, );
{ "end_byte": 2171, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/tokens.ts" }
angular/packages/core/src/hydration/skip_hydration.ts_0_2892
/** * @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 {TNode, TNodeFlags} from '../render3/interfaces/node'; import {RElement} from '../render3/interfaces/renderer_dom'; /** * The name of an attribute that can be added to the hydration boundary node * (component host node) to disable hydration for the content within that boundary. */ export const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration'; /** Lowercase name of the `ngSkipHydration` attribute used for case-insensitive comparisons. */ const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = 'ngskiphydration'; /** * Helper function to check if a given TNode has the 'ngSkipHydration' attribute. */ export function hasSkipHydrationAttrOnTNode(tNode: TNode): boolean { const attrs = tNode.mergedAttrs; if (attrs === null) return false; // only ever look at the attribute name and skip the values for (let i = 0; i < attrs.length; i += 2) { const value = attrs[i]; // This is a marker, which means that the static attributes section is over, // so we can exit early. if (typeof value === 'number') return false; if (typeof value === 'string' && value.toLowerCase() === SKIP_HYDRATION_ATTR_NAME_LOWER_CASE) { return true; } } return false; } /** * Helper function to check if a given RElement has the 'ngSkipHydration' attribute. */ export function hasSkipHydrationAttrOnRElement(rNode: RElement): boolean { return rNode.hasAttribute(SKIP_HYDRATION_ATTR_NAME); } /** * Checks whether a TNode has a flag to indicate that it's a part of * a skip hydration block. */ export function hasInSkipHydrationBlockFlag(tNode: TNode): boolean { return (tNode.flags & TNodeFlags.inSkipHydrationBlock) === TNodeFlags.inSkipHydrationBlock; } /** * Helper function that determines if a given node is within a skip hydration block * by navigating up the TNode tree to see if any parent nodes have skip hydration * attribute. */ export function isInSkipHydrationBlock(tNode: TNode): boolean { if (hasInSkipHydrationBlockFlag(tNode)) { return true; } let currentTNode: TNode | null = tNode.parent; while (currentTNode) { if (hasInSkipHydrationBlockFlag(tNode) || hasSkipHydrationAttrOnTNode(currentTNode)) { return true; } currentTNode = currentTNode.parent; } return false; } /** * Check if an i18n block is in a skip hydration section by looking at a parent TNode * to determine if this TNode is in a skip hydration section or the TNode has * the `ngSkipHydration` attribute. */ export function isI18nInSkipHydrationBlock(parentTNode: TNode): boolean { return ( hasInSkipHydrationBlockFlag(parentTNode) || hasSkipHydrationAttrOnTNode(parentTNode) || isInSkipHydrationBlock(parentTNode) ); }
{ "end_byte": 2892, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/skip_hydration.ts" }
angular/packages/core/src/hydration/compression.ts_0_3039
/** * @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 {NodeNavigationStep, REFERENCE_NODE_BODY, REFERENCE_NODE_HOST} from './interfaces'; /** * Regexp that extracts a reference node information from the compressed node location. * The reference node is represented as either: * - a number which points to an LView slot * - the `b` char which indicates that the lookup should start from the `document.body` * - the `h` char to start lookup from the component host node (`lView[HOST]`) */ const REF_EXTRACTOR_REGEXP = new RegExp( `^(\\d+)*(${REFERENCE_NODE_BODY}|${REFERENCE_NODE_HOST})*(.*)`, ); /** * Helper function that takes a reference node location and a set of navigation steps * (from the reference node) to a target node and outputs a string that represents * a location. * * For example, given: referenceNode = 'b' (body) and path = ['firstChild', 'firstChild', * 'nextSibling'], the function returns: `bf2n`. */ export function compressNodeLocation(referenceNode: string, path: NodeNavigationStep[]): string { const result: Array<string | number> = [referenceNode]; for (const segment of path) { const lastIdx = result.length - 1; if (lastIdx > 0 && result[lastIdx - 1] === segment) { // An empty string in a count slot represents 1 occurrence of an instruction. const value = (result[lastIdx] || 1) as number; result[lastIdx] = value + 1; } else { // Adding a new segment to the path. // Using an empty string in a counter field to avoid encoding `1`s // into the path, since they are implicit (e.g. `f1n1` vs `fn`), so // it's enough to have a single char in this case. result.push(segment, ''); } } return result.join(''); } /** * Helper function that reverts the `compressNodeLocation` and transforms a given * string into an array where at 0th position there is a reference node info and * after that it contains information (in pairs) about a navigation step and the * number of repetitions. * * For example, the path like 'bf2n' will be transformed to: * ['b', 'firstChild', 2, 'nextSibling', 1]. * * This information is later consumed by the code that navigates the DOM to find * a given node by its location. */ export function decompressNodeLocation( path: string, ): [string | number, ...(number | NodeNavigationStep)[]] { const matches = path.match(REF_EXTRACTOR_REGEXP)!; const [_, refNodeId, refNodeName, rest] = matches; // If a reference node is represented by an index, transform it to a number. const ref = refNodeId ? parseInt(refNodeId, 10) : refNodeName; const steps: (number | NodeNavigationStep)[] = []; // Match all segments in a path. for (const [_, step, count] of rest.matchAll(/(f|n)(\d*)/g)) { const repeat = parseInt(count, 10) || 1; steps.push(step as NodeNavigationStep, repeat); } return [ref, ...steps]; }
{ "end_byte": 3039, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/compression.ts" }
angular/packages/core/src/hydration/interfaces.ts_0_8424
/** * @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 {DeferBlockTrigger} from '../defer/interfaces'; import type {I18nICUNode} from '../render3/interfaces/i18n'; import {RNode} from '../render3/interfaces/renderer_dom'; /** Encodes that the node lookup should start from the host node of this component. */ export const REFERENCE_NODE_HOST = 'h'; /** Encodes that the node lookup should start from the document body node. */ export const REFERENCE_NODE_BODY = 'b'; /** * Describes navigation steps that the runtime logic need to perform, * starting from a given (known) element. */ export enum NodeNavigationStep { FirstChild = 'f', NextSibling = 'n', } /** * Keys within serialized view data structure to represent various * parts. See the `SerializedView` interface below for additional information. */ export const ELEMENT_CONTAINERS = 'e'; export const TEMPLATES = 't'; export const CONTAINERS = 'c'; export const MULTIPLIER = 'x'; export const NUM_ROOT_NODES = 'r'; 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 DEFER_BLOCK_ID = 'di'; export const DEFER_BLOCK_STATE = 's'; export const DEFER_PARENT_BLOCK_ID = 'p'; export const DEFER_HYDRATE_TRIGGERS = 't'; export const DEFER_PREFETCH_TRIGGERS = 'pt'; /** * Represents element containers within this view, stored as key-value pairs * where key is an index of a container in an LView (also used in the * `elementContainerStart` instruction), the value is the number of root nodes * in this container. This information is needed to locate an anchor comment * node that goes after all container nodes. */ export interface SerializedElementContainers { [key: number]: number; } /** * Serialized data structure that contains relevant hydration * annotation information that describes a given hydration boundary * (e.g. a component). */ export interface SerializedView { /** * Serialized information about <ng-container>s. */ [ELEMENT_CONTAINERS]?: SerializedElementContainers; /** * Serialized information about templates. * Key-value pairs where a key is an index of the corresponding * `template` instruction and the value is a unique id that can * be used during hydration to identify that template. */ [TEMPLATES]?: Record<number, string>; /** * Serialized information about view containers. * Key-value pairs where a key is an index of the corresponding * LContainer entry within an LView, and the value is a list * of serialized information about views within this container. */ [CONTAINERS]?: Record<number, SerializedContainerView[]>; /** * Serialized information about nodes in a template. * Key-value pairs where a key is an index of the corresponding * DOM node in an LView and the value is a path that describes * the location of this node (as a set of navigation instructions). */ [NODES]?: Record<number, string>; /** * A list of ids which represents a set of nodes disconnected * from the DOM tree at the serialization time, but otherwise * present in the internal data structures. * * This information is used to avoid triggering the hydration * logic for such nodes and instead use a regular "creation mode". */ [DISCONNECTED_NODES]?: number[]; /** * Serialized information about i18n blocks in a template. * Key-value pairs where a key is an index of the corresponding * i18n entry within an LView, and the value is a list of * active ICU cases. */ [I18N_DATA]?: Record<number, number[]>; /** * If this view represents a `@defer` block, this field contains * unique id of the block. */ [DEFER_BLOCK_ID]?: string; /** * This field represents a status, based on the `DeferBlockState` enum. */ [DEFER_BLOCK_STATE]?: number; } /** * Serialized data structure that contains relevant hydration * annotation information about a view that is a part of a * ViewContainer collection. */ export interface SerializedContainerView extends SerializedView { /** * Unique id that represents a TView that was used to create * a given instance of a view: * - TViewType.Embedded: a unique id generated during serialization on the server * - TViewType.Component: an id generated based on component properties * (see `getComponentId` function for details) */ [TEMPLATE_ID]: string; /** * Number of root nodes that belong to this view. * This information is needed to effectively traverse the DOM tree * and identify segments that belong to different views. */ [NUM_ROOT_NODES]: number; /** * Number of times this view is repeated. * This is used to avoid serializing and sending the same hydration * information about similar views (for example, produced by *ngFor). */ [MULTIPLIER]?: number; } /** * Serialized data structure that contains relevant defer block * information that describes a given incremental hydration boundary */ export interface SerializedDeferBlock { /** * This contains the unique id of this defer block's parent, if it exists. */ [DEFER_PARENT_BLOCK_ID]: string | null; /** * This field represents a status, based on the `DeferBlockState` enum. */ [DEFER_BLOCK_STATE]?: number; /** * Number of root nodes that belong to this defer block's template. * This information is needed to effectively traverse the DOM tree * and add jsaction attributes to root nodes appropriately for * incremental hydration. */ [NUM_ROOT_NODES]: number; /** * The list of triggers that exist for incremental hydration, based on the * `Trigger` enum. */ [DEFER_HYDRATE_TRIGGERS]: (DeferBlockTrigger | SerializedTriggerDetails)[] | null; } export interface SerializedTriggerDetails { trigger: DeferBlockTrigger; delay?: number; } /** * An object that contains hydration-related information serialized * on the server, as well as the necessary references to segments of * the DOM, to facilitate the hydration process for a given hydration * boundary on the client. */ export interface DehydratedView { /** * The readonly hydration annotation data. */ data: Readonly<SerializedView>; /** * A reference to the first child in a DOM segment associated * with a given hydration boundary. * * Once a view becomes hydrated, the value is set to `null`, which * indicates that further detaching/attaching view actions should result * in invoking corresponding DOM actions (attaching DOM nodes action is * skipped when we hydrate, since nodes are already in the DOM). */ firstChild: RNode | null; /** * Stores references to first nodes in DOM segments that * represent either an <ng-container> or a view container. */ segmentHeads?: {[index: number]: RNode | null}; /** * An instance of a Set that represents nodes disconnected from * the DOM tree at the serialization time, but otherwise present * in the internal data structures. * * The Set is based on the `SerializedView[DISCONNECTED_NODES]` data * and is needed to have constant-time lookups. * * If the value is `null`, it means that there were no disconnected * nodes detected in this view at serialization time. */ disconnectedNodes?: Set<number> | null; /** * A mapping from a view to the first child to begin claiming nodes. * * This mapping is generated by an i18n block, and is the source of * truth for the nodes inside of it. */ i18nNodes?: Map<number, RNode | null>; /** * A mapping from the index of an ICU node to dehydrated data for it. * * This information is used during the hydration process on the client. * ICU cases that were active during server-side rendering will be added * to the map. The hydration logic will "claim" matching cases, removing * them from the map. The remaining entries are "unclaimed", and will be * removed from the DOM during hydration cleanup. */ dehydratedIcuData?: Map<number, DehydratedIcuData>; /** * A mapping of defer block unique ids to the defer block data */ dehydratedDeferBlockData?: Record<string, SerializedDeferBlock>; }
{ "end_byte": 8424, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/interfaces.ts" }
angular/packages/core/src/hydration/interfaces.ts_8426_9294
/** * An object that contains hydration-related information serialized * on the server, as well as the necessary references to segments of * the DOM, to facilitate the hydration process for a given view * inside a view container (either an embedded view or a view created * for a component). */ export interface DehydratedContainerView extends DehydratedView { data: Readonly<SerializedContainerView>; } /** * An object that contains information about a dehydrated ICU case, * to facilitate cleaning up ICU cases that were active during * server-side rendering, but not during hydration. */ export interface DehydratedIcuData { /** * The case index that this data represents. */ case: number; /** * A reference back to the AST for the ICU node. This allows the * AST to be used to clean up dehydrated nodes. */ node: I18nICUNode; }
{ "end_byte": 9294, "start_byte": 8426, "url": "https://github.com/angular/angular/blob/main/packages/core/src/hydration/interfaces.ts" }
angular/packages/core/src/defer/timer_scheduler.ts_0_7692
/** * @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 {Injector, ɵɵdefineInjectable} from '../di'; import {arrayInsert2, arraySplice} from '../util/array_utils'; /** * Returns a function that captures a provided delay. * Invoking the returned function schedules a trigger. */ export function onTimer(delay: number) { return (callback: VoidFunction, injector: Injector) => scheduleTimerTrigger(delay, callback, injector); } /** * Schedules a callback to be invoked after a given timeout. * * @param delay A number of ms to wait until firing a callback. * @param callback A function to be invoked after a timeout. * @param injector injector for the app. */ export function scheduleTimerTrigger(delay: number, callback: VoidFunction, injector: Injector) { const scheduler = injector.get(TimerScheduler); const cleanupFn = () => scheduler.remove(callback); scheduler.add(delay, callback); return cleanupFn; } /** * Helper service to schedule `setTimeout`s for batches of defer blocks, * to avoid calling `setTimeout` for each defer block (e.g. if defer blocks * are created inside a for loop). */ export class TimerScheduler { // Indicates whether current callbacks are being invoked. executingCallbacks = false; // Currently scheduled `setTimeout` id. timeoutId: number | null = null; // When currently scheduled timer would fire. invokeTimerAt: number | null = null; // List of callbacks to be invoked. // For each callback we also store a timestamp on when the callback // should be invoked. We store timestamps and callback functions // in a flat array to avoid creating new objects for each entry. // [timestamp1, callback1, timestamp2, callback2, ...] current: Array<number | VoidFunction> = []; // List of callbacks collected while invoking current set of callbacks. // Those callbacks are added to the "current" queue at the end of // the current callback invocation. The shape of this list is the same // as the shape of the `current` list. deferred: Array<number | VoidFunction> = []; add(delay: number, callback: VoidFunction) { const target = this.executingCallbacks ? this.deferred : this.current; this.addToQueue(target, Date.now() + delay, callback); this.scheduleTimer(); } remove(callback: VoidFunction) { const {current, deferred} = this; const callbackIndex = this.removeFromQueue(current, callback); if (callbackIndex === -1) { // Try cleaning up deferred queue only in case // we didn't find a callback in the "current" queue. this.removeFromQueue(deferred, callback); } // If the last callback was removed and there is a pending timeout - cancel it. if (current.length === 0 && deferred.length === 0) { this.clearTimeout(); } } private addToQueue( target: Array<number | VoidFunction>, invokeAt: number, callback: VoidFunction, ) { let insertAtIndex = target.length; for (let i = 0; i < target.length; i += 2) { const invokeQueuedCallbackAt = target[i] as number; if (invokeQueuedCallbackAt > invokeAt) { // We've reached a first timer that is scheduled // for a later time than what we are trying to insert. // This is the location at which we need to insert, // no need to iterate further. insertAtIndex = i; break; } } arrayInsert2(target, insertAtIndex, invokeAt, callback); } private removeFromQueue(target: Array<number | VoidFunction>, callback: VoidFunction) { let index = -1; for (let i = 0; i < target.length; i += 2) { const queuedCallback = target[i + 1]; if (queuedCallback === callback) { index = i; break; } } if (index > -1) { // Remove 2 elements: a timestamp slot and // the following slot with a callback function. arraySplice(target, index, 2); } return index; } private scheduleTimer() { const callback = () => { this.clearTimeout(); this.executingCallbacks = true; // Clone the current state of the queue, since it might be altered // as we invoke callbacks. const current = [...this.current]; // Invoke callbacks that were scheduled to run before the current time. const now = Date.now(); for (let i = 0; i < current.length; i += 2) { const invokeAt = current[i] as number; const callback = current[i + 1] as VoidFunction; if (invokeAt <= now) { callback(); } else { // We've reached a timer that should not be invoked yet. break; } } // The state of the queue might've changed after callbacks invocation, // run the cleanup logic based on the *current* state of the queue. let lastCallbackIndex = -1; for (let i = 0; i < this.current.length; i += 2) { const invokeAt = this.current[i] as number; if (invokeAt <= now) { // Add +1 to account for a callback function that // goes after the timestamp in events array. lastCallbackIndex = i + 1; } else { // We've reached a timer that should not be invoked yet. break; } } if (lastCallbackIndex >= 0) { arraySplice(this.current, 0, lastCallbackIndex + 1); } this.executingCallbacks = false; // If there are any callbacks added during an invocation // of the current ones - move them over to the "current" // queue. if (this.deferred.length > 0) { for (let i = 0; i < this.deferred.length; i += 2) { const invokeAt = this.deferred[i] as number; const callback = this.deferred[i + 1] as VoidFunction; this.addToQueue(this.current, invokeAt, callback); } this.deferred.length = 0; } this.scheduleTimer(); }; // Avoid running timer callbacks more than once per // average frame duration. This is needed for better // batching and to avoid kicking off excessive change // detection cycles. const FRAME_DURATION_MS = 16; // 1000ms / 60fps if (this.current.length > 0) { const now = Date.now(); // First element in the queue points at the timestamp // of the first (earliest) event. const invokeAt = this.current[0] as number; if ( this.timeoutId === null || // Reschedule a timer in case a queue contains an item with // an earlier timestamp and the delta is more than an average // frame duration. (this.invokeTimerAt && this.invokeTimerAt - invokeAt > FRAME_DURATION_MS) ) { // There was a timeout already, but an earlier event was added // into the queue. In this case we drop an old timer and setup // a new one with an updated (smaller) timeout. this.clearTimeout(); const timeout = Math.max(invokeAt - now, FRAME_DURATION_MS); this.invokeTimerAt = invokeAt; this.timeoutId = setTimeout(callback, timeout) as unknown as number; } } } private clearTimeout() { if (this.timeoutId !== null) { clearTimeout(this.timeoutId); this.timeoutId = null; } } ngOnDestroy() { this.clearTimeout(); this.current.length = 0; this.deferred.length = 0; } /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: TimerScheduler, providedIn: 'root', factory: () => new TimerScheduler(), }); }
{ "end_byte": 7692, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/timer_scheduler.ts" }
angular/packages/core/src/defer/dom_triggers.ts_0_8686
/*! * @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 {afterNextRender} from '../render3/after_render/hooks'; import type {Injector} from '../di'; import {assertLContainer, assertLView} from '../render3/assert'; import {CONTAINER_HEADER_OFFSET} from '../render3/interfaces/container'; import {TNode} from '../render3/interfaces/node'; import {isDestroyed} from '../render3/interfaces/type_checks'; import {HEADER_OFFSET, INJECTOR, LView} from '../render3/interfaces/view'; import { getNativeByIndex, removeLViewOnDestroy, storeLViewOnDestroy, walkUpViews, } from '../render3/util/view_utils'; import {assertElement, assertEqual} from '../util/assert'; import {NgZone} from '../zone'; import {storeTriggerCleanupFn} from './cleanup'; import { DEFER_BLOCK_STATE, DeferBlockInternalState, DeferBlockState, TriggerType, } from './interfaces'; import {getLDeferBlockDetails} from './utils'; /** Configuration object used to register passive and capturing events. */ const eventListenerOptions: AddEventListenerOptions = { passive: true, capture: true, }; /** Keeps track of the currently-registered `on hover` triggers. */ const hoverTriggers = new WeakMap<Element, DeferEventEntry>(); /** Keeps track of the currently-registered `on interaction` triggers. */ const interactionTriggers = new WeakMap<Element, DeferEventEntry>(); /** Currently-registered `viewport` triggers. */ const viewportTriggers = new WeakMap<Element, DeferEventEntry>(); /** Names of the events considered as interaction events. */ export const interactionEventNames = ['click', 'keydown'] as const; /** Names of the events considered as hover events. */ export const hoverEventNames = ['mouseenter', 'mouseover', 'focusin'] as const; /** `IntersectionObserver` used to observe `viewport` triggers. */ let intersectionObserver: IntersectionObserver | null = null; /** Number of elements currently observed with `viewport` triggers. */ let observedViewportElements = 0; /** Object keeping track of registered callbacks for a deferred block trigger. */ class DeferEventEntry { callbacks = new Set<VoidFunction>(); listener = () => { for (const callback of this.callbacks) { callback(); } }; } /** * Registers an interaction trigger. * @param trigger Element that is the trigger. * @param callback Callback to be invoked when the trigger is interacted with. */ export function onInteraction(trigger: Element, callback: VoidFunction): VoidFunction { let entry = interactionTriggers.get(trigger); // If this is the first entry for this element, add the listeners. if (!entry) { // Note that managing events centrally like this lends itself well to using global // event delegation. It currently does delegation at the element level, rather than the // document level, because: // 1. Global delegation is the most effective when there are a lot of events being registered // at the same time. Deferred blocks are unlikely to be used in such a way. // 2. Matching events to their target isn't free. For each `click` and `keydown` event we // would have look through all the triggers and check if the target either is the element // itself or it's contained within the element. Given that `click` and `keydown` are some // of the most common events, this may end up introducing a lot of runtime overhead. // 3. We're still registering only two events per element, no matter how many deferred blocks // are referencing it. entry = new DeferEventEntry(); interactionTriggers.set(trigger, entry); for (const name of interactionEventNames) { trigger.addEventListener(name, entry!.listener, eventListenerOptions); } } entry.callbacks.add(callback); return () => { const {callbacks, listener} = entry!; callbacks.delete(callback); if (callbacks.size === 0) { interactionTriggers.delete(trigger); for (const name of interactionEventNames) { trigger.removeEventListener(name, listener, eventListenerOptions); } } }; } /** * Registers a hover trigger. * @param trigger Element that is the trigger. * @param callback Callback to be invoked when the trigger is hovered over. */ export function onHover(trigger: Element, callback: VoidFunction): VoidFunction { let entry = hoverTriggers.get(trigger); // If this is the first entry for this element, add the listener. if (!entry) { entry = new DeferEventEntry(); hoverTriggers.set(trigger, entry); for (const name of hoverEventNames) { trigger.addEventListener(name, entry!.listener, eventListenerOptions); } } entry.callbacks.add(callback); return () => { const {callbacks, listener} = entry!; callbacks.delete(callback); if (callbacks.size === 0) { for (const name of hoverEventNames) { trigger.removeEventListener(name, listener, eventListenerOptions); } hoverTriggers.delete(trigger); } }; } /** * Registers a viewport trigger. * @param trigger Element that is the trigger. * @param callback Callback to be invoked when the trigger comes into the viewport. * @param injector Injector that can be used by the trigger to resolve DI tokens. */ export function onViewport( trigger: Element, callback: VoidFunction, injector: Injector, ): VoidFunction { const ngZone = injector.get(NgZone); let entry = viewportTriggers.get(trigger); intersectionObserver = intersectionObserver || ngZone.runOutsideAngular(() => { return new IntersectionObserver((entries) => { for (const current of entries) { // Only invoke the callbacks if the specific element is intersecting. if (current.isIntersecting && viewportTriggers.has(current.target)) { ngZone.run(viewportTriggers.get(current.target)!.listener); } } }); }); if (!entry) { entry = new DeferEventEntry(); ngZone.runOutsideAngular(() => intersectionObserver!.observe(trigger)); viewportTriggers.set(trigger, entry); observedViewportElements++; } entry.callbacks.add(callback); return () => { // It's possible that a different cleanup callback fully removed this element already. if (!viewportTriggers.has(trigger)) { return; } entry!.callbacks.delete(callback); if (entry!.callbacks.size === 0) { intersectionObserver?.unobserve(trigger); viewportTriggers.delete(trigger); observedViewportElements--; } if (observedViewportElements === 0) { intersectionObserver?.disconnect(); intersectionObserver = null; } }; } /** * Helper function to get the LView in which a deferred block's trigger is rendered. * @param deferredHostLView LView in which the deferred block is defined. * @param deferredTNode TNode defining the deferred block. * @param walkUpTimes Number of times to go up in the view hierarchy to find the trigger's view. * A negative value means that the trigger is inside the block's placeholder, while an undefined * value means that the trigger is in the same LView as the deferred block. */ export function getTriggerLView( deferredHostLView: LView, deferredTNode: TNode, walkUpTimes: number | undefined, ): LView | null { // The trigger is in the same view, we don't need to traverse. if (walkUpTimes == null) { return deferredHostLView; } // A positive value or zero means that the trigger is in a parent view. if (walkUpTimes >= 0) { return walkUpViews(walkUpTimes, deferredHostLView); } // If the value is negative, it means that the trigger is inside the placeholder. const deferredContainer = deferredHostLView[deferredTNode.index]; ngDevMode && assertLContainer(deferredContainer); const triggerLView = deferredContainer[CONTAINER_HEADER_OFFSET] ?? null; // We need to null check, because the placeholder might not have been rendered yet. if (ngDevMode && triggerLView !== null) { const lDetails = getLDeferBlockDetails(deferredHostLView, deferredTNode); const renderedState = lDetails[DEFER_BLOCK_STATE]; assertEqual( renderedState, DeferBlockState.Placeholder, 'Expected a placeholder to be rendered in this defer block.', ); assertLView(triggerLView); } return triggerLView; } /** * Gets the element that a deferred block's trigger is pointing to. * @param triggerLView LView in which the trigger is defined. * @param triggerIndex Index at which the trigger element should've been rendered. */
{ "end_byte": 8686, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/dom_triggers.ts" }
angular/packages/core/src/defer/dom_triggers.ts_8687_11913
export function getTriggerElement(triggerLView: LView, triggerIndex: number): Element { const element = getNativeByIndex(HEADER_OFFSET + triggerIndex, triggerLView); ngDevMode && assertElement(element); return element as Element; } /** * Registers a DOM-node based trigger. * @param initialLView LView in which the defer block is rendered. * @param tNode TNode representing the defer block. * @param triggerIndex Index at which to find the trigger element. * @param walkUpTimes Number of times to go up/down in the view hierarchy to find the trigger. * @param registerFn Function that will register the DOM events. * @param callback Callback to be invoked when the trigger receives the event that should render * the deferred block. * @param type Trigger type to distinguish between regular and prefetch triggers. */ export function registerDomTrigger( initialLView: LView, tNode: TNode, triggerIndex: number, walkUpTimes: number | undefined, registerFn: (element: Element, callback: VoidFunction, injector: Injector) => VoidFunction, callback: VoidFunction, type: TriggerType, ) { const injector = initialLView[INJECTOR]!; const zone = injector.get(NgZone); function pollDomTrigger() { // If the initial view was destroyed, we don't need to do anything. if (isDestroyed(initialLView)) { return; } const lDetails = getLDeferBlockDetails(initialLView, tNode); const renderedState = lDetails[DEFER_BLOCK_STATE]; // If the block was loaded before the trigger was resolved, we don't need to do anything. if ( renderedState !== DeferBlockInternalState.Initial && renderedState !== DeferBlockState.Placeholder ) { return; } const triggerLView = getTriggerLView(initialLView, tNode, walkUpTimes); // Keep polling until we resolve the trigger's LView. if (!triggerLView) { afterNextRender({read: pollDomTrigger}, {injector}); return; } // It's possible that the trigger's view was destroyed before we resolved the trigger element. if (isDestroyed(triggerLView)) { return; } const element = getTriggerElement(triggerLView, triggerIndex); const cleanup = registerFn( element, () => { // `pollDomTrigger` runs outside the zone (because of `afterNextRender`) and registers its // listeners outside the zone, so we jump back into the zone prior to running the callback. zone.run(() => { if (initialLView !== triggerLView) { removeLViewOnDestroy(triggerLView, cleanup); } callback(); }); }, injector, ); // The trigger and deferred block might be in different LViews. // For the main LView the cleanup would happen as a part of // `storeTriggerCleanupFn` logic. For trigger LView we register // a cleanup function there to remove event handlers in case an // LView gets destroyed before a trigger is invoked. if (initialLView !== triggerLView) { storeLViewOnDestroy(triggerLView, cleanup); } storeTriggerCleanupFn(type, lDetails, cleanup); } // Begin polling for the trigger. afterNextRender({read: pollDomTrigger}, {injector}); }
{ "end_byte": 11913, "start_byte": 8687, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/dom_triggers.ts" }
angular/packages/core/src/defer/idle_scheduler.ts_0_3988
/** * @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 {Injector, inject, ɵɵdefineInjectable} from '../di'; import {NgZone} from '../zone'; /** * Helper function to schedule a callback to be invoked when a browser becomes idle. * * @param callback A function to be invoked when a browser becomes idle. * @param injector injector for the app */ export function onIdle(callback: VoidFunction, injector: Injector) { const scheduler = injector.get(IdleScheduler); const cleanupFn = () => scheduler.remove(callback); scheduler.add(callback); return cleanupFn; } /** * Use shims for the `requestIdleCallback` and `cancelIdleCallback` functions for * environments where those functions are not available (e.g. Node.js and Safari). * * Note: we wrap the `requestIdleCallback` call into a function, so that it can be * overridden/mocked in test environment and picked up by the runtime code. */ const _requestIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? requestIdleCallback : setTimeout; const _cancelIdleCallback = () => typeof requestIdleCallback !== 'undefined' ? cancelIdleCallback : clearTimeout; /** * Helper service to schedule `requestIdleCallback`s for batches of defer blocks, * to avoid calling `requestIdleCallback` for each defer block (e.g. if * defer blocks are defined inside a for loop). */ export class IdleScheduler { // Indicates whether current callbacks are being invoked. executingCallbacks = false; // Currently scheduled idle callback id. idleId: number | null = null; // Set of callbacks to be invoked next. current = new Set<VoidFunction>(); // Set of callbacks collected while invoking current set of callbacks. // Those callbacks are scheduled for the next idle period. deferred = new Set<VoidFunction>(); ngZone = inject(NgZone); requestIdleCallbackFn = _requestIdleCallback().bind(globalThis); cancelIdleCallbackFn = _cancelIdleCallback().bind(globalThis); add(callback: VoidFunction) { const target = this.executingCallbacks ? this.deferred : this.current; target.add(callback); if (this.idleId === null) { this.scheduleIdleCallback(); } } remove(callback: VoidFunction) { const {current, deferred} = this; current.delete(callback); deferred.delete(callback); // If the last callback was removed and there is a pending // idle callback - cancel it. if (current.size === 0 && deferred.size === 0) { this.cancelIdleCallback(); } } private scheduleIdleCallback() { const callback = () => { this.cancelIdleCallback(); this.executingCallbacks = true; for (const callback of this.current) { callback(); } this.current.clear(); this.executingCallbacks = false; // If there are any callbacks added during an invocation // of the current ones - make them "current" and schedule // a new idle callback. if (this.deferred.size > 0) { for (const callback of this.deferred) { this.current.add(callback); } this.deferred.clear(); this.scheduleIdleCallback(); } }; // Ensure that the callback runs in the NgZone since // the `requestIdleCallback` is not currently patched by Zone.js. this.idleId = this.requestIdleCallbackFn(() => this.ngZone.run(callback)) as number; } private cancelIdleCallback() { if (this.idleId !== null) { this.cancelIdleCallbackFn(this.idleId); this.idleId = null; } } ngOnDestroy() { this.cancelIdleCallback(); this.current.clear(); this.deferred.clear(); } /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: IdleScheduler, providedIn: 'root', factory: () => new IdleScheduler(), }); }
{ "end_byte": 3988, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/idle_scheduler.ts" }
angular/packages/core/src/defer/utils.ts_0_6437
/** * @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 {assertIndexInDeclRange} from '../render3/assert'; import {DependencyDef} from '../render3/interfaces/definition'; import {TContainerNode, TNode} from '../render3/interfaces/node'; import {HEADER_OFFSET, LView, TVIEW, TView} from '../render3/interfaces/view'; import {getTNode} from '../render3/util/view_utils'; import {assertEqual, throwError} from '../util/assert'; import { DeferBlockState, DeferDependenciesLoadingState, LDeferBlockDetails, LOADING_AFTER_SLOT, MINIMUM_SLOT, TDeferBlockDetails, } from './interfaces'; /** * Calculates a data slot index for defer block info (either static or * instance-specific), given an index of a defer instruction. */ export function getDeferBlockDataIndex(deferBlockIndex: number) { // Instance state is located at the *next* position // after the defer block slot in an LView or TView.data. return deferBlockIndex + 1; } /** Retrieves a defer block state from an LView, given a TNode that represents a block. */ export function getLDeferBlockDetails(lView: LView, tNode: TNode): LDeferBlockDetails { const tView = lView[TVIEW]; const slotIndex = getDeferBlockDataIndex(tNode.index); ngDevMode && assertIndexInDeclRange(tView, slotIndex); return lView[slotIndex]; } /** Stores a defer block instance state in LView. */ export function setLDeferBlockDetails( lView: LView, deferBlockIndex: number, lDetails: LDeferBlockDetails, ) { const tView = lView[TVIEW]; const slotIndex = getDeferBlockDataIndex(deferBlockIndex); ngDevMode && assertIndexInDeclRange(tView, slotIndex); lView[slotIndex] = lDetails; } /** Retrieves static info about a defer block, given a TView and a TNode that represents a block. */ export function getTDeferBlockDetails(tView: TView, tNode: TNode): TDeferBlockDetails { const slotIndex = getDeferBlockDataIndex(tNode.index); ngDevMode && assertIndexInDeclRange(tView, slotIndex); return tView.data[slotIndex] as TDeferBlockDetails; } /** Stores a defer block static info in `TView.data`. */ export function setTDeferBlockDetails( tView: TView, deferBlockIndex: number, deferBlockConfig: TDeferBlockDetails, ) { const slotIndex = getDeferBlockDataIndex(deferBlockIndex); ngDevMode && assertIndexInDeclRange(tView, slotIndex); tView.data[slotIndex] = deferBlockConfig; } export function getTemplateIndexForState( newState: DeferBlockState, hostLView: LView, tNode: TNode, ): number | null { const tView = hostLView[TVIEW]; const tDetails = getTDeferBlockDetails(tView, tNode); switch (newState) { case DeferBlockState.Complete: return tDetails.primaryTmplIndex; case DeferBlockState.Loading: return tDetails.loadingTmplIndex; case DeferBlockState.Error: return tDetails.errorTmplIndex; case DeferBlockState.Placeholder: return tDetails.placeholderTmplIndex; default: ngDevMode && throwError(`Unexpected defer block state: ${newState}`); return null; } } /** * Returns a minimum amount of time that a given state should be rendered for, * taking into account `minimum` parameter value. If the `minimum` value is * not specified - returns `null`. */ export function getMinimumDurationForState( tDetails: TDeferBlockDetails, currentState: DeferBlockState, ): number | null { if (currentState === DeferBlockState.Placeholder) { return tDetails.placeholderBlockConfig?.[MINIMUM_SLOT] ?? null; } else if (currentState === DeferBlockState.Loading) { return tDetails.loadingBlockConfig?.[MINIMUM_SLOT] ?? null; } return null; } /** Retrieves the value of the `after` parameter on the @loading block. */ export function getLoadingBlockAfter(tDetails: TDeferBlockDetails): number | null { return tDetails.loadingBlockConfig?.[LOADING_AFTER_SLOT] ?? null; } /** * Adds downloaded dependencies into a directive or a pipe registry, * making sure that a dependency doesn't yet exist in the registry. */ export function addDepsToRegistry<T extends DependencyDef[]>(currentDeps: T | null, newDeps: T): T { if (!currentDeps || currentDeps.length === 0) { return newDeps; } const currentDepSet = new Set(currentDeps); for (const dep of newDeps) { currentDepSet.add(dep); } // If `currentDeps` is the same length, there were no new deps and can // return the original array. return currentDeps.length === currentDepSet.size ? currentDeps : (Array.from(currentDepSet) as T); } /** Retrieves a TNode that represents main content of a defer block. */ export function getPrimaryBlockTNode(tView: TView, tDetails: TDeferBlockDetails): TContainerNode { const adjustedIndex = tDetails.primaryTmplIndex + HEADER_OFFSET; return getTNode(tView, adjustedIndex) as TContainerNode; } /** * Asserts whether all dependencies for a defer block are loaded. * Always run this function (in dev mode) before rendering a defer * block in completed state. */ export function assertDeferredDependenciesLoaded(tDetails: TDeferBlockDetails) { assertEqual( tDetails.loadingState, DeferDependenciesLoadingState.COMPLETE, 'Expecting all deferred dependencies to be loaded.', ); } /** * Determines if a given value matches the expected structure of a defer block * * We can safely rely on the primaryTmplIndex because every defer block requires * that a primary template exists. All the other template options are optional. */ export function isTDeferBlockDetails(value: unknown): value is TDeferBlockDetails { return ( value !== null && typeof value === 'object' && typeof (value as TDeferBlockDetails).primaryTmplIndex === 'number' ); } /** * Whether a given TNode represents a defer block. */ export function isDeferBlock(tView: TView, tNode: TNode): boolean { let tDetails: TDeferBlockDetails | null = null; const slotIndex = getDeferBlockDataIndex(tNode.index); // Check if a slot index is in the reasonable range. // Note: we do `-1` on the right border, since defer block details are stored // in the `n+1` slot, see `getDeferBlockDataIndex` for more info. if (HEADER_OFFSET < slotIndex && slotIndex < tView.bindingStartIndex) { tDetails = getTDeferBlockDetails(tView, tNode); } return !!tDetails && isTDeferBlockDetails(tDetails); }
{ "end_byte": 6437, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/utils.ts" }
angular/packages/core/src/defer/cleanup.ts_0_2124
/*! * @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 {Injector} from '../di'; import { HYDRATE_TRIGGER_CLEANUP_FNS, LDeferBlockDetails, PREFETCH_TRIGGER_CLEANUP_FNS, TRIGGER_CLEANUP_FNS, TriggerType, SSR_UNIQUE_ID, } from './interfaces'; import {DeferBlockRegistry} from './registry'; /** * Registers a cleanup function associated with a prefetching trigger * or a regular trigger of a defer block. */ export function storeTriggerCleanupFn( type: TriggerType, lDetails: LDeferBlockDetails, cleanupFn: VoidFunction, ) { const key = getCleanupFnKeyByType(type); if (lDetails[key] === null) { lDetails[key] = []; } (lDetails[key]! as VoidFunction[]).push(cleanupFn); } /** * Invokes registered cleanup functions either for prefetch or for regular triggers. */ export function invokeTriggerCleanupFns(type: TriggerType, lDetails: LDeferBlockDetails) { const key = getCleanupFnKeyByType(type); const cleanupFns = lDetails[key] as VoidFunction[]; if (cleanupFns !== null) { for (const cleanupFn of cleanupFns) { cleanupFn(); } lDetails[key] = null; } } /** * Invokes registered cleanup functions for both prefetch and regular triggers. */ export function invokeAllTriggerCleanupFns( lDetails: LDeferBlockDetails, registry: DeferBlockRegistry | null, ) { // TODO(incremental-hydration): cleanup functions are invoked in multiple places // should we centralize where cleanup functions are invoked to this registry? if (registry !== null) { registry.invokeCleanupFns(lDetails[SSR_UNIQUE_ID]!); } invokeTriggerCleanupFns(TriggerType.Prefetch, lDetails); invokeTriggerCleanupFns(TriggerType.Regular, lDetails); } function getCleanupFnKeyByType(type: TriggerType): number { let key = TRIGGER_CLEANUP_FNS; if (type === TriggerType.Prefetch) { key = PREFETCH_TRIGGER_CLEANUP_FNS; } else if (type === TriggerType.Hydrate) { key = HYDRATE_TRIGGER_CLEANUP_FNS; } return key; }
{ "end_byte": 2124, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/cleanup.ts" }
angular/packages/core/src/defer/instructions.ts_0_7647
/** * @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 {setActiveConsumer} from '@angular/core/primitives/signals'; import {CachedInjectorService} from '../cached_injector_service'; import {NotificationSource} from '../change_detection/scheduling/zoneless_scheduling'; import {EnvironmentInjector, InjectionToken, Injector, Provider} from '../di'; import {internalImportProvidersFrom} from '../di/provider_collection'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import { DEFER_BLOCK_ID, DEFER_BLOCK_STATE as SERIALIZED_DEFER_BLOCK_STATE, DehydratedContainerView, } from '../hydration/interfaces'; import {populateDehydratedViewsInLContainer} from '../linker/view_container_ref'; import {PendingTasksInternal} from '../pending_tasks'; import {assertLContainer, assertTNodeForLView} from '../render3/assert'; import {bindingUpdated} from '../render3/bindings'; import {ChainedInjector} from '../render3/chained_injector'; import {getComponentDef, getDirectiveDef, getPipeDef} from '../render3/def_getters'; import {getTemplateLocationDetails} from '../render3/instructions/element_validation'; import {markViewDirty} from '../render3/instructions/mark_view_dirty'; import {handleError} from '../render3/instructions/shared'; import {declareTemplate} from '../render3/instructions/template'; import {DEHYDRATED_VIEWS, 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 {performanceMarkFeature} 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, DeferBlockTrigger, LDeferBlockDetails, LOADING_AFTER_CLEANUP_FN, NEXT_DEFER_BLOCK_STATE, ON_COMPLETE_FNS, SSR_BLOCK_STATE, STATE_IS_FROZEN_UNTIL, TDeferBlockDetails, TriggerType, DeferBlock, SSR_UNIQUE_ID, } from './interfaces'; import {onTimer, scheduleTimerTrigger} from './timer_scheduler'; import { addDepsToRegistry, assertDeferredDependenciesLoaded, getLDeferBlockDetails, getLoadingBlockAfter, getMinimumDurationForState, getPrimaryBlockTNode, getTDeferBlockDetails, getTemplateIndexForState, setLDeferBlockDetails, setTDeferBlockDetails, } from './utils'; import {DeferBlockRegistry} from './registry'; import {incrementallyHydrateFromBlockName} from '../hydration/blocks'; import {isIncrementalHydrationEnabled} from '../hydration/utils'; /** * **INTERNAL**, avoid referencing it in application code. * * * Injector token that allows to provide `DeferBlockDependencyInterceptor` class * implementation. * * This token is only injected in devMode */ 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' : '', ); /** * Determines whether defer blocks should be fully rendered through on the server side * for incremental hydration. */ function shouldTriggerWhenOnServer(injector: Injector) { return !isPlatformBrowser(injector) && isIncrementalHydrationEnabled(injector); } // TODO(incremental-hydration): Optimize this further by moving the calculation to earlier // in the process. Consider a flag we can check similar to LView[FLAGS]. /** * Determines whether regular defer block triggers should be invoked based on client state * and whether incremental hydration is enabled. Hydrate triggers are invoked elsewhere. */ function shouldTriggerWhenOnClient( injector: Injector, lDetails: LDeferBlockDetails, tDetails: TDeferBlockDetails, ): boolean { if (!isPlatformBrowser(injector)) { return false; } const isServerRendered = lDetails[SSR_BLOCK_STATE] && lDetails[SSR_BLOCK_STATE] === DeferBlockState.Complete; const hasHydrateTriggers = tDetails.hydrateTriggers && tDetails.hydrateTriggers.size > 0; if (hasHydrateTriggers && isServerRendered && isIncrementalHydrationEnabled(injector)) { return false; } return true; } /** * 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, tDeferBlockDetails: TDeferBlockDetails, ): boolean { const config = injector.get(DEFER_BLOCK_CONFIG, null, {optional: true}); if (config?.behavior === DeferBlockBehavior.Manual) { return false; } return isPlatformBrowser(injector) || tDeferBlockDetails.hydrateTriggers !== null; } function getHydrateTriggers(tView: TView, tNode: TNode): Map<DeferBlockTrigger, number | null> { const tDetails = getTDeferBlockDetails(tView, tNode); return (tDetails.hydrateTriggers ??= new Map()); } function getPrefetchTriggers(tDetails: TDeferBlockDetails): Set<DeferBlockTrigger> { return (tDetails.prefetchTriggers ??= new Set()); } /** * 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; } } /*
{ "end_byte": 7647, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_7649_15641
* 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; const tNode = declareTemplate(lView, tView, index, null, 0, 0); const injector = lView[INJECTOR]!; if (tView.firstCreatePass) { performanceMarkFeature('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, providers: null, hydrateTriggers: null, prefetchTriggers: null, }; enableTimerScheduling?.(tView, tDetails, placeholderConfigIndex, loadingConfigIndex); setTDeferBlockDetails(tView, adjustedIndex, tDetails); } 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); let ssrBlockState = null; let ssrUniqueId: string | null = null; if (lContainer[DEHYDRATED_VIEWS]?.length > 0) { const info = lContainer[DEHYDRATED_VIEWS][0].data; ssrUniqueId = info[DEFER_BLOCK_ID] ?? null; ssrBlockState = info[SERIALIZED_DEFER_BLOCK_STATE]; } // 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 ssrUniqueId, // SSR_UNIQUE_ID ssrBlockState, // SSR_BLOCK_STATE null, // ON_COMPLETE_FNS null, // HYDRATE_TRIGGER_CLEANUP_FNS ]; setLDeferBlockDetails(lView, adjustedIndex, lDetails); let registry: DeferBlockRegistry | null = null; if (ssrUniqueId !== null) { // TODO(incremental-hydration): explore how we can make // `DeferBlockRegistry` tree-shakable for client-only cases. registry = injector.get(DeferBlockRegistry); // Also store this defer block in the registry. registry.add(ssrUniqueId, {lView, tNode, lContainer}); } const cleanupTriggersFn = () => invokeAllTriggerCleanupFns(lDetails, registry); // 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 tDetails = getTDeferBlockDetails(lView[TVIEW], 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) && shouldTriggerWhenOnClient(lView[INJECTOR]!, lDetails, tDetails) ) { // 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 tNode = getSelectedTNode(); const bindingIndex = nextBindingIndex(); const prefetchTriggers = getPrefetchTriggers(getTDeferBlockDetails(getTView(), tNode)); prefetchTriggers.add(DeferBlockTrigger.When); 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); } } } /** * Hydrates the deferred content when a value becomes truthy. * @codeGenApi */ export function ɵɵdeferHydrateWhen(rawValue: unknown) { const lView = getLView(); // TODO(incremental-hydration): audit all defer instructions to reduce unnecessary work by // moving function calls inside their relevant control flow blocks const bindingIndex = nextBindingIndex(); const tNode = getSelectedTNode(); const tView = getTView(); const hydrateTriggers = getHydrateTriggers(tView, tNode); hydrateTriggers.set(DeferBlockTrigger.When, null); if (bindingUpdated(lView, bindingIndex, rawValue)) { const injector = lView[INJECTOR]!; if (shouldTriggerWhenOnServer(injector)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } else { try { const value = Boolean(rawValue); // handle truthy or falsy values if (value === true) { // 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. incrementallyHydrateFromBlockName( injector, getLDeferBlockDetails(lView, tNode)[SSR_UNIQUE_ID]!, (deferBlock: DeferBlock) => triggerAndWaitForCompletion(deferBlock), ); } } finally { const prevConsumer = setActiveConsumer(null); setActiveConsumer(prevConsumer); } } } } /** * Speci
{ "end_byte": 15641, "start_byte": 7649, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_15643_22766
es that hydration never occurs. * @codeGenApi */ export function ɵɵdeferHydrateNever() { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Never, null); if (shouldTriggerWhenOnServer(lView[INJECTOR]!)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } } /** * 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, DeferBlockTrigger.Idle); } /** * Sets up logic to handle the `on idle` deferred trigger. * @codeGenApi */ export function ɵɵdeferHydrateOnIdle() { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Idle, null); if (shouldTriggerWhenOnServer(lView[INJECTOR]!)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } else { scheduleDelayedHydrating(onIdle, lView, tNode); } } /** * 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 injector = lView[INJECTOR]!; const tDetails = getTDeferBlockDetails(tView, tNode); const lDetails = getLDeferBlockDetails(lView, tNode); // Render placeholder block only if loading template is not present and we're on // the client to avoid content flickering, since it would be immediately replaced // by the loading block. if (!shouldTriggerDeferBlock(injector, tDetails) || tDetails.loadingTmplIndex === null) { renderPlaceholder(lView, tNode); } if (shouldTriggerWhenOnClient(injector, lDetails, tDetails)) { 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); const prefetchTriggers = getPrefetchTriggers(tDetails); prefetchTriggers.add(DeferBlockTrigger.Immediate); if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) { triggerResourceLoading(tDetails, lView, tNode); } } /** * Sets up logic to handle the `on immediate` hydrate trigger. * @codeGenApi */ export function ɵɵdeferHydrateOnImmediate() { const lView = getLView(); const tNode = getCurrentTNode()!; const injector = lView[INJECTOR]!; const lDetails = getLDeferBlockDetails(lView, tNode); const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Immediate, null); if (shouldTriggerWhenOnServer(injector)) { triggerDeferBlock(lView, tNode); } else { incrementallyHydrateFromBlockName( injector, lDetails[SSR_UNIQUE_ID]!, (deferBlock: DeferBlock) => triggerAndWaitForCompletion(deferBlock), ); } } /** * 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), DeferBlockTrigger.Timer); } /** * Creates runtime data structures for the `on timer` hydrate trigger. * @param delay Amount of time to wait before loading the content. * @codeGenApi */ export function ɵɵdeferHydrateOnTimer(delay: number) { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Timer, delay); if (shouldTriggerWhenOnServer(lView[INJECTOR]!)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } else { scheduleDelayedHydrating(onTimer(delay), lView, tNode); } } /** * 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()!; const lDetails = getLDeferBlockDetails(lView, tNode); const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode); renderPlaceholder(lView, tNode); if (shouldTriggerWhenOnClient(lView[INJECTOR]!, lDetails, tDetails)) { 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); const prefetchTriggers = getPrefetchTriggers(tDetails); prefetchTriggers.add(DeferBlockTrigger.Hover); 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 hover` hydrate trigger. * @codeGenApi */ export function ɵɵdeferHydrateOnHover() { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Hover, null); if (shouldTriggerWhenOnServer(lView[INJECTOR]!)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } // The actual triggering of hydration on hover is handled by JSAction in // event_replay.ts. } /** * 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(tr
{ "end_byte": 22766, "start_byte": 15643, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_22767_29996
ggerIndex: number, walkUpTimes?: number) { const lView = getLView(); const tNode = getCurrentTNode()!; const lDetails = getLDeferBlockDetails(lView, tNode); const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode); renderPlaceholder(lView, tNode); if (shouldTriggerWhenOnClient(lView[INJECTOR]!, lDetails, tDetails)) { 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); const prefetchTriggers = getPrefetchTriggers(tDetails); prefetchTriggers.add(DeferBlockTrigger.Interaction); 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 interaction` hydrate trigger. * @codeGenApi */ export function ɵɵdeferHydrateOnInteraction() { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Interaction, null); if (shouldTriggerWhenOnServer(lView[INJECTOR]!)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } // The actual triggering of hydration on interaction is handled by JSAction in // event_replay.ts. } /** * 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()!; const lDetails = getLDeferBlockDetails(lView, tNode); const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode); renderPlaceholder(lView, tNode); if (shouldTriggerWhenOnClient(lView[INJECTOR]!, lDetails, tDetails)) { 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); const prefetchTriggers = getPrefetchTriggers(tDetails); prefetchTriggers.add(DeferBlockTrigger.Viewport); if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) { registerDomTrigger( lView, tNode, triggerIndex, walkUpTimes, onViewport, () => triggerPrefetching(tDetails, lView, tNode), TriggerType.Prefetch, ); } } /** * Creates runtime data structures for the `on viewport` hydrate trigger. * @codeGenApi */ export function ɵɵdeferHydrateOnViewport() { const lView = getLView(); const tNode = getCurrentTNode()!; const hydrateTriggers = getHydrateTriggers(getTView(), tNode); hydrateTriggers.set(DeferBlockTrigger.Viewport, null); const injector = lView[INJECTOR]!; if (shouldTriggerWhenOnServer(injector)) { // We are on the server and SSR for defer blocks is enabled. triggerDeferBlock(lView, tNode); } // The actual triggering of hydration on viewport happens in incremental.ts, // since these instructions won't exist for dehydrated content. } /********** Helper functions **********/ /** * Schedules triggering of a defer block for `on idle` and `on timer` conditions. */ function scheduleDelayedTrigger( scheduleFn: (callback: VoidFunction, injector: Injector) => VoidFunction, ) { const lView = getLView(); const tNode = getCurrentTNode()!; const injector = lView[INJECTOR]!; const lDetails = getLDeferBlockDetails(lView, tNode); const tDetails = getTDeferBlockDetails(lView[TVIEW], tNode); renderPlaceholder(lView, tNode); if (shouldTriggerWhenOnClient(lView[INJECTOR]!, lDetails, tDetails)) { // Only trigger the scheduled trigger on the browser // since we don't want to delay the server response. const cleanupFn = scheduleFn(() => triggerDeferBlock(lView, tNode), injector); 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, injector: Injector) => VoidFunction, trigger: DeferBlockTrigger, ) { const lView = getLView(); const injector = lView[INJECTOR]!; // Only trigger the scheduled trigger on the browser // since we don't want to delay the server response. if (isPlatformBrowser(injector)) { const tNode = getCurrentTNode()!; const tView = lView[TVIEW]; const tDetails = getTDeferBlockDetails(tView, tNode); const prefetchTriggers = getPrefetchTriggers(tDetails); prefetchTriggers.add(trigger); if (tDetails.loadingState === DeferDependenciesLoadingState.NOT_STARTED) { const lDetails = getLDeferBlockDetails(lView, tNode); const prefetch = () => triggerPrefetching(tDetails, lView, tNode); const cleanupFn = scheduleFn(prefetch, injector); storeTriggerCleanupFn(TriggerType.Prefetch, lDetails, cleanupFn); } } } /** * Schedules hydration triggering of a defer block for `on idle` and `on timer` conditions. */ export function scheduleDelayedHydrating( scheduleFn: (callback: VoidFunction, injector: Injector) => VoidFunction, lView: LView, tNode: TNode, ) { // Only trigger the scheduled trigger on the browser // since we don't want to delay the server response. const injector = lView[INJECTOR]!; if (isPlatformBrowser(injector)) { const lDetails = getLDeferBlockDetails(lView, tNode); const cleanupFn = scheduleFn( () => incrementallyHydrateFromBlockName( injector, lDetails[SSR_UNIQUE_ID]!, (deferBlock: DeferBlock) => triggerAndWaitForCompletion(deferBlock), ), injector, ); storeTriggerCleanupFn(TriggerType.Hydrate, lDetails, cleanupFn); } } /** * Transitions a defer block to the new state.
{ "end_byte": 29996, "start_byte": 22767, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_29998_36233
pdates 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]; const ssrState = lDetails[SSR_BLOCK_STATE]; if (ssrState !== null && newState < ssrState) { return; // trying to render a previous state, exit } if ( isValidStateChange(currentState, newState) && isValidStateChange(lDetails[NEXT_DEFER_BLOCK_STATE] ?? -1, newState) ) { const injector = hostLView[INJECTOR]!; const tDetails = getTDeferBlockDetails(hostTView, tNode); // Skips scheduling on the server since it can delay the server response. const needsScheduling = !skipTimerScheduling && isPlatformBrowser(injector) && (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); } } } /** * Checks whether there is a cached injector associated with a given defer block * declaration and returns if it exists. If there is no cached injector present - * creates a new injector and stores in the cache. */ function getOrCreateEnvironmentInjector( parentInjector: Injector, tDetails: TDeferBlockDetails, providers: Provider[], ) { return parentInjector .get(CachedInjectorService) .getOrCreateInjector( tDetails, parentInjector as EnvironmentInjector, providers, ngDevMode ? 'DeferBlock Injector' : '', ); } /** * Creates a new injector, which contains providers collected from dependencies (NgModules) of * defer-loaded components. This function detects different types of parent injectors and creates * a new injector based on that. */ function createDeferBlockInjector( parentInjector: Injector, tDetails: TDeferBlockDetails, providers: Provider[], ) { // Check if the parent injector is an instance of a `ChainedInjector`. // // In this case, we retain the shape of the injector and use a newly created // `EnvironmentInjector` as a parent in the `ChainedInjector`. That is needed to // make sure that the primary injector gets consulted first (since it's typically // a NodeInjector) and `EnvironmentInjector` tree is consulted after that. if (parentInjector instanceof ChainedInjector) { const origInjector = parentInjector.injector; // Guaranteed to be an environment injector const parentEnvInjector = parentInjector.parentInjector; const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers); return new ChainedInjector(origInjector, envInjector); } const parentEnvInjector = parentInjector.get(EnvironmentInjector); // If the `parentInjector` is *not* an `EnvironmentInjector` - we need to create // a new `ChainedInjector` with the following setup: // // - the provided `parentInjector` becomes a primary injector // - an existing (real) `EnvironmentInjector` becomes a parent injector for // a newly-created one, which contains extra providers // // So the final order in which injectors would be consulted in this case would look like this: // // 1. Provided `parentInjector` // 2. Newly-created `EnvironmentInjector` with extra providers // 3. `EnvironmentInjector` from the `parentInjector` if (parentEnvInjector !== parentInjector) { const envInjector = getOrCreateEnvironmentInjector(parentEnvInjector, tDetails, providers); return new ChainedInjector(parentInjector, envInjector); } // The `parentInjector` is an instance of an `EnvironmentInjector`. // No need for special handling, we can use `parentInjector` as a // parent injector directly. return getOrCreateEnvironmentInjector(parentInjector, tDetails, providers); } function findMatchingDehydratedViewForDeferBlock( lContainer: LContainer, lDetails: LDeferBlockDetails, ): DehydratedContainerView | null { // TODO(incremental-hydration): extract into a separate util function and use in relevant places. const views = lContainer[DEHYDRATED_VIEWS]; if (views === null || views.length === 0) { return null; } // Find matching view based on serialized defer block state. // TODO(incremental-hydration): reconcile this logic with the regular logic that looks up // dehydrated views to see if there is anything missing in this function. return ( views.find( (view: any) => view.data[SERIALIZED_DEFER_BLOCK_STATE] === lDetails[DEFER_BLOCK_STATE], ) ?? null ); } /** * Applies changes to the DOM to reflect a given state. */ function applyDeferBlockState( newState: DeferBlo
{ "end_byte": 36233, "start_byte": 29998, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_36234_43880
kState, 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; // The TNode that represents a template that will activated in the defer block const activeBlockTNode = 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); let injector: Injector | undefined; if (newState === DeferBlockState.Complete) { // When we render a defer block in completed state, there might be // newly loaded standalone components used within the block, which may // import NgModules with providers. In order to make those providers // available for components declared in that NgModule, we create an instance // of an environment injector to host those providers and pass this injector // to the logic that creates a view. const tDetails = getTDeferBlockDetails(hostTView, tNode); const providers = tDetails.providers; if (providers && providers.length > 0) { injector = createDeferBlockInjector(hostLView[INJECTOR]!, tDetails, providers); } } const dehydratedView = findMatchingDehydratedViewForDeferBlock(lContainer, lDetails); // Render either when we don't have dehydrated views at all (e.g. client rendering) // or when dehydrated view is found (in which case we hydrate). // Otherwise, do nothing, since we'd end up erasing SSR'ed content. // TODO(incremental-hydration): Use the util function for checking dehydrated views mentioned above const isClientOnly = lContainer[DEHYDRATED_VIEWS] === null || lContainer[DEHYDRATED_VIEWS].length === 0; if (isClientOnly || dehydratedView) { // Erase dehydrated view info, so that it's not removed later // by post-hydration cleanup process. // TODO(incremental-hydration): we need a better mechanism here. lContainer[DEHYDRATED_VIEWS] = null; const embeddedLView = createAndRenderEmbeddedLView(hostLView, activeBlockTNode, null, { injector, dehydratedView, }); addLViewToLContainer( lContainer, embeddedLView, viewIndex, shouldAddViewToDom(activeBlockTNode, dehydratedView), ); markViewDirty(embeddedLView, NotificationSource.DeferBlockStateUpdate); } // TODO(incremental-hydration): // - what if we had some views in `lContainer[DEHYDRATED_VIEWS]`, but // we didn't find a view that matches the expected state? // - for example, handle a situation when a block was in the "completed" state // on the server, but the loading failing on the client. How do we reconcile and cleanup? // TODO(incremental-hydration): should we also invoke if newState === DeferBlockState.Error? if (newState === DeferBlockState.Complete && Array.isArray(lDetails[ON_COMPLETE_FNS])) { for (const callback of lDetails[ON_COMPLETE_FNS]) { callback(); } lDetails[ON_COMPLETE_FNS] = null; } } if (newState === DeferBlockState.Complete && Array.isArray(lDetails[ON_COMPLETE_FNS])) { for (const callback of lDetails[ON_COMPLETE_FNS]) { callback(); } lDetails[ON_COMPLETE_FNS] = null; } } /** * 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[INJECTOR]!); } /** * 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) { const tDeferBlockDetails = getTDeferBlockDetails(lView[TVIEW], tNode); if (lView[INJECTOR] && shouldTriggerDeferBlock(lView[INJECTOR]!, tDeferBlockDetails)) { triggerResourceLoading(tDetails, lView, tNode); } } /** * Trigger loading of defer block dependencies
{ "end_byte": 43880, "start_byte": 36234, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_43882_52413
f 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, ): Promise<unknown> { 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 tDetails.loadingPromise ?? Promise.resolve(); } 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); } } // Indicate that an application is not stable and has a pending task. const pendingTasks = injector.get(PendingTasksInternal); const taskId = pendingTasks.add(); // The `dependenciesFn` might be `null` when all dependencies within // a given defer block were eagerly referenced elsewhere in a file, // thus no dynamic `import()`s were produced. if (!dependenciesFn) { tDetails.loadingPromise = Promise.resolve().then(() => { tDetails.loadingPromise = null; tDetails.loadingState = DeferDependenciesLoadingState.COMPLETE; pendingTasks.remove(taskId); }); return tDetails.loadingPromise; } // 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 the loading Promise // and a pending task should also be removed. tDetails.loadingPromise = null; pendingTasks.remove(taskId); if (failed) { tDetails.loadingState = DeferDependenciesLoadingState.FAILED; if (tDetails.errorTmplIndex === null) { const templateLocation = ngDevMode ? 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, ); // Extract providers from all NgModules imported by standalone components // used within this defer block. const directiveTypes = directiveDefs.map((def) => def.type); const providers = internalImportProvidersFrom(false, ...directiveTypes); tDetails.providers = providers; } if (pipeDefs.length > 0) { primaryBlockTView.pipeRegistry = addDepsToRegistry<PipeDefList>( primaryBlockTView.pipeRegistry, pipeDefs, ); } } }); return tDetails.loadingPromise; } /** 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. */ export function triggerDeferBlock(lView: LView, tNode: TNode) { const tView = lView[TVIEW]; const lContainer = lView[tNode.index]; const injector = lView[INJECTOR]!; ngDevMode && assertLContainer(lContainer); const lDetails = getLDeferBlockDetails(lView, tNode); const tDetails = getTDeferBlockDetails(tView, tNode); if (!shouldTriggerDeferBlock(injector, tDetails)) return; let registry: DeferBlockRegistry | null = null; if (isIncrementalHydrationEnabled(injector)) { registry = injector.get(DeferBlockRegistry); } // Defer block is triggered, cleanup all registered trigger functions. invokeAllTriggerCleanupFns(lDetails, registry); 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'); } } } /** * Triggers the resource loading for a defer block and passes back a promise * to handle cleanup on completion */ export function triggerAndWaitForCompletion(deferBlock: DeferBlock): Promise<void> { const lDetails = getLDeferBlockDetails(deferBlock.lView, deferBlock.tNode); const promise = new Promise<void>((resolve) => { onDeferBlockCompletion(lDetails, resolve); }); triggerDeferBlock(deferBlock.lView, deferBlock.tNode); return promise; } /** * Registers cleanup functions for a defer block when the block has finished * fetching and rendering */ function onDeferBlockCompletion(lDetails: LDeferBlo
{ "end_byte": 52413, "start_byte": 43882, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/instructions.ts_52414_52638
kDetails, callback: VoidFunction) { if (!Array.isArray(lDetails[ON_COMPLETE_FNS])) { lDetails[ON_COMPLETE_FNS] = []; } lDetails[ON_COMPLETE_FNS].push(callback); }
{ "end_byte": 52638, "start_byte": 52414, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/instructions.ts" }
angular/packages/core/src/defer/registry.ts_0_2227
/** * @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 {ɵɵdefineInjectable} from '../di'; import {DeferBlock} from './interfaces'; // TODO(incremental-hydration): refactor this so that it's not used in CSR cases /** * The DeferBlockRegistry is used for incremental hydration purposes. It keeps * track of the Defer Blocks that need hydration so we can effectively * navigate up to the top dehydrated defer block and fire appropriate cleanup * functions post hydration. */ export class DeferBlockRegistry { private registry = new Map<string, DeferBlock>(); private cleanupFns = new Map<string, Function[]>(); add(blockId: string, info: DeferBlock) { this.registry.set(blockId, info); } get(blockId: string): DeferBlock | null { return this.registry.get(blockId) ?? null; } // TODO(incremental-hydration): we need to determine when this should be invoked // to prevent leaking memory in SSR cases remove(blockId: string) { this.registry.delete(blockId); } get size(): number { return this.registry.size; } addCleanupFn(blockId: string, fn: Function) { let cleanupFunctions: Function[] = []; if (this.cleanupFns.has(blockId)) { cleanupFunctions = this.cleanupFns.get(blockId)!; } cleanupFunctions.push(fn); this.cleanupFns.set(blockId, cleanupFunctions); } invokeCleanupFns(blockId: string) { // TODO(incremental-hydration): determine if we can safely remove entries from // the cleanupFns after they've been invoked. Can we reset // `this.cleanupFns.get(blockId)`? const fns = this.cleanupFns.get(blockId) ?? []; for (let fn of fns) { fn(); } } // Blocks that are being hydrated. // TODO(incremental-hydration): cleanup task - we currently retain ids post hydration // and need to determine when we can remove them. hydrating = new Set(); /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: DeferBlockRegistry, providedIn: 'root', factory: () => new DeferBlockRegistry(), }); }
{ "end_byte": 2227, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/registry.ts" }
angular/packages/core/src/defer/discovery.ts_0_2114
/** * @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 {CONTAINER_HEADER_OFFSET} from '../render3/interfaces/container'; import {TNode} from '../render3/interfaces/node'; import {isLContainer, isLView} from '../render3/interfaces/type_checks'; import {HEADER_OFFSET, LView, TVIEW} from '../render3/interfaces/view'; import {DeferBlock, TDeferBlockDetails} from './interfaces'; import {getTDeferBlockDetails, isTDeferBlockDetails} from './utils'; /** * Defer block instance for testing. */ export interface DeferBlockDetails extends DeferBlock { tDetails: TDeferBlockDetails; } /** * Retrieves all defer blocks in a given LView. * * @param lView lView with defer blocks * @param deferBlocks defer block aggregator array */ export function getDeferBlocks(lView: LView, deferBlocks: DeferBlockDetails[]) { const tView = lView[TVIEW]; for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { if (isLContainer(lView[i])) { const lContainer = lView[i]; // An LContainer may represent an instance of a defer block, in which case // we store it as a result. Otherwise, keep iterating over LContainer views and // look for defer blocks. const isLast = i === tView.bindingStartIndex - 1; if (!isLast) { const tNode = tView.data[i] as TNode; const tDetails = getTDeferBlockDetails(tView, tNode); if (isTDeferBlockDetails(tDetails)) { deferBlocks.push({lContainer, lView, tNode, tDetails}); // This LContainer represents a defer block, so we exit // this iteration and don't inspect views in this LContainer. continue; } } for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) { getDeferBlocks(lContainer[i] as LView, deferBlocks); } } else if (isLView(lView[i])) { // This is a component, enter the `getDeferBlocks` recursively. getDeferBlocks(lView[i], deferBlocks); } } }
{ "end_byte": 2114, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/discovery.ts" }
angular/packages/core/src/defer/interfaces.ts_0_8068
/** * @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 {Provider} from '../di/interface/provider'; import type {LContainer} from '../render3/interfaces/container'; import type {DependencyType} from '../render3/interfaces/definition'; import type {TNode} from '../render3/interfaces/node'; import type {LView} from '../render3/interfaces/view'; // TODO(incremental-hydration): This interface should be renamed to better // reflect what it does. DeferBlock is to generic /** * Basic set of data structures used for identifying a defer block * and triggering defer blocks */ export interface DeferBlock { lView: LView; tNode: TNode; lContainer: LContainer; } /** * Describes the shape of a function generated by the compiler * to download dependencies that can be defer-loaded. */ export type DependencyResolverFn = () => Array<Promise<DependencyType>>; /** * Defines types of defer block triggers. */ export const enum TriggerType { /** * Represents regular triggers (e.g. `@defer (on idle) { ... }`). */ Regular, /** * Represents prefetch triggers (e.g. `@defer (prefetch on idle) { ... }`). */ Prefetch, /** * Represents hydrate triggers (e.g. `@defer (hydrate on idle) { ... }`). */ Hydrate, } /** * Describes the state of defer block dependency loading. */ export enum DeferDependenciesLoadingState { /** Initial state, dependency loading is not yet triggered */ NOT_STARTED, /** Dependency loading is in progress */ IN_PROGRESS, /** Dependency loading has completed successfully */ COMPLETE, /** Dependency loading has failed */ FAILED, } /** Slot index where `minimum` parameter value is stored. */ export const MINIMUM_SLOT = 0; /** Slot index where `after` parameter value is stored. */ export const LOADING_AFTER_SLOT = 1; /** Configuration object for a loading block as it is stored in the component constants. */ export type DeferredLoadingBlockConfig = [minimumTime: number | null, afterTime: number | null]; /** Configuration object for a placeholder block as it is stored in the component constants. */ export type DeferredPlaceholderBlockConfig = [minimumTime: number | null]; /** * Describes the data shared across all instances of a defer block. */ export interface TDeferBlockDetails { /** * Index in an LView and TData arrays where a template for the primary content * can be found. */ primaryTmplIndex: number; /** * Index in an LView and TData arrays where a template for the loading block can be found. */ loadingTmplIndex: number | null; /** * Extra configuration parameters (such as `after` and `minimum`) for the loading block. */ loadingBlockConfig: DeferredLoadingBlockConfig | null; /** * Index in an LView and TData arrays where a template for the placeholder block can be found. */ placeholderTmplIndex: number | null; /** * Extra configuration parameters (such as `after` and `minimum`) for the placeholder block. */ placeholderBlockConfig: DeferredPlaceholderBlockConfig | null; /** * Index in an LView and TData arrays where a template for the error block can be found. */ errorTmplIndex: number | null; /** * Compiler-generated function that loads all dependencies for a defer block. */ dependencyResolverFn: DependencyResolverFn | null; /** * Keeps track of the current loading state of defer block dependencies. */ loadingState: DeferDependenciesLoadingState; /** * Dependency loading Promise. This Promise is helpful for cases when there * are multiple instances of a defer block (e.g. if it was used inside of an *ngFor), * which all await the same set of dependencies. */ loadingPromise: Promise<unknown> | null; /** * List of providers collected from all NgModules that were imported by * standalone components used within this defer block. */ providers: Provider[] | null; /** * List of hydrate triggers for a given block */ hydrateTriggers: Map<DeferBlockTrigger, HydrateTriggerDetails | null> | null; /** * List of prefetch triggers for a given block */ prefetchTriggers: Set<DeferBlockTrigger> | null; } /** * Describes the current state of this defer block instance. * * @publicApi */ export enum DeferBlockState { /** The placeholder block content is rendered */ Placeholder = 0, /** The loading block content is rendered */ Loading = 1, /** The main content block content is rendered */ Complete = 2, /** The error block content is rendered */ Error = 3, } /** * Represents defer trigger types. */ export const enum DeferBlockTrigger { Idle, Immediate, Viewport, Interaction, Hover, Timer, When, Never, } /** * Describes specified delay (in ms) in the `hydrate on timer()` trigger. */ export interface HydrateTimerTriggerDetails { delay: number; } /** * Describes all possible hydration trigger details specified in a template. */ export type HydrateTriggerDetails = HydrateTimerTriggerDetails; /** * Describes the initial state of this defer block instance. * * Note: this state is internal only and *must* be represented * with a number lower than any value in the `DeferBlockState` enum. */ export enum DeferBlockInternalState { /** Initial state. Nothing is rendered yet. */ Initial = -1, } export const NEXT_DEFER_BLOCK_STATE = 0; // Note: it's *important* to keep the state in this slot, because this slot // is used by runtime logic to differentiate between LViews, LContainers and // other types (see `isLView` and `isLContainer` functions). In case of defer // blocks, this slot would always be a number. export const DEFER_BLOCK_STATE = 1; export const STATE_IS_FROZEN_UNTIL = 2; export const LOADING_AFTER_CLEANUP_FN = 3; export const TRIGGER_CLEANUP_FNS = 4; export const PREFETCH_TRIGGER_CLEANUP_FNS = 5; export const SSR_UNIQUE_ID = 6; export const SSR_BLOCK_STATE = 7; export const ON_COMPLETE_FNS = 8; export const HYDRATE_TRIGGER_CLEANUP_FNS = 9; /** * Describes instance-specific defer block data. * * Note: currently there is only the `state` slot, but more slots * would be added later to keep track of `after` and `maximum` features * (which would require per-instance state). */ export interface LDeferBlockDetails extends Array<unknown> { /** * Currently rendered block state. */ [DEFER_BLOCK_STATE]: DeferBlockState | DeferBlockInternalState; /** * Block state that was requested when another state was rendered. */ [NEXT_DEFER_BLOCK_STATE]: DeferBlockState | null; /** * Timestamp indicating when the current state can be switched to * the next one, in case teh current state has `minimum` parameter. */ [STATE_IS_FROZEN_UNTIL]: number | null; /** * Contains a reference to a cleanup function which cancels a timeout * when Angular waits before rendering loading state. This is used when * the loading block has the `after` parameter configured. */ [LOADING_AFTER_CLEANUP_FN]: VoidFunction | null; /** * List of cleanup functions for regular triggers. */ [TRIGGER_CLEANUP_FNS]: VoidFunction[] | null; /** * List of cleanup functions for prefetch triggers. */ [PREFETCH_TRIGGER_CLEANUP_FNS]: VoidFunction[] | null; /** * Unique id of this defer block assigned during SSR. */ [SSR_UNIQUE_ID]: string | null; /** * Defer block state after SSR. */ [SSR_BLOCK_STATE]: number | null; /** * A set of callbacks to be invoked once the main content is rendered. */ [ON_COMPLETE_FNS]: VoidFunction[] | null; /** * List of cleanup functions for hydrate triggers. */ [HYDRATE_TRIGGER_CLEANUP_FNS]: VoidFunction[] | null; } /** * Internal structure used for configuration of defer block behavior. * */ export interface DeferBlockConfig { behavior: DeferBlockBehavior; } /** * Options for configuring defer blocks behavior. * @publicApi */
{ "end_byte": 8068, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/interfaces.ts" }
angular/packages/core/src/defer/interfaces.ts_8069_9166
export enum DeferBlockBehavior { /** * Manual triggering mode for defer blocks. Provides control over when defer blocks render * and which state they render. */ Manual, /** * Playthrough mode for defer blocks. This mode behaves like defer blocks would in a browser. * This is the default behavior in test environments. */ Playthrough, } /** * **INTERNAL**, avoid referencing it in application code. * * Describes a helper class that allows to intercept a call to retrieve current * dependency loading function and replace it with a different implementation. * This interceptor class is needed to allow testing blocks in different states * by simulating loading response. */ export interface DeferBlockDependencyInterceptor { /** * Invoked for each defer block when dependency loading function is accessed. */ intercept(dependencyFn: DependencyResolverFn | null): DependencyResolverFn | null; /** * Allows to configure an interceptor function. */ setInterceptor(interceptorFn: (current: DependencyResolverFn) => DependencyResolverFn): void; }
{ "end_byte": 9166, "start_byte": 8069, "url": "https://github.com/angular/angular/blob/main/packages/core/src/defer/interfaces.ts" }
angular/packages/core/src/util/decorators.ts_0_6678
/** * @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} from '../interface/type'; import {noSideEffects} from './closure'; /** * An interface implemented by all Angular type decorators, which allows them to be used as * decorators as well as Angular syntax. * * ``` * @ng.Component({...}) * class MyClass {...} * ``` * * @publicApi */ export interface TypeDecorator { /** * Invoke as decorator. */ <T extends Type<any>>(type: T): T; // Make TypeDecorator assignable to built-in ParameterDecorator type. // ParameterDecorator is declared in lib.d.ts as a `declare type` // so we cannot declare this interface as a subtype. // see https://github.com/angular/angular/issues/3379#issuecomment-126169417 (target: Object, propertyKey?: string | symbol, parameterIndex?: number): void; // Standard (non-experimental) Decorator signature that avoids direct usage of // any TS 5.0+ specific types. (target: unknown, context: unknown): void; } export const ANNOTATIONS = '__annotations__'; export const PARAMETERS = '__parameters__'; export const PROP_METADATA = '__prop__metadata__'; /** * @suppress {globalThis} */ export function makeDecorator<T>( name: string, props?: (...args: any[]) => any, parentClass?: any, additionalProcessing?: (type: Type<T>) => void, typeFn?: (type: Type<T>, ...args: any[]) => void, ): {new (...args: any[]): any; (...args: any[]): any; (...args: any[]): (cls: any) => any} { return noSideEffects(() => { const metaCtor = makeMetadataCtor(props); function DecoratorFactory( this: unknown | typeof DecoratorFactory, ...args: any[] ): (cls: Type<T>) => any { if (this instanceof DecoratorFactory) { metaCtor.call(this, ...args); return this as typeof DecoratorFactory; } const annotationInstance = new (DecoratorFactory as any)(...args); return function TypeDecorator(cls: Type<T>) { if (typeFn) typeFn(cls, ...args); // Use of Object.defineProperty is important since it creates non-enumerable property which // prevents the property is copied during subclassing. const annotations = cls.hasOwnProperty(ANNOTATIONS) ? (cls as any)[ANNOTATIONS] : (Object.defineProperty(cls, ANNOTATIONS, {value: []}) as any)[ANNOTATIONS]; annotations.push(annotationInstance); if (additionalProcessing) additionalProcessing(cls); return cls; }; } if (parentClass) { DecoratorFactory.prototype = Object.create(parentClass.prototype); } DecoratorFactory.prototype.ngMetadataName = name; (DecoratorFactory as any).annotationCls = DecoratorFactory; return DecoratorFactory as any; }); } function makeMetadataCtor(props?: (...args: any[]) => any): any { return function ctor(this: any, ...args: any[]) { if (props) { const values = props(...args); for (const propName in values) { this[propName] = values[propName]; } } }; } export function makeParamDecorator( name: string, props?: (...args: any[]) => any, parentClass?: any, ): any { return noSideEffects(() => { const metaCtor = makeMetadataCtor(props); function ParamDecoratorFactory( this: unknown | typeof ParamDecoratorFactory, ...args: any[] ): any { if (this instanceof ParamDecoratorFactory) { metaCtor.apply(this, args); return this; } const annotationInstance = new (<any>ParamDecoratorFactory)(...args); (<any>ParamDecorator).annotation = annotationInstance; return ParamDecorator; function ParamDecorator(cls: any, unusedKey: any, index: number): any { // Use of Object.defineProperty is important since it creates non-enumerable property which // prevents the property is copied during subclassing. const parameters = cls.hasOwnProperty(PARAMETERS) ? (cls as any)[PARAMETERS] : Object.defineProperty(cls, PARAMETERS, {value: []})[PARAMETERS]; // there might be gaps if some in between parameters do not have annotations. // we pad with nulls. while (parameters.length <= index) { parameters.push(null); } (parameters[index] = parameters[index] || []).push(annotationInstance); return cls; } } if (parentClass) { ParamDecoratorFactory.prototype = Object.create(parentClass.prototype); } ParamDecoratorFactory.prototype.ngMetadataName = name; (<any>ParamDecoratorFactory).annotationCls = ParamDecoratorFactory; return ParamDecoratorFactory; }); } export function makePropDecorator( name: string, props?: (...args: any[]) => any, parentClass?: any, additionalProcessing?: (target: any, name: string, ...args: any[]) => void, ): any { return noSideEffects(() => { const metaCtor = makeMetadataCtor(props); function PropDecoratorFactory( this: unknown | typeof PropDecoratorFactory, ...args: any[] ): any { if (this instanceof PropDecoratorFactory) { metaCtor.apply(this, args); return this; } const decoratorInstance = new (<any>PropDecoratorFactory)(...args); function PropDecorator(target: any, name: string) { // target is undefined with standard decorators. This case is not supported and will throw // if this decorator is used in JIT mode with standard decorators. if (target === undefined) { throw new Error('Standard Angular field decorators are not supported in JIT mode.'); } const constructor = target.constructor; // Use of Object.defineProperty is important because it creates a non-enumerable property // which prevents the property from being copied during subclassing. const meta = constructor.hasOwnProperty(PROP_METADATA) ? (constructor as any)[PROP_METADATA] : Object.defineProperty(constructor, PROP_METADATA, {value: {}})[PROP_METADATA]; meta[name] = (meta.hasOwnProperty(name) && meta[name]) || []; meta[name].unshift(decoratorInstance); if (additionalProcessing) additionalProcessing(target, name, ...args); } return PropDecorator; } if (parentClass) { PropDecoratorFactory.prototype = Object.create(parentClass.prototype); } PropDecoratorFactory.prototype.ngMetadataName = name; (<any>PropDecoratorFactory).annotationCls = PropDecoratorFactory; return PropDecoratorFactory; }); }
{ "end_byte": 6678, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/util/decorators.ts" }
angular/packages/core/src/util/ng_dev_mode.ts_0_4920
/** * @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 {global} from './global'; declare global { /** * Values of ngDevMode * Depending on the current state of the application, ngDevMode may have one of several values. * * For convenience, the “truthy” value which enables dev mode is also an object which contains * Angular’s performance counters. This is not necessary, but cuts down on boilerplate for the * perf counters. * * ngDevMode may also be set to false. This can happen in one of a few ways: * - The user explicitly sets `window.ngDevMode = false` somewhere in their app. * - The user calls `enableProdMode()`. * - The URL contains a `ngDevMode=false` text. * Finally, ngDevMode may not have been defined at all. */ const ngDevMode: null | NgDevModePerfCounters; interface NgDevModePerfCounters { namedConstructors: boolean; firstCreatePass: number; tNode: number; tView: number; rendererCreateTextNode: number; rendererSetText: number; rendererCreateElement: number; rendererAddEventListener: number; rendererSetAttribute: number; rendererRemoveAttribute: number; rendererSetProperty: number; rendererSetClassName: number; rendererAddClass: number; rendererRemoveClass: number; rendererSetStyle: number; rendererRemoveStyle: number; rendererDestroy: number; rendererDestroyNode: number; rendererMoveNode: number; rendererRemoveNode: number; rendererAppendChild: number; rendererInsertBefore: number; rendererCreateComment: number; hydratedNodes: number; hydratedComponents: number; dehydratedViewsRemoved: number; dehydratedViewsCleanupRuns: number; componentsSkippedHydration: number; } } export function ngDevModeResetPerfCounters(): NgDevModePerfCounters { const locationString = typeof location !== 'undefined' ? location.toString() : ''; const newCounters: NgDevModePerfCounters = { namedConstructors: locationString.indexOf('ngDevMode=namedConstructors') != -1, firstCreatePass: 0, tNode: 0, tView: 0, rendererCreateTextNode: 0, rendererSetText: 0, rendererCreateElement: 0, rendererAddEventListener: 0, rendererSetAttribute: 0, rendererRemoveAttribute: 0, rendererSetProperty: 0, rendererSetClassName: 0, rendererAddClass: 0, rendererRemoveClass: 0, rendererSetStyle: 0, rendererRemoveStyle: 0, rendererDestroy: 0, rendererDestroyNode: 0, rendererMoveNode: 0, rendererRemoveNode: 0, rendererAppendChild: 0, rendererInsertBefore: 0, rendererCreateComment: 0, hydratedNodes: 0, hydratedComponents: 0, dehydratedViewsRemoved: 0, dehydratedViewsCleanupRuns: 0, componentsSkippedHydration: 0, }; // Make sure to refer to ngDevMode as ['ngDevMode'] for closure. const allowNgDevModeTrue = locationString.indexOf('ngDevMode=false') === -1; if (!allowNgDevModeTrue) { global['ngDevMode'] = false; } else { if (typeof global['ngDevMode'] !== 'object') { global['ngDevMode'] = {}; } Object.assign(global['ngDevMode'], newCounters); } return newCounters; } /** * This function checks to see if the `ngDevMode` has been set. If yes, * then we honor it, otherwise we default to dev mode with additional checks. * * The idea is that unless we are doing production build where we explicitly * set `ngDevMode == false` we should be helping the developer by providing * as much early warning and errors as possible. * * `ɵɵdefineComponent` is guaranteed to have been called before any component template functions * (and thus Ivy instructions), so a single initialization there is sufficient to ensure ngDevMode * is defined for the entire instruction set. * * When checking `ngDevMode` on toplevel, always init it before referencing it * (e.g. `((typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode())`), otherwise you can * get a `ReferenceError` like in https://github.com/angular/angular/issues/31595. * * Details on possible values for `ngDevMode` can be found on its docstring. * * NOTE: * - changes to the `ngDevMode` name must be synced with `compiler-cli/src/tooling.ts`. */ export function initNgDevMode(): boolean { // The below checks are to ensure that calling `initNgDevMode` multiple times does not // reset the counters. // If the `ngDevMode` is not an object, then it means we have not created the perf counters // yet. if (typeof ngDevMode === 'undefined' || ngDevMode) { if (typeof ngDevMode !== 'object' || Object.keys(ngDevMode).length === 0) { ngDevModeResetPerfCounters(); } return typeof ngDevMode !== 'undefined' && !!ngDevMode; } return false; }
{ "end_byte": 4920, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/util/ng_dev_mode.ts" }
angular/packages/core/src/util/closure.ts_0_781
/** * @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 */ /** * Convince closure compiler that the wrapped function has no side-effects. * * Closure compiler always assumes that `toString` has no side-effects. We use this quirk to * allow us to execute a function but have closure compiler mark the call as no-side-effects. * It is important that the return value for the `noSideEffects` function be assigned * to something which is retained otherwise the call to `noSideEffects` will be removed by closure * compiler. */ export function noSideEffects<T>(fn: () => T): T { return {toString: fn}.toString() as unknown as T; }
{ "end_byte": 781, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/util/closure.ts" }
angular/packages/core/src/util/dom.ts_0_2217
/** * @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 */ /** * Disallowed strings in the comment. * * see: https://html.spec.whatwg.org/multipage/syntax.html#comments */ const COMMENT_DISALLOWED = /^>|^->|<!--|-->|--!>|<!-$/g; /** * Delimiter in the disallowed strings which needs to be wrapped with zero with character. */ const COMMENT_DELIMITER = /(<|>)/g; const COMMENT_DELIMITER_ESCAPED = '\u200B$1\u200B'; /** * Escape the content of comment strings so that it can be safely inserted into a comment node. * * The issue is that HTML does not specify any way to escape comment end text inside the comment. * Consider: `<!-- The way you close a comment is with ">", and "->" at the beginning or by "-->" or * "--!>" at the end. -->`. Above the `"-->"` is meant to be text not an end to the comment. This * can be created programmatically through DOM APIs. (`<!--` are also disallowed.) * * see: https://html.spec.whatwg.org/multipage/syntax.html#comments * * ``` * div.innerHTML = div.innerHTML * ``` * * One would expect that the above code would be safe to do, but it turns out that because comment * text is not escaped, the comment may contain text which will prematurely close the comment * opening up the application for XSS attack. (In SSR we programmatically create comment nodes which * may contain such text and expect them to be safe.) * * This function escapes the comment text by looking for comment delimiters (`<` and `>`) and * surrounding them with `_>_` where the `_` is a zero width space `\u200B`. The result is that if a * comment contains any of the comment start/end delimiters (such as `<!--`, `-->` or `--!>`) the * text it will render normally but it will not cause the HTML parser to close/open the comment. * * @param value text to make safe for comment node by escaping the comment open/close character * sequence. */ export function escapeCommentText(value: string): string { return value.replace(COMMENT_DISALLOWED, (text) => text.replace(COMMENT_DELIMITER, COMMENT_DELIMITER_ESCAPED), ); }
{ "end_byte": 2217, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/util/dom.ts" }
angular/packages/core/src/util/callback_scheduler.ts_0_2996
/** * @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 {noop} from './noop'; /** * Gets a scheduling function that runs the callback after the first of setTimeout and * requestAnimationFrame resolves. * * - `requestAnimationFrame` ensures that change detection runs ahead of a browser repaint. * This ensures that the create and update passes of a change detection always happen * in the same frame. * - When the browser is resource-starved, `rAF` can execute _before_ a `setTimeout` because * rendering is a very high priority process. This means that `setTimeout` cannot guarantee * same-frame create and update pass, when `setTimeout` is used to schedule the update phase. * - While `rAF` gives us the desirable same-frame updates, it has two limitations that * prevent it from being used alone. First, it does not run in background tabs, which would * prevent Angular from initializing an application when opened in a new tab (for example). * Second, repeated calls to requestAnimationFrame will execute at the refresh rate of the * hardware (~16ms for a 60Hz display). This would cause significant slowdown of tests that * are written with several updates and asserts in the form of "update; await stable; assert;". * - Both `setTimeout` and `rAF` are able to "coalesce" several events from a single user * interaction into a single change detection. Importantly, this reduces view tree traversals when * compared to an alternative timing mechanism like `queueMicrotask`, where change detection would * then be interleaves between each event. * * By running change detection after the first of `setTimeout` and `rAF` to execute, we get the * best of both worlds. * * @returns a function to cancel the scheduled callback */ export function scheduleCallbackWithRafRace(callback: Function): () => void { let timeoutId: number; let animationFrameId: number; function cleanup() { callback = noop; try { if (animationFrameId !== undefined && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(animationFrameId); } if (timeoutId !== undefined) { clearTimeout(timeoutId); } } catch { // Clearing/canceling can fail in tests due to the timing of functions being patched and unpatched // Just ignore the errors - we protect ourselves from this issue by also making the callback a no-op. } } timeoutId = setTimeout(() => { callback(); cleanup(); }) as unknown as number; if (typeof requestAnimationFrame === 'function') { animationFrameId = requestAnimationFrame(() => { callback(); cleanup(); }); } return () => cleanup(); } export function scheduleCallbackWithMicrotask(callback: Function): () => void { queueMicrotask(() => callback()); return () => { callback = noop; }; }
{ "end_byte": 2996, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/util/callback_scheduler.ts" }