_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/src/render3/def_getters.ts_0_2126
/** * @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 type {NgModuleDef} from '../r3_symbols'; import {stringify} from '../util/stringify'; import {NG_COMP_DEF, NG_DIR_DEF, NG_MOD_DEF, NG_PIPE_DEF} from './fields'; import type {ComponentDef, DirectiveDef, PipeDef} from './interfaces/definition'; export function getNgModuleDef<T>(type: any, throwNotFound: true): NgModuleDef<T>; export function getNgModuleDef<T>(type: any): NgModuleDef<T> | null; export function getNgModuleDef<T>(type: any, throwNotFound?: boolean): NgModuleDef<T> | null { const ngModuleDef = type[NG_MOD_DEF] || null; if (!ngModuleDef && throwNotFound === true) { throw new Error(`Type ${stringify(type)} does not have 'ɵmod' property.`); } return ngModuleDef; } /** * The following getter methods retrieve the definition from the type. Currently the retrieval * honors inheritance, but in the future we may change the rule to require that definitions are * explicit. This would require some sort of migration strategy. */ export function getComponentDef<T>(type: any): ComponentDef<T> | null { return type[NG_COMP_DEF] || null; } export function getDirectiveDef<T>(type: any): DirectiveDef<T> | null { return type[NG_DIR_DEF] || null; } export function getPipeDef<T>(type: any): PipeDef<T> | null { return type[NG_PIPE_DEF] || null; } /** * Checks whether a given Component, Directive or Pipe is marked as standalone. * This will return false if passed anything other than a Component, Directive, or Pipe class * See [this guide](guide/components/importing) for additional information: * * @param type A reference to a Component, Directive or Pipe. * @publicApi */ export function isStandalone(type: Type<unknown>): boolean { const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type); // TODO: standalone as default value (invert the condition) return def !== null ? def.standalone : false; }
{ "end_byte": 2126, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/def_getters.ts" }
angular/packages/core/src/render3/errors.ts_0_6218
/** * @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 './def_getters'; import {getDeclarationComponentDef} from './instructions/element_validation'; import {TNode} from './interfaces/node'; import {LView, TVIEW} from './interfaces/view'; import {INTERPOLATION_DELIMITER} from './util/misc_utils'; import {stringifyForError} from './util/stringify_utils'; /** * The max length of the string representation of a value in an error message */ const VALUE_STRING_LENGTH_LIMIT = 200; /** Verifies that a given type is a Standalone Component. */ export function assertStandaloneComponentType(type: Type<unknown>) { assertComponentDef(type); const componentDef = getComponentDef(type)!; if (!componentDef.standalone) { throw new RuntimeError( RuntimeErrorCode.TYPE_IS_NOT_STANDALONE, `The ${stringifyForError(type)} component is not marked as standalone, ` + `but Angular expects to have a standalone component here. ` + `Please make sure the ${stringifyForError(type)} component has ` + `the \`standalone: true\` flag in the decorator.`, ); } } /** Verifies whether a given type is a component */ export function assertComponentDef(type: Type<unknown>) { if (!getComponentDef(type)) { throw new RuntimeError( RuntimeErrorCode.MISSING_GENERATED_DEF, `The ${stringifyForError(type)} is not an Angular component, ` + `make sure it has the \`@Component\` decorator.`, ); } } /** Called when there are multiple component selectors that match a given node */ export function throwMultipleComponentError( tNode: TNode, first: Type<unknown>, second: Type<unknown>, ): never { throw new RuntimeError( RuntimeErrorCode.MULTIPLE_COMPONENTS_MATCH, `Multiple components match node with tagname ${tNode.value}: ` + `${stringifyForError(first)} and ` + `${stringifyForError(second)}`, ); } /** Throws an ExpressionChangedAfterChecked error if checkNoChanges mode is on. */ export function throwErrorIfNoChangesMode( creationMode: boolean, oldValue: any, currValue: any, propName: string | undefined, lView: LView, ): never { const hostComponentDef = getDeclarationComponentDef(lView); const componentClassName = hostComponentDef?.type?.name; const field = propName ? ` for '${propName}'` : ''; let msg = `ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value${field}: '${formatValue( oldValue, )}'. Current value: '${formatValue(currValue)}'.${ componentClassName ? ` Expression location: ${componentClassName} component` : '' }`; if (creationMode) { msg += ` It seems like the view has been created after its parent and its children have been dirty checked.` + ` Has it been created in a change detection hook?`; } throw new RuntimeError(RuntimeErrorCode.EXPRESSION_CHANGED_AFTER_CHECKED, msg); } function formatValue(value: unknown): string { let strValue: string = String(value); // JSON.stringify will throw on circular references try { if (Array.isArray(value) || strValue === '[object Object]') { strValue = JSON.stringify(value); } } catch (error) {} return strValue.length > VALUE_STRING_LENGTH_LIMIT ? strValue.substring(0, VALUE_STRING_LENGTH_LIMIT) + '…' : strValue; } function constructDetailsForInterpolation( lView: LView, rootIndex: number, expressionIndex: number, meta: string, changedValue: any, ) { const [propName, prefix, ...chunks] = meta.split(INTERPOLATION_DELIMITER); let oldValue = prefix, newValue = prefix; for (let i = 0; i < chunks.length; i++) { const slotIdx = rootIndex + i; oldValue += `${lView[slotIdx]}${chunks[i]}`; newValue += `${slotIdx === expressionIndex ? changedValue : lView[slotIdx]}${chunks[i]}`; } return {propName, oldValue, newValue}; } /** * Constructs an object that contains details for the ExpressionChangedAfterItHasBeenCheckedError: * - property name (for property bindings or interpolations) * - old and new values, enriched using information from metadata * * More information on the metadata storage format can be found in `storePropertyBindingMetadata` * function description. */ export function getExpressionChangedErrorDetails( lView: LView, bindingIndex: number, oldValue: any, newValue: any, ): {propName?: string; oldValue: any; newValue: any} { const tData = lView[TVIEW].data; const metadata = tData[bindingIndex]; if (typeof metadata === 'string') { // metadata for property interpolation if (metadata.indexOf(INTERPOLATION_DELIMITER) > -1) { return constructDetailsForInterpolation( lView, bindingIndex, bindingIndex, metadata, newValue, ); } // metadata for property binding return {propName: metadata, oldValue, newValue}; } // metadata is not available for this expression, check if this expression is a part of the // property interpolation by going from the current binding index left and look for a string that // contains INTERPOLATION_DELIMITER, the layout in tView.data for this case will look like this: // [..., 'id�Prefix � and � suffix', null, null, null, ...] if (metadata === null) { let idx = bindingIndex - 1; while (typeof tData[idx] !== 'string' && tData[idx + 1] === null) { idx--; } const meta = tData[idx]; if (typeof meta === 'string') { const matches = meta.match(new RegExp(INTERPOLATION_DELIMITER, 'g')); // first interpolation delimiter separates property name from interpolation parts (in case of // property interpolations), so we subtract one from total number of found delimiters if (matches && matches.length - 1 > bindingIndex - idx) { return constructDetailsForInterpolation(lView, idx, bindingIndex, meta, newValue); } } } return {propName: undefined, oldValue, newValue}; }
{ "end_byte": 6218, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/errors.ts" }
angular/packages/core/src/render3/view_engine_compatibility_prebound.ts_0_644
/** * @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 {createTemplateRef, TemplateRef} from '../linker/template_ref'; import {TNode} from './interfaces/node'; import {LView} from './interfaces/view'; /** * Retrieves `TemplateRef` instance from `Injector` when a local reference is placed on the * `<ng-template>` element. * * @codeGenApi */ export function ɵɵtemplateRefExtractor(tNode: TNode, lView: LView): TemplateRef<any> | null { return createTemplateRef(tNode, lView); }
{ "end_byte": 644, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/view_engine_compatibility_prebound.ts" }
angular/packages/core/src/render3/TREE_SHAKING.md_0_2460
# Tree Shaking Principles When designing code please keep these principles in mind ## Enums for features are not-tree-shakable Here is an example of code which is not tree shakable. ``` export function query<T>( predicate: Type<any>| string[], descend?: boolean, read?: QueryReadType | Type<T>): QueryList<T> { ngDevMode && assertPreviousIsParent(); const queryList = new QueryList<T>(); const query = currentQuery || (currentQuery = new LQuery_()); query.track(queryList, predicate, descend, read); return queryList; } ``` Notice that `query()` takes the `QueryReadType` as enumeration. ``` function readFromNodeInjector( nodeInjector: LInjector, node: LNode, read: QueryReadType | Type<any>): any { if (read === QueryReadType.ElementRef) { return getOrCreateElementRef(nodeInjector); } if (read === QueryReadType.ViewContainerRef) { return getOrCreateContainerRef(nodeInjector); } if (read === QueryReadType.TemplateRef) { return getOrCreateTemplateRef(nodeInjector); } const matchingIdx = geIdxOfMatchingDirective(node, read); if (matchingIdx !== null) { return node.view.data[matchingIdx]; } return null; } ``` Sometimes later in the above code the `readFromNodeInjector` takes the `QueryReadType` enumeration and performs specific behavior. The issue is that once the `query` instruction is pulled in it will pull in `ElementRef`, `ContainerRef`, and `TemplateRef` regardless if the `query` instruction queries for them. A better way to do this is to encapsulate the work into an object or function which will then be passed into the `query` instead of the enumeration. ``` function queryElementRefFeature() {...} function queryContainerRefFeature() {...} function queryTemplateRefFeature() {...} query(predicate, descend, queryElementRefFeature) {...} ``` this would allow the `readFromNodeInjector` to simply call the `read` function (or object) like so. ``` function readFromNodeInjector( nodeInjector: LInjector, node: LNode, readFn: (injector: Injector) => any) | Type<any>): any { if (isFeature(readFn)) { return readFn(nodeInjector); } const matchingIdx = geIdxOfMatchingDirective(node, readFn); if (matchingIdx !== null) { return node.view.data[matchingIdx]; } return null; } ``` This approach allows us to preserve the tree-shaking. In essence the if statement has moved from runtime (non-tree-shakable) to compile time (tree-shakable) position.
{ "end_byte": 2460, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/TREE_SHAKING.md" }
angular/packages/core/src/render3/bindings.ts_0_4119
/** * @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 {assertIndexInRange, assertLessThan, assertNotSame} from '../util/assert'; import {devModeEqual} from '../util/comparison'; import {getExpressionChangedErrorDetails, throwErrorIfNoChangesMode} from './errors'; import {LView} from './interfaces/view'; import {isInCheckNoChangesMode} from './state'; import {NO_CHANGE} from './tokens'; // TODO(misko): consider inlining /** Updates binding and returns the value. */ export function updateBinding(lView: LView, bindingIndex: number, value: any): any { return (lView[bindingIndex] = value); } /** Gets the current binding value. */ export function getBinding(lView: LView, bindingIndex: number): any { ngDevMode && assertIndexInRange(lView, bindingIndex); ngDevMode && assertNotSame(lView[bindingIndex], NO_CHANGE, 'Stored value should never be NO_CHANGE.'); return lView[bindingIndex]; } /** * Updates binding if changed, then returns whether it was updated. * * This function also checks the `CheckNoChangesMode` and throws if changes are made. * Some changes (Objects/iterables) during `CheckNoChangesMode` are exempt to comply with VE * behavior. * * @param lView current `LView` * @param bindingIndex The binding in the `LView` to check * @param value New value to check against `lView[bindingIndex]` * @returns `true` if the bindings has changed. (Throws if binding has changed during * `CheckNoChangesMode`) */ export function bindingUpdated(lView: LView, bindingIndex: number, value: any): boolean { ngDevMode && assertNotSame(value, NO_CHANGE, 'Incoming value should never be NO_CHANGE.'); ngDevMode && assertLessThan(bindingIndex, lView.length, `Slot should have been initialized to NO_CHANGE`); const oldValue = lView[bindingIndex]; if (Object.is(oldValue, value)) { return false; } else { if (ngDevMode && isInCheckNoChangesMode()) { // View engine didn't report undefined values as changed on the first checkNoChanges pass // (before the change detection was run). const oldValueToCompare = oldValue !== NO_CHANGE ? oldValue : undefined; if (!devModeEqual(oldValueToCompare, value)) { const details = getExpressionChangedErrorDetails( lView, bindingIndex, oldValueToCompare, value, ); throwErrorIfNoChangesMode( oldValue === NO_CHANGE, details.oldValue, details.newValue, details.propName, lView, ); } // There was a change, but the `devModeEqual` decided that the change is exempt from an error. // For this reason we exit as if no change. The early exit is needed to prevent the changed // value to be written into `LView` (If we would write the new value that we would not see it // as change on next CD.) return false; } lView[bindingIndex] = value; return true; } } /** Updates 2 bindings if changed, then returns whether either was updated. */ export function bindingUpdated2(lView: LView, bindingIndex: number, exp1: any, exp2: any): boolean { const different = bindingUpdated(lView, bindingIndex, exp1); return bindingUpdated(lView, bindingIndex + 1, exp2) || different; } /** Updates 3 bindings if changed, then returns whether any was updated. */ export function bindingUpdated3( lView: LView, bindingIndex: number, exp1: any, exp2: any, exp3: any, ): boolean { const different = bindingUpdated2(lView, bindingIndex, exp1, exp2); return bindingUpdated(lView, bindingIndex + 2, exp3) || different; } /** Updates 4 bindings if changed, then returns whether any was updated. */ export function bindingUpdated4( lView: LView, bindingIndex: number, exp1: any, exp2: any, exp3: any, exp4: any, ): boolean { const different = bindingUpdated2(lView, bindingIndex, exp1, exp2); return bindingUpdated2(lView, bindingIndex + 2, exp3, exp4) || different; }
{ "end_byte": 4119, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/bindings.ts" }
angular/packages/core/src/render3/definition.ts_0_6999
/** * @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 {ChangeDetectionStrategy} from '../change_detection/constants'; import {EnvironmentInjector} from '../di/r3_injector'; import {formatRuntimeError, RuntimeErrorCode} from '../errors'; import {Type, Writable} from '../interface/type'; import {NgModuleDef} from '../metadata/ng_module_def'; import {SchemaMetadata} from '../metadata/schema'; import {ViewEncapsulation} from '../metadata/view'; import {noSideEffects} from '../util/closure'; import {EMPTY_ARRAY, EMPTY_OBJ} from '../util/empty'; import {initNgDevMode} from '../util/ng_dev_mode'; import {performanceMarkFeature} from '../util/performance'; import {getComponentDef, getDirectiveDef, getPipeDef} from './def_getters'; import type { ComponentDef, ComponentDefFeature, ComponentTemplate, ContentQueriesFunction, DependencyTypeList, DirectiveDef, DirectiveDefFeature, DirectiveDefListOrFactory, HostBindingsFunction, InputTransformFunction, PipeDef, PipeDefListOrFactory, TypeOrFactory, ViewQueriesFunction, } from './interfaces/definition'; import {InputFlags} from './interfaces/input_flags'; import type {TAttributes, TConstantsOrFactory} from './interfaces/node'; import {CssSelectorList} from './interfaces/projection'; import {stringifyCSSSelectorList} from './node_selector_matcher'; import {NG_STANDALONE_DEFAULT_VALUE} from './standalone-default-value'; import {StandaloneService} from './standalone_service'; /** * Map of inputs for a given directive/component. * * Given: * ``` * class MyComponent { * @Input() * publicInput1: string; * * @Input('publicInput2') * declaredInput2: string; * * @Input({transform: (value: boolean) => value ? 1 : 0}) * transformedInput3: number; * * signalInput = input(3); * } * ``` * * is described as: * ``` * { * publicInput1: 'publicInput1', * declaredInput2: [InputFlags.None, 'declaredInput2', 'publicInput2'], * transformedInput3: [ * InputFlags.None, * 'transformedInput3', * 'transformedInput3', * (value: boolean) => value ? 1 : 0 * ], * signalInput: [InputFlags.SignalBased, "signalInput"], * } * ``` * * Which the minifier may translate to: * ``` * { * minifiedPublicInput1: 'publicInput1', * minifiedDeclaredInput2: [InputFlags.None, 'publicInput2', 'declaredInput2'], * minifiedTransformedInput3: [ * InputFlags.None, * 'transformedInput3', * 'transformedInput3', * (value: boolean) => value ? 1 : 0 * ], * minifiedSignalInput: [InputFlags.SignalBased, "signalInput"], * } * ``` * * This allows the render to re-construct the minified, public, and declared names * of properties. * * NOTE: * - Because declared and public name are usually same we only generate the array * `['declared', 'public']` format when they differ, or there is a transform. * - The reason why this API and `outputs` API is not the same is that `NgOnChanges` has * inconsistent behavior in that it uses declared names rather than minified or public. */ type DirectiveInputs<T> = { [P in keyof T]?: // Basic case. Mapping minified name to public name. | string // Complex input when there are flags, or differing public name and declared name, or there // is a transform. Such inputs are not as common, so the array form is only generated then. | [ flags: InputFlags, publicName: string, declaredName?: string, transform?: InputTransformFunction, ]; }; interface DirectiveDefinition<T> { /** * Directive type, needed to configure the injector. */ type: Type<T>; /** The selectors that will be used to match nodes to this directive. */ selectors?: CssSelectorList; /** * A map of input names. */ inputs?: DirectiveInputs<T>; /** * A map of output names. * * The format is in: `{[actualPropertyName: string]:string}`. * * Which the minifier may translate to: `{[minifiedPropertyName: string]:string}`. * * This allows the render to re-construct the minified and non-minified names * of properties. */ outputs?: {[P in keyof T]?: string}; /** * A list of optional features to apply. * * See: {@link NgOnChangesFeature}, {@link ProvidersFeature}, {@link InheritDefinitionFeature} */ features?: DirectiveDefFeature[]; /** * Function executed by the parent template to allow child directive to apply host bindings. */ hostBindings?: HostBindingsFunction<T>; /** * The number of bindings in this directive `hostBindings` (including pure fn bindings). * * Used to calculate the length of the component's LView array, so we * can pre-fill the array and set the host binding start index. */ hostVars?: number; /** * Assign static attribute values to a host element. * * This property will assign static attribute values as well as class and style * values to a host element. Since attribute values can consist of different types of values, * the `hostAttrs` array must include the values in the following format: * * attrs = [ * // static attributes (like `title`, `name`, `id`...) * attr1, value1, attr2, value, * * // a single namespace value (like `x:id`) * NAMESPACE_MARKER, namespaceUri1, name1, value1, * * // another single namespace value (like `x:name`) * NAMESPACE_MARKER, namespaceUri2, name2, value2, * * // a series of CSS classes that will be applied to the element (no spaces) * CLASSES_MARKER, class1, class2, class3, * * // a series of CSS styles (property + value) that will be applied to the element * STYLES_MARKER, prop1, value1, prop2, value2 * ] * * All non-class and non-style attributes must be defined at the start of the list * first before all class and style values are set. When there is a change in value * type (like when classes and styles are introduced) a marker must be used to separate * the entries. The marker values themselves are set via entries found in the * [AttributeMarker] enum. */ hostAttrs?: TAttributes; /** * Function to create instances of content queries associated with a given directive. */ contentQueries?: ContentQueriesFunction<T>; /** * Additional set of instructions specific to view query processing. This could be seen as a * set of instructions to be inserted into the template function. */ viewQuery?: ViewQueriesFunction<T> | null; /** * Defines the name that can be used in the template to assign this directive to a variable. * * See: {@link Directive.exportAs} */ exportAs?: string[]; /** * Whether this directive/component is standalone. */ standalone?: boolean; /** * Whether this directive/component is signal-based. */ signals?: boolean; }
{ "end_byte": 6999, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/definition.ts" }
angular/packages/core/src/render3/definition.ts_7001_13757
interface ComponentDefinition<T> extends Omit<DirectiveDefinition<T>, 'features'> { /** * The number of nodes, local refs, and pipes in this component template. * * Used to calculate the length of this component's LView array, so we * can pre-fill the array and set the binding start index. */ decls: number; /** * The number of bindings in this component template (including pure fn bindings). * * Used to calculate the length of this component's LView array, so we * can pre-fill the array and set the host binding start index. */ vars: number; /** * Template function use for rendering DOM. * * This function has following structure. * * ``` * function Template<T>(ctx:T, creationMode: boolean) { * if (creationMode) { * // Contains creation mode instructions. * } * // Contains binding update instructions * } * ``` * * Common instructions are: * Creation mode instructions: * - `elementStart`, `elementEnd` * - `text` * - `container` * - `listener` * * Binding update instructions: * - `bind` * - `elementAttribute` * - `elementProperty` * - `elementClass` * - `elementStyle` * */ template: ComponentTemplate<T>; /** * Constants for the nodes in the component's view. * Includes attribute arrays, local definition arrays etc. */ consts?: TConstantsOrFactory; /** * An array of `ngContent[selector]` values that were found in the template. */ ngContentSelectors?: string[]; /** * A list of optional features to apply. * * See: {@link NgOnChangesFeature}, {@link ProvidersFeature} */ features?: ComponentDefFeature[]; /** * Defines template and style encapsulation options available for Component's {@link Component}. */ encapsulation?: ViewEncapsulation; /** * Defines arbitrary developer-defined data to be stored on a renderer instance. * This is useful for renderers that delegate to other renderers. * * see: animation */ data?: {[kind: string]: any}; /** * A set of styles that the component needs to be present for component to render correctly. */ styles?: string[]; /** * The strategy that the default change detector uses to detect changes. * When set, takes effect the next time change detection is triggered. */ changeDetection?: ChangeDetectionStrategy; /** * Registry of directives, components, and pipes that may be found in this component's view. * * This property is either an array of types or a function that returns the array of types. This * function may be necessary to support forward declarations. */ dependencies?: TypeOrFactory<DependencyTypeList>; /** * The set of schemas that declare elements to be allowed in the component's template. */ schemas?: SchemaMetadata[] | null; } /** * Create a component definition object. * * * # Example * ``` * class MyComponent { * // Generated by Angular Template Compiler * // [Symbol] syntax will not be supported by TypeScript until v2.7 * static ɵcmp = defineComponent({ * ... * }); * } * ``` * @codeGenApi */ export function ɵɵdefineComponent<T>( componentDefinition: ComponentDefinition<T>, ): ComponentDef<any> { return noSideEffects(() => { // Initialize ngDevMode. This must be the first statement in ɵɵdefineComponent. // See the `initNgDevMode` docstring for more information. (typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode(); const baseDef = getNgDirectiveDef(componentDefinition as DirectiveDefinition<T>); const def: Writable<ComponentDef<T>> = { ...baseDef, decls: componentDefinition.decls, vars: componentDefinition.vars, template: componentDefinition.template, consts: componentDefinition.consts || null, ngContentSelectors: componentDefinition.ngContentSelectors, onPush: componentDefinition.changeDetection === ChangeDetectionStrategy.OnPush, directiveDefs: null!, // assigned in noSideEffects pipeDefs: null!, // assigned in noSideEffects dependencies: (baseDef.standalone && componentDefinition.dependencies) || null, getStandaloneInjector: baseDef.standalone ? (parentInjector: EnvironmentInjector) => { return parentInjector.get(StandaloneService).getOrCreateStandaloneInjector(def); } : null, getExternalStyles: null, signals: componentDefinition.signals ?? false, data: componentDefinition.data || {}, encapsulation: componentDefinition.encapsulation || ViewEncapsulation.Emulated, styles: componentDefinition.styles || EMPTY_ARRAY, _: null, schemas: componentDefinition.schemas || null, tView: null, id: '', }; // TODO: Do we still need/want this ? if (baseDef.standalone) { performanceMarkFeature('NgStandalone'); } initFeatures(def); const dependencies = componentDefinition.dependencies; def.directiveDefs = extractDefListOrFactory(dependencies, /* pipeDef */ false); def.pipeDefs = extractDefListOrFactory(dependencies, /* pipeDef */ true); def.id = getComponentId(def); return def; }); } export function extractDirectiveDef(type: Type<any>): DirectiveDef<any> | ComponentDef<any> | null { return getComponentDef(type) || getDirectiveDef(type); } function nonNull<T>(value: T | null): value is T { return value !== null; } /** * @codeGenApi */ export function ɵɵdefineNgModule<T>(def: { /** Token representing the module. Used by DI. */ type: T; /** List of components to bootstrap. */ bootstrap?: Type<any>[] | (() => Type<any>[]); /** List of components, directives, and pipes declared by this module. */ declarations?: Type<any>[] | (() => Type<any>[]); /** List of modules or `ModuleWithProviders` imported by this module. */ imports?: Type<any>[] | (() => Type<any>[]); /** * List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this * module. */ exports?: Type<any>[] | (() => Type<any>[]); /** The set of schemas that declare elements to be allowed in the NgModule. */ schemas?: SchemaMetadata[] | null; /** Unique ID for the module that is used with `getModuleFactory`. */ id?: string | null; }): unknown { return noSideEffects(() => { const res: NgModuleDef<T> = { type: def.type, bootstrap: def.bootstrap || EMPTY_ARRAY, declarations: def.declarations || EMPTY_ARRAY, imports: def.imports || EMPTY_ARRAY, exports: def.exports || EMPTY_ARRAY, transitiveCompileScopes: null, schemas: def.schemas || null, id: def.id || null, }; return res; }); } /**
{ "end_byte": 13757, "start_byte": 7001, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/definition.ts" }
angular/packages/core/src/render3/definition.ts_13759_20767
Converts binding objects from the `DirectiveDefinition` into more efficient * lookup dictionaries that are optimized for the framework runtime. * * This function converts inputs or output directive information into new objects * where the public name conveniently maps to the minified internal field name. * * For inputs, the input flags are additionally persisted into the new data structure, * so that those can be quickly retrieved when needed. * * e.g. for * * ``` * class Comp { * @Input() * propName1: string; * * @Input('publicName2') * declaredPropName2: number; * * inputSignal = input(3); * } * ``` * * will be serialized as * * ``` * { * propName1: 'propName1', * declaredPropName2: ['publicName2', 'declaredPropName2'], * inputSignal: [InputFlags.SignalBased, 'inputSignal'], * } * ``` * * which is than translated by the minifier as: * * ``` * { * minifiedPropName1: 'propName1', * minifiedPropName2: ['publicName2', 'declaredPropName2'], * minifiedInputSignal: [InputFlags.SignalBased, 'inputSignal'], * } * ``` * * becomes: (public name => minifiedName + isSignal if needed) * * ``` * { * 'propName1': 'minifiedPropName1', * 'publicName2': 'minifiedPropName2', * 'inputSignal': ['minifiedInputSignal', InputFlags.SignalBased], * } * ``` * * Optionally the function can take `declaredInputs` which will result * in: (public name => declared name) * * ``` * { * 'propName1': 'propName1', * 'publicName2': 'declaredPropName2', * 'inputSignal': 'inputSignal', * } * ``` * */ function parseAndConvertBindingsForDefinition<T>( obj: DirectiveDefinition<T>['outputs'] | undefined, ): Record<keyof T, string>; function parseAndConvertBindingsForDefinition<T>( obj: DirectiveInputs<T> | undefined, declaredInputs: Record<string, string>, ): Record<keyof T, string | [minifiedName: string, flags: InputFlags]>; function parseAndConvertBindingsForDefinition<T>( obj: undefined | DirectiveInputs<T> | DirectiveDefinition<T>['outputs'], declaredInputs?: Record<string, string>, ): Record<keyof T, string | [minifiedName: string, flags: InputFlags]> { if (obj == null) return EMPTY_OBJ as any; const newLookup: any = {}; for (const minifiedKey in obj) { if (obj.hasOwnProperty(minifiedKey)) { const value = obj[minifiedKey]!; let publicName: string; let declaredName: string; let inputFlags = InputFlags.None; if (Array.isArray(value)) { inputFlags = value[0]; publicName = value[1]; declaredName = value[2] ?? publicName; // declared name might not be set to save bytes. } else { publicName = value; declaredName = value; } // For inputs, capture the declared name, or if some flags are set. if (declaredInputs) { // Perf note: An array is only allocated for the input if there are flags. newLookup[publicName] = inputFlags !== InputFlags.None ? [minifiedKey, inputFlags] : minifiedKey; declaredInputs[publicName] = declaredName as string; } else { newLookup[publicName] = minifiedKey; } } } return newLookup; } /** * Create a directive definition object. * * # Example * ```ts * class MyDirective { * // Generated by Angular Template Compiler * // [Symbol] syntax will not be supported by TypeScript until v2.7 * static ɵdir = ɵɵdefineDirective({ * ... * }); * } * ``` * * @codeGenApi */ export function ɵɵdefineDirective<T>( directiveDefinition: DirectiveDefinition<T>, ): DirectiveDef<any> { return noSideEffects(() => { const def = getNgDirectiveDef(directiveDefinition); initFeatures(def); return def; }); } /** * Create a pipe definition object. * * # Example * ``` * class MyPipe implements PipeTransform { * // Generated by Angular Template Compiler * static ɵpipe = definePipe({ * ... * }); * } * ``` * @param pipeDef Pipe definition generated by the compiler * * @codeGenApi */ export function ɵɵdefinePipe<T>(pipeDef: { /** Name of the pipe. Used for matching pipes in template to pipe defs. */ name: string; /** Pipe class reference. Needed to extract pipe lifecycle hooks. */ type: Type<T>; /** Whether the pipe is pure. */ pure?: boolean; /** * Whether the pipe is standalone. */ standalone?: boolean; }): unknown { return <PipeDef<T>>{ type: pipeDef.type, name: pipeDef.name, factory: null, pure: pipeDef.pure !== false, standalone: pipeDef.standalone ?? NG_STANDALONE_DEFAULT_VALUE, onDestroy: pipeDef.type.prototype.ngOnDestroy || null, }; } function getNgDirectiveDef<T>(directiveDefinition: DirectiveDefinition<T>): DirectiveDef<T> { const declaredInputs: Record<string, string> = {}; return { type: directiveDefinition.type, providersResolver: null, factory: null, hostBindings: directiveDefinition.hostBindings || null, hostVars: directiveDefinition.hostVars || 0, hostAttrs: directiveDefinition.hostAttrs || null, contentQueries: directiveDefinition.contentQueries || null, declaredInputs: declaredInputs, inputTransforms: null, inputConfig: directiveDefinition.inputs || EMPTY_OBJ, exportAs: directiveDefinition.exportAs || null, standalone: directiveDefinition.standalone ?? NG_STANDALONE_DEFAULT_VALUE, signals: directiveDefinition.signals === true, selectors: directiveDefinition.selectors || EMPTY_ARRAY, viewQuery: directiveDefinition.viewQuery || null, features: directiveDefinition.features || null, setInput: null, findHostDirectiveDefs: null, hostDirectives: null, inputs: parseAndConvertBindingsForDefinition(directiveDefinition.inputs, declaredInputs), outputs: parseAndConvertBindingsForDefinition(directiveDefinition.outputs), debugInfo: null, }; } function initFeatures<T>(definition: DirectiveDef<T> | ComponentDef<T>): void { definition.features?.forEach((fn) => fn(definition)); } export function extractDefListOrFactory( dependencies: TypeOrFactory<DependencyTypeList> | undefined, pipeDef: false, ): DirectiveDefListOrFactory | null; export function extractDefListOrFactory( dependencies: TypeOrFactory<DependencyTypeList> | undefined, pipeDef: true, ): PipeDefListOrFactory | null; export function extractDefListOrFactory( dependencies: TypeOrFactory<DependencyTypeList> | undefined, pipeDef: boolean, ): unknown { if (!dependencies) { return null; } const defExtractor = pipeDef ? getPipeDef : extractDirectiveDef; return () => (typeof dependencies === 'function' ? dependencies() : dependencies) .map((dep) => defExtractor(dep)) .filter(nonNull); } /** * A map that contains the generated component IDs and type. */ export const GENERATED_COMP_IDS = new Map<string, Type<unknown>>(); /** * A method can returns a component ID from the component definition using a variant of DJB2 hash * algorithm. */ function getCo
{ "end_byte": 20767, "start_byte": 13759, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/definition.ts" }
angular/packages/core/src/render3/definition.ts_20768_23217
ponentId<T>(componentDef: ComponentDef<T>): string { let hash = 0; // We cannot rely solely on the component selector as the same selector can be used in different // modules. // // `componentDef.style` is not used, due to it causing inconsistencies. Ex: when server // component styles has no sourcemaps and browsers do. // // Example: // https://github.com/angular/components/blob/d9f82c8f95309e77a6d82fd574c65871e91354c2/src/material/core/option/option.ts#L248 // https://github.com/angular/components/blob/285f46dc2b4c5b127d356cb7c4714b221f03ce50/src/material/legacy-core/option/option.ts#L32 const hashSelectors = [ componentDef.selectors, componentDef.ngContentSelectors, componentDef.hostVars, componentDef.hostAttrs, componentDef.consts, componentDef.vars, componentDef.decls, componentDef.encapsulation, componentDef.standalone, componentDef.signals, componentDef.exportAs, JSON.stringify(componentDef.inputs), JSON.stringify(componentDef.outputs), // We cannot use 'componentDef.type.name' as the name of the symbol will change and will not // match in the server and browser bundles. Object.getOwnPropertyNames(componentDef.type.prototype), !!componentDef.contentQueries, !!componentDef.viewQuery, ].join('|'); for (const char of hashSelectors) { hash = (Math.imul(31, hash) + char.charCodeAt(0)) << 0; } // Force positive number hash. // 2147483647 = equivalent of Integer.MAX_VALUE. hash += 2147483647 + 1; const compId = 'c' + hash; if (typeof ngDevMode === 'undefined' || ngDevMode) { if (GENERATED_COMP_IDS.has(compId)) { const previousCompDefType = GENERATED_COMP_IDS.get(compId)!; if (previousCompDefType !== componentDef.type) { console.warn( formatRuntimeError( RuntimeErrorCode.COMPONENT_ID_COLLISION, `Component ID generation collision detected. Components '${ previousCompDefType.name }' and '${componentDef.type.name}' with selector '${stringifyCSSSelectorList( componentDef.selectors, )}' generated the same component ID. To fix this, you can change the selector of one of those components or add an extra host attribute to force a different ID.`, ), ); } } else { GENERATED_COMP_IDS.set(compId, componentDef.type); } } return compId; }
{ "end_byte": 23217, "start_byte": 20768, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/definition.ts" }
angular/packages/core/src/render3/errors_di.ts_0_2527
/** * @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 {ProviderToken} from '../di'; import {isEnvironmentProviders} from '../di/interface/provider'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import {Type} from '../interface/type'; import {stringify} from '../util/stringify'; import {stringifyForError} from './util/stringify_utils'; /** Called when directives inject each other (creating a circular dependency) */ export function throwCyclicDependencyError(token: string, path?: string[]): never { const depPath = path ? `. Dependency path: ${path.join(' > ')} > ${token}` : ''; throw new RuntimeError( RuntimeErrorCode.CYCLIC_DI_DEPENDENCY, ngDevMode ? `Circular dependency in DI detected for ${token}${depPath}` : token, ); } export function throwMixedMultiProviderError() { throw new Error(`Cannot mix multi providers and regular providers`); } export function throwInvalidProviderError( ngModuleType?: Type<unknown>, providers?: any[], provider?: any, ): never { if (ngModuleType && providers) { const providerDetail = providers.map((v) => (v == provider ? '?' + provider + '?' : '...')); throw new Error( `Invalid provider for the NgModule '${stringify( ngModuleType, )}' - only instances of Provider and Type are allowed, got: [${providerDetail.join(', ')}]`, ); } else if (isEnvironmentProviders(provider)) { if (provider.ɵfromNgModule) { throw new RuntimeError( RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT, `Invalid providers from 'importProvidersFrom' present in a non-environment injector. 'importProvidersFrom' can't be used for component providers.`, ); } else { throw new RuntimeError( RuntimeErrorCode.PROVIDER_IN_WRONG_CONTEXT, `Invalid providers present in a non-environment injector. 'EnvironmentProviders' can't be used for component providers.`, ); } } else { throw new Error('Invalid provider'); } } /** Throws an error when a token is not found in DI. */ export function throwProviderNotFoundError( token: ProviderToken<unknown>, injectorName?: string, ): never { const errorMessage = ngDevMode && `No provider for ${stringifyForError(token)} found${injectorName ? ` in ${injectorName}` : ''}`; throw new RuntimeError(RuntimeErrorCode.PROVIDER_NOT_FOUND, errorMessage); }
{ "end_byte": 2527, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/errors_di.ts" }
angular/packages/core/src/render3/local_compilation.ts_0_836
/** * @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 {depsTracker} from './deps_tracker/deps_tracker'; import { ComponentType, DependencyTypeList, RawScopeInfoFromDecorator, } from './interfaces/definition'; export function ɵɵgetComponentDepsFactory( type: ComponentType<any>, rawImports?: RawScopeInfoFromDecorator[], ): () => DependencyTypeList { return () => { try { return depsTracker.getComponentDependencies(type, rawImports).dependencies; } catch (e) { console.error( `Computing dependencies in local compilation mode for the component "${type.name}" failed with the exception:`, e, ); throw e; } }; }
{ "end_byte": 836, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/local_compilation.ts" }
angular/packages/core/src/render3/STORING_METADATA_IN_D.TS.md_0_2137
# Storing Metadata in `.d.ts` files Previous version of Angular used `metadata.json` files to store information about directives/component/pipes/ng-modules. `ngc` compiler would than do a global analysis to generate the `.ngfactory.ts` files from the `metadata.json`. Ivy strives for locality, which means that `ngtsc` should not need any global information in order to compile the system. The above is mostly true. Unfortunately, in order for `ngtsc` to generate code which is tree shakable `ngtsc` does need to have global knowledge. Here is an abbreviated example of breakage of tree-shake-ability. ```typescript @Directive({ selector: '[tooltip]' }) export class TooltipDirective { // ngtsc generates this: static ɵdir = ɵɵdefineDirective(...); } @Component({ selector: 'app-root', template: 'Hello World!' }) class MyAppComponent { // ngtsc generates this: static ɵdir = ɵɵdefineComponent({ ... directives: [ // BREAKS TREE-SHAKING!!! // TooltipDirective included here because it was declared in the NgModule // ngtsc does not know it can be omitted. // Only way for ngtsc to know that it can omit TooltipDirective is if it knows // its selector and see if the selector matches the current component's template. TooltipDirective ] }); } @NgModule({ declarations: [MyAppComponent, TooltipDirective], bootstrap: [MyAppComponent], }) class MyAppModule { // ngtsc generates this: static ɵmod = ɵɵdefineNgModule(...); } ``` Notice that `ngtsc` can't remove `TooltipDirective` because it would need to know its selector and see if the directive matches in the component's template. Knowing the selector breaks locality and so we make an exception for some locality information such as selector, inputs and outputs. Since we are breaking the locality rule, we need to store the information someplace since `ngtsc` can't have access to the `TooltipDirective` source. We store the information in the `.d.ts` file like so. ```typescript class TooltipDirective { static ɵdir: DirectiveDeclaration<TooltipDirective, '[tooltip]', '', {}, {}, []> } ```
{ "end_byte": 2137, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/STORING_METADATA_IN_D.TS.md" }
angular/packages/core/src/render3/assert.ts_0_7039
/** * @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 {assertDefined, assertEqual, assertNumber, throwError} from '../util/assert'; import {getComponentDef, getNgModuleDef} from './def_getters'; import {LContainer} from './interfaces/container'; import {DirectiveDef} from './interfaces/definition'; import {TIcu} from './interfaces/i18n'; import {NodeInjectorOffset} from './interfaces/injector'; import {TNode} from './interfaces/node'; import {isLContainer, isLView} from './interfaces/type_checks'; import { DECLARATION_COMPONENT_VIEW, FLAGS, HEADER_OFFSET, LView, LViewFlags, T_HOST, TVIEW, TView, } from './interfaces/view'; // [Assert functions do not constraint type when they are guarded by a truthy // expression.](https://github.com/microsoft/TypeScript/issues/37295) export function assertTNodeForLView(tNode: TNode, lView: LView) { assertTNodeForTView(tNode, lView[TVIEW]); } export function assertTNodeForTView(tNode: TNode, tView: TView) { assertTNode(tNode); const tData = tView.data; for (let i = HEADER_OFFSET; i < tData.length; i++) { if (tData[i] === tNode) { return; } } throwError('This TNode does not belong to this TView.'); } export function assertTNode(tNode: TNode) { assertDefined(tNode, 'TNode must be defined'); if (!(tNode && typeof tNode === 'object' && tNode.hasOwnProperty('directiveStylingLast'))) { throwError('Not of type TNode, got: ' + tNode); } } export function assertTIcu(tIcu: TIcu) { assertDefined(tIcu, 'Expected TIcu to be defined'); if (!(typeof tIcu.currentCaseLViewIndex === 'number')) { throwError('Object is not of TIcu type.'); } } export function assertComponentType( actual: any, msg: string = "Type passed in is not ComponentType, it does not have 'ɵcmp' property.", ) { if (!getComponentDef(actual)) { throwError(msg); } } export function assertNgModuleType( actual: any, msg: string = "Type passed in is not NgModuleType, it does not have 'ɵmod' property.", ) { if (!getNgModuleDef(actual)) { throwError(msg); } } export function assertCurrentTNodeIsParent(isParent: boolean) { assertEqual(isParent, true, 'currentTNode should be a parent'); } export function assertHasParent(tNode: TNode | null) { assertDefined(tNode, 'currentTNode should exist!'); assertDefined(tNode!.parent, 'currentTNode should have a parent'); } export function assertLContainer(value: any): asserts value is LContainer { assertDefined(value, 'LContainer must be defined'); assertEqual(isLContainer(value), true, 'Expecting LContainer'); } export function assertLViewOrUndefined(value: any): asserts value is LView | null | undefined { value && assertEqual(isLView(value), true, 'Expecting LView or undefined or null'); } export function assertLView(value: any): asserts value is LView { assertDefined(value, 'LView must be defined'); assertEqual(isLView(value), true, 'Expecting LView'); } export function assertFirstCreatePass(tView: TView, errMessage?: string) { assertEqual( tView.firstCreatePass, true, errMessage || 'Should only be called in first create pass.', ); } export function assertFirstUpdatePass(tView: TView, errMessage?: string) { assertEqual( tView.firstUpdatePass, true, errMessage || 'Should only be called in first update pass.', ); } /** * This is a basic sanity check that an object is probably a directive def. DirectiveDef is * an interface, so we can't do a direct instanceof check. */ export function assertDirectiveDef<T>(obj: any): asserts obj is DirectiveDef<T> { if (obj.type === undefined || obj.selectors == undefined || obj.inputs === undefined) { throwError( `Expected a DirectiveDef/ComponentDef and this object does not seem to have the expected shape.`, ); } } export function assertIndexInDeclRange(tView: TView, index: number) { assertBetween(HEADER_OFFSET, tView.bindingStartIndex, index); } export function assertIndexInExpandoRange(lView: LView, index: number) { const tView = lView[1]; assertBetween(tView.expandoStartIndex, lView.length, index); } export function assertBetween(lower: number, upper: number, index: number) { if (!(lower <= index && index < upper)) { throwError(`Index out of range (expecting ${lower} <= ${index} < ${upper})`); } } export function assertProjectionSlots(lView: LView, errMessage?: string) { assertDefined(lView[DECLARATION_COMPONENT_VIEW], 'Component views should exist.'); assertDefined( lView[DECLARATION_COMPONENT_VIEW][T_HOST]!.projection, errMessage || 'Components with projection nodes (<ng-content>) must have projection slots defined.', ); } export function assertParentView(lView: LView | null, errMessage?: string) { assertDefined( lView, errMessage || "Component views should always have a parent view (component's host view)", ); } export function assertNoDuplicateDirectives(directives: DirectiveDef<unknown>[]): void { // The array needs at least two elements in order to have duplicates. if (directives.length < 2) { return; } const seenDirectives = new Set<DirectiveDef<unknown>>(); for (const current of directives) { if (seenDirectives.has(current)) { throw new RuntimeError( RuntimeErrorCode.DUPLICATE_DIRECTIVE, `Directive ${current.type.name} matches multiple times on the same element. ` + `Directives can only match an element once.`, ); } seenDirectives.add(current); } } /** * This is a basic sanity check that the `injectorIndex` seems to point to what looks like a * NodeInjector data structure. * * @param lView `LView` which should be checked. * @param injectorIndex index into the `LView` where the `NodeInjector` is expected. */ export function assertNodeInjector(lView: LView, injectorIndex: number) { assertIndexInExpandoRange(lView, injectorIndex); assertIndexInExpandoRange(lView, injectorIndex + NodeInjectorOffset.PARENT); assertNumber(lView[injectorIndex + 0], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 1], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 2], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 3], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 4], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 5], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 6], 'injectorIndex should point to a bloom filter'); assertNumber(lView[injectorIndex + 7], 'injectorIndex should point to a bloom filter'); assertNumber( lView[injectorIndex + NodeInjectorOffset.PARENT], 'injectorIndex should point to parent injector', ); }
{ "end_byte": 7039, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/assert.ts" }
angular/packages/core/src/render3/tokens.ts_0_543
/** * @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 interface NO_CHANGE { // This is a brand that ensures that this type can never match anything else __brand__: 'NO_CHANGE'; } /** A special value which designates that a value has not changed. */ export const NO_CHANGE: NO_CHANGE = typeof ngDevMode === 'undefined' || ngDevMode ? {__brand__: 'NO_CHANGE'} : ({} as NO_CHANGE);
{ "end_byte": 543, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/tokens.ts" }
angular/packages/core/src/render3/node_manipulation_i18n.ts_0_3101
/** * @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 {assertDomNode, assertIndexInRange} from '../util/assert'; import {TNode, TNodeFlags, TNodeType} from './interfaces/node'; import {Renderer} from './interfaces/renderer'; import {RElement, RNode} from './interfaces/renderer_dom'; import {LView} from './interfaces/view'; import {getInsertInFrontOfRNodeWithNoI18n, nativeInsertBefore} from './node_manipulation'; import {unwrapRNode} from './util/view_utils'; /** * Find a node in front of which `currentTNode` should be inserted (takes i18n into account). * * This method determines the `RNode` in front of which we should insert the `currentRNode`. This * takes `TNode.insertBeforeIndex` into account. * * @param parentTNode parent `TNode` * @param currentTNode current `TNode` (The node which we would like to insert into the DOM) * @param lView current `LView` */ export function getInsertInFrontOfRNodeWithI18n( parentTNode: TNode, currentTNode: TNode, lView: LView, ): RNode | null { const tNodeInsertBeforeIndex = currentTNode.insertBeforeIndex; const insertBeforeIndex = Array.isArray(tNodeInsertBeforeIndex) ? tNodeInsertBeforeIndex[0] : tNodeInsertBeforeIndex; if (insertBeforeIndex === null) { return getInsertInFrontOfRNodeWithNoI18n(parentTNode, currentTNode, lView); } else { ngDevMode && assertIndexInRange(lView, insertBeforeIndex); return unwrapRNode(lView[insertBeforeIndex]); } } /** * Process `TNode.insertBeforeIndex` by adding i18n text nodes. * * See `TNode.insertBeforeIndex` */ export function processI18nInsertBefore( renderer: Renderer, childTNode: TNode, lView: LView, childRNode: RNode | RNode[], parentRElement: RElement | null, ): void { const tNodeInsertBeforeIndex = childTNode.insertBeforeIndex; if (Array.isArray(tNodeInsertBeforeIndex)) { // An array indicates that there are i18n nodes that need to be added as children of this // `childRNode`. These i18n nodes were created before this `childRNode` was available and so // only now can be added. The first element of the array is the normal index where we should // insert the `childRNode`. Additional elements are the extra nodes to be added as children of // `childRNode`. ngDevMode && assertDomNode(childRNode); let i18nParent: RElement | null = childRNode as RElement; let anchorRNode: RNode | null = null; if (!(childTNode.type & TNodeType.AnyRNode)) { anchorRNode = i18nParent; i18nParent = parentRElement; } if (i18nParent !== null && childTNode.componentOffset === -1) { for (let i = 1; i < tNodeInsertBeforeIndex.length; i++) { // No need to `unwrapRNode` because all of the indexes point to i18n text nodes. // see `assertDomNode` below. const i18nChild = lView[tNodeInsertBeforeIndex[i]]; nativeInsertBefore(renderer, i18nParent, i18nChild, anchorRNode, false); } } } }
{ "end_byte": 3101, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation_i18n.ts" }
angular/packages/core/src/render3/di.ts_0_7847
/** * @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 {isForwardRef, resolveForwardRef} from '../di/forward_ref'; import {injectRootLimpMode, setInjectImplementation} from '../di/inject_switch'; import {Injector} from '../di/injector'; import {convertToBitFlags} from '../di/injector_compatibility'; import {InjectorMarkers} from '../di/injector_marker'; import {InjectFlags, InjectOptions} from '../di/interface/injector'; import {ProviderToken} from '../di/provider_token'; import {Type} from '../interface/type'; import {assertDefined, assertEqual, assertIndexInRange} from '../util/assert'; import {noSideEffects} from '../util/closure'; import {assertDirectiveDef, assertNodeInjector, assertTNodeForLView} from './assert'; import { emitInstanceCreatedByInjectorEvent, InjectorProfilerContext, runInInjectorProfilerContext, setInjectorProfilerContext, } from './debug/injector_profiler'; import {getFactoryDef} from './definition_factory'; import {throwCyclicDependencyError, throwProviderNotFoundError} from './errors_di'; import {NG_ELEMENT_ID, NG_FACTORY_DEF} from './fields'; import {registerPreOrderHooks} from './hooks'; import {AttributeMarker} from './interfaces/attribute_marker'; import {ComponentDef, DirectiveDef} from './interfaces/definition'; import { isFactory, NO_PARENT_INJECTOR, NodeInjectorFactory, NodeInjectorOffset, RelativeInjectorLocation, RelativeInjectorLocationFlags, } from './interfaces/injector'; import { TContainerNode, TDirectiveHostNode, TElementContainerNode, TElementNode, TNode, TNodeProviderIndexes, TNodeType, } from './interfaces/node'; import {isComponentDef, isComponentHost} from './interfaces/type_checks'; import { DECLARATION_COMPONENT_VIEW, DECLARATION_VIEW, EMBEDDED_VIEW_INJECTOR, FLAGS, INJECTOR, LView, LViewFlags, T_HOST, TData, TVIEW, TView, TViewType, } from './interfaces/view'; import {assertTNodeType} from './node_assert'; import {enterDI, getCurrentTNode, getLView, leaveDI} from './state'; import {isNameOnlyAttributeMarker} from './util/attrs_utils'; import { getParentInjectorIndex, getParentInjectorView, hasParentInjector, } from './util/injector_utils'; import {stringifyForError} from './util/stringify_utils'; /** * Defines if the call to `inject` should include `viewProviders` in its resolution. * * This is set to true when we try to instantiate a component. This value is reset in * `getNodeInjectable` to a value which matches the declaration location of the token about to be * instantiated. This is done so that if we are injecting a token which was declared outside of * `viewProviders` we don't accidentally pull `viewProviders` in. * * Example: * * ``` * @Injectable() * class MyService { * constructor(public value: String) {} * } * * @Component({ * providers: [ * MyService, * {provide: String, value: 'providers' } * ] * viewProviders: [ * {provide: String, value: 'viewProviders'} * ] * }) * class MyComponent { * constructor(myService: MyService, value: String) { * // We expect that Component can see into `viewProviders`. * expect(value).toEqual('viewProviders'); * // `MyService` was not declared in `viewProviders` hence it can't see it. * expect(myService.value).toEqual('providers'); * } * } * * ``` */ let includeViewProviders = true; export function setIncludeViewProviders(v: boolean): boolean { const oldValue = includeViewProviders; includeViewProviders = v; return oldValue; } /** * The number of slots in each bloom filter (used by DI). The larger this number, the fewer * directives that will share slots, and thus, the fewer false positives when checking for * the existence of a directive. */ const BLOOM_SIZE = 256; const BLOOM_MASK = BLOOM_SIZE - 1; /** * The number of bits that is represented by a single bloom bucket. JS bit operations are 32 bits, * so each bucket represents 32 distinct tokens which accounts for log2(32) = 5 bits of a bloom hash * number. */ const BLOOM_BUCKET_BITS = 5; /** Counter used to generate unique IDs for directives. */ let nextNgElementId = 0; /** Value used when something wasn't found by an injector. */ const NOT_FOUND = {}; /** * Registers this directive as present in its node's injector by flipping the directive's * corresponding bit in the injector's bloom filter. * * @param injectorIndex The index of the node injector where this token should be registered * @param tView The TView for the injector's bloom filters * @param type The directive token to register */ export function bloomAdd( injectorIndex: number, tView: TView, type: ProviderToken<any> | string, ): void { ngDevMode && assertEqual(tView.firstCreatePass, true, 'expected firstCreatePass to be true'); let id: number | undefined; if (typeof type === 'string') { id = type.charCodeAt(0) || 0; } else if (type.hasOwnProperty(NG_ELEMENT_ID)) { id = (type as any)[NG_ELEMENT_ID]; } // Set a unique ID on the directive type, so if something tries to inject the directive, // we can easily retrieve the ID and hash it into the bloom bit that should be checked. if (id == null) { id = (type as any)[NG_ELEMENT_ID] = nextNgElementId++; } // We only have BLOOM_SIZE (256) slots in our bloom filter (8 buckets * 32 bits each), // so all unique IDs must be modulo-ed into a number from 0 - 255 to fit into the filter. const bloomHash = id & BLOOM_MASK; // Create a mask that targets the specific bit associated with the directive. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding // to bit positions 0 - 31 in a 32 bit integer. const mask = 1 << bloomHash; // Each bloom bucket in `tData` represents `BLOOM_BUCKET_BITS` number of bits of `bloomHash`. // Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset that the mask // should be written to. (tView.data as number[])[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)] |= mask; } /** * Creates (or gets an existing) injector for a given element or container. * * @param tNode for which an injector should be retrieved / created. * @param lView View where the node is stored * @returns Node injector */ export function getOrCreateNodeInjectorForNode( tNode: TElementNode | TContainerNode | TElementContainerNode, lView: LView, ): number { const existingInjectorIndex = getInjectorIndex(tNode, lView); if (existingInjectorIndex !== -1) { return existingInjectorIndex; } const tView = lView[TVIEW]; if (tView.firstCreatePass) { tNode.injectorIndex = lView.length; insertBloom(tView.data, tNode); // foundation for node bloom insertBloom(lView, null); // foundation for cumulative bloom insertBloom(tView.blueprint, null); } const parentLoc = getParentInjectorLocation(tNode, lView); const injectorIndex = tNode.injectorIndex; // If a parent injector can't be found, its location is set to -1. // In that case, we don't need to set up a cumulative bloom if (hasParentInjector(parentLoc)) { const parentIndex = getParentInjectorIndex(parentLoc); const parentLView = getParentInjectorView(parentLoc, lView); const parentData = parentLView[TVIEW].data as any; // Creates a cumulative bloom filter that merges the parent's bloom filter // and its own cumulative bloom (which contains tokens for all ancestors) for (let i = 0; i < NodeInjectorOffset.BLOOM_SIZE; i++) { lView[injectorIndex + i] = parentLView[parentIndex + i] | parentData[parentIndex + i]; } } lView[injectorIndex + NodeInjectorOffset.PARENT] = parentLoc; return injectorIndex; }
{ "end_byte": 7847, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/di.ts_7849_15921
function insertBloom(arr: any[], footer: TNode | null): void { arr.push(0, 0, 0, 0, 0, 0, 0, 0, footer); } export function getInjectorIndex(tNode: TNode, lView: LView): number { if ( tNode.injectorIndex === -1 || // If the injector index is the same as its parent's injector index, then the index has been // copied down from the parent node. No injector has been created yet on this node. (tNode.parent && tNode.parent.injectorIndex === tNode.injectorIndex) || // After the first template pass, the injector index might exist but the parent values // might not have been calculated yet for this instance lView[tNode.injectorIndex + NodeInjectorOffset.PARENT] === null ) { return -1; } else { ngDevMode && assertIndexInRange(lView, tNode.injectorIndex); return tNode.injectorIndex; } } /** * Finds the index of the parent injector, with a view offset if applicable. Used to set the * parent injector initially. * * @returns Returns a number that is the combination of the number of LViews that we have to go up * to find the LView containing the parent inject AND the index of the injector within that LView. */ export function getParentInjectorLocation(tNode: TNode, lView: LView): RelativeInjectorLocation { if (tNode.parent && tNode.parent.injectorIndex !== -1) { // If we have a parent `TNode` and there is an injector associated with it we are done, because // the parent injector is within the current `LView`. return tNode.parent.injectorIndex as RelativeInjectorLocation; // ViewOffset is 0 } // When parent injector location is computed it may be outside of the current view. (ie it could // be pointing to a declared parent location). This variable stores number of declaration parents // we need to walk up in order to find the parent injector location. let declarationViewOffset = 0; let parentTNode: TNode | null = null; let lViewCursor: LView | null = lView; // The parent injector is not in the current `LView`. We will have to walk the declared parent // `LView` hierarchy and look for it. If we walk of the top, that means that there is no parent // `NodeInjector`. while (lViewCursor !== null) { parentTNode = getTNodeFromLView(lViewCursor); if (parentTNode === null) { // If we have no parent, than we are done. return NO_PARENT_INJECTOR; } ngDevMode && parentTNode && assertTNodeForLView(parentTNode!, lViewCursor[DECLARATION_VIEW]!); // Every iteration of the loop requires that we go to the declared parent. declarationViewOffset++; lViewCursor = lViewCursor[DECLARATION_VIEW]; if (parentTNode.injectorIndex !== -1) { // We found a NodeInjector which points to something. return (parentTNode.injectorIndex | (declarationViewOffset << RelativeInjectorLocationFlags.ViewOffsetShift)) as RelativeInjectorLocation; } } return NO_PARENT_INJECTOR; } /** * Makes a type or an injection token public to the DI system by adding it to an * injector's bloom filter. * * @param di The node injector in which a directive will be added * @param token The type or the injection token to be made public */ export function diPublicInInjector( injectorIndex: number, tView: TView, token: ProviderToken<any>, ): void { bloomAdd(injectorIndex, tView, token); } /** * Inject static attribute value into directive constructor. * * This method is used with `factory` functions which are generated as part of * `defineDirective` or `defineComponent`. The method retrieves the static value * of an attribute. (Dynamic attributes are not supported since they are not resolved * at the time of injection and can change over time.) * * # Example * Given: * ``` * @Component(...) * class MyComponent { * constructor(@Attribute('title') title: string) { ... } * } * ``` * When instantiated with * ``` * <my-component title="Hello"></my-component> * ``` * * Then factory method generated is: * ``` * MyComponent.ɵcmp = defineComponent({ * factory: () => new MyComponent(injectAttribute('title')) * ... * }) * ``` * * @publicApi */ export function injectAttributeImpl(tNode: TNode, attrNameToInject: string): string | null { ngDevMode && assertTNodeType(tNode, TNodeType.AnyContainer | TNodeType.AnyRNode); ngDevMode && assertDefined(tNode, 'expecting tNode'); if (attrNameToInject === 'class') { return tNode.classes; } if (attrNameToInject === 'style') { return tNode.styles; } const attrs = tNode.attrs; if (attrs) { const attrsLength = attrs.length; let i = 0; while (i < attrsLength) { const value = attrs[i]; // If we hit a `Bindings` or `Template` marker then we are done. if (isNameOnlyAttributeMarker(value)) break; // Skip namespaced attributes if (value === AttributeMarker.NamespaceURI) { // we skip the next two values // as namespaced attributes looks like // [..., AttributeMarker.NamespaceURI, 'http://someuri.com/test', 'test:exist', // 'existValue', ...] i = i + 2; } else if (typeof value === 'number') { // Skip to the first value of the marked attribute. i++; while (i < attrsLength && typeof attrs[i] === 'string') { i++; } } else if (value === attrNameToInject) { return attrs[i + 1] as string; } else { i = i + 2; } } } return null; } function notFoundValueOrThrow<T>( notFoundValue: T | null, token: ProviderToken<T>, flags: InjectFlags, ): T | null { if (flags & InjectFlags.Optional || notFoundValue !== undefined) { return notFoundValue; } else { throwProviderNotFoundError(token, 'NodeInjector'); } } /** * Returns the value associated to the given token from the ModuleInjector or throws exception * * @param lView The `LView` that contains the `tNode` * @param token The token to look for * @param flags Injection flags * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional` * @returns the value from the injector or throws an exception */ function lookupTokenUsingModuleInjector<T>( lView: LView, token: ProviderToken<T>, flags: InjectFlags, notFoundValue?: any, ): T | null { if (flags & InjectFlags.Optional && notFoundValue === undefined) { // This must be set or the NullInjector will throw for optional deps notFoundValue = null; } if ((flags & (InjectFlags.Self | InjectFlags.Host)) === 0) { const moduleInjector = lView[INJECTOR]; // switch to `injectInjectorOnly` implementation for module injector, since module injector // should not have access to Component/Directive DI scope (that may happen through // `directiveInject` implementation) const previousInjectImplementation = setInjectImplementation(undefined); try { if (moduleInjector) { return moduleInjector.get(token, notFoundValue, flags & InjectFlags.Optional); } else { return injectRootLimpMode(token, notFoundValue, flags & InjectFlags.Optional); } } finally { setInjectImplementation(previousInjectImplementation); } } return notFoundValueOrThrow<T>(notFoundValue, token, flags); } /** * Returns the value associated to the given token from the NodeInjectors => ModuleInjector. * * Look for the injector providing the token by walking up the node injector tree and then * the module injector tree. * * This function patches `token` with `__NG_ELEMENT_ID__` which contains the id for the bloom * filter. `-1` is reserved for injecting `Injector` (implemented by `NodeInjector`) * * @param tNode The Node where the search for the injector should start * @param lView The `LView` that contains the `tNode` * @param token The token to look for * @param flags Injection flags * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional` * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided */
{ "end_byte": 15921, "start_byte": 7849, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/di.ts_15922_22175
xport function getOrCreateInjectable<T>( tNode: TDirectiveHostNode | null, lView: LView, token: ProviderToken<T>, flags: InjectFlags = InjectFlags.Default, notFoundValue?: any, ): T | null { if (tNode !== null) { // If the view or any of its ancestors have an embedded // view injector, we have to look it up there first. if ( lView[FLAGS] & LViewFlags.HasEmbeddedViewInjector && // The token must be present on the current node injector when the `Self` // flag is set, so the lookup on embedded view injector(s) can be skipped. !(flags & InjectFlags.Self) ) { const embeddedInjectorValue = lookupTokenUsingEmbeddedInjector( tNode, lView, token, flags, NOT_FOUND, ); if (embeddedInjectorValue !== NOT_FOUND) { return embeddedInjectorValue; } } // Otherwise try the node injector. const value = lookupTokenUsingNodeInjector(tNode, lView, token, flags, NOT_FOUND); if (value !== NOT_FOUND) { return value; } } // Finally, fall back to the module injector. return lookupTokenUsingModuleInjector<T>(lView, token, flags, notFoundValue); } /** * Returns the value associated to the given token from the node injector. * * @param tNode The Node where the search for the injector should start * @param lView The `LView` that contains the `tNode` * @param token The token to look for * @param flags Injection flags * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional` * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided */ function lookupTokenUsingNodeInjector<T>( tNode: TDirectiveHostNode, lView: LView, token: ProviderToken<T>, flags: InjectFlags, notFoundValue?: any, ) { const bloomHash = bloomHashBitOrFactory(token); // If the ID stored here is a function, this is a special object like ElementRef or TemplateRef // so just call the factory function to create it. if (typeof bloomHash === 'function') { if (!enterDI(lView, tNode, flags)) { // Failed to enter DI, try module injector instead. If a token is injected with the @Host // flag, the module injector is not searched for that token in Ivy. return flags & InjectFlags.Host ? notFoundValueOrThrow<T>(notFoundValue, token, flags) : lookupTokenUsingModuleInjector<T>(lView, token, flags, notFoundValue); } try { let value: unknown; if (ngDevMode) { runInInjectorProfilerContext( new NodeInjector(getCurrentTNode() as TElementNode, getLView()), token as Type<T>, () => { value = bloomHash(flags); if (value != null) { emitInstanceCreatedByInjectorEvent(value); } }, ); } else { value = bloomHash(flags); } if (value == null && !(flags & InjectFlags.Optional)) { throwProviderNotFoundError(token); } else { return value; } } finally { leaveDI(); } } else if (typeof bloomHash === 'number') { // A reference to the previous injector TView that was found while climbing the element // injector tree. This is used to know if viewProviders can be accessed on the current // injector. let previousTView: TView | null = null; let injectorIndex = getInjectorIndex(tNode, lView); let parentLocation = NO_PARENT_INJECTOR; let hostTElementNode: TNode | null = flags & InjectFlags.Host ? lView[DECLARATION_COMPONENT_VIEW][T_HOST] : null; // If we should skip this injector, or if there is no injector on this node, start by // searching the parent injector. if (injectorIndex === -1 || flags & InjectFlags.SkipSelf) { parentLocation = injectorIndex === -1 ? getParentInjectorLocation(tNode, lView) : lView[injectorIndex + NodeInjectorOffset.PARENT]; if (parentLocation === NO_PARENT_INJECTOR || !shouldSearchParent(flags, false)) { injectorIndex = -1; } else { previousTView = lView[TVIEW]; injectorIndex = getParentInjectorIndex(parentLocation); lView = getParentInjectorView(parentLocation, lView); } } // Traverse up the injector tree until we find a potential match or until we know there // *isn't* a match. while (injectorIndex !== -1) { ngDevMode && assertNodeInjector(lView, injectorIndex); // Check the current injector. If it matches, see if it contains token. const tView = lView[TVIEW]; ngDevMode && assertTNodeForLView(tView.data[injectorIndex + NodeInjectorOffset.TNODE] as TNode, lView); if (bloomHasToken(bloomHash, injectorIndex, tView.data)) { // At this point, we have an injector which *may* contain the token, so we step through // the providers and directives associated with the injector's corresponding node to get // the instance. const instance: T | {} | null = searchTokensOnInjector<T>( injectorIndex, lView, token, previousTView, flags, hostTElementNode, ); if (instance !== NOT_FOUND) { return instance; } } parentLocation = lView[injectorIndex + NodeInjectorOffset.PARENT]; if ( parentLocation !== NO_PARENT_INJECTOR && shouldSearchParent( flags, lView[TVIEW].data[injectorIndex + NodeInjectorOffset.TNODE] === hostTElementNode, ) && bloomHasToken(bloomHash, injectorIndex, lView) ) { // The def wasn't found anywhere on this node, so it was a false positive. // Traverse up the tree and continue searching. previousTView = tView; injectorIndex = getParentInjectorIndex(parentLocation); lView = getParentInjectorView(parentLocation, lView); } else { // If we should not search parent OR If the ancestor bloom filter value does not have the // bit corresponding to the directive we can give up on traversing up to find the specific // injector. injectorIndex = -1; } } } return notFoundValue; }
{ "end_byte": 22175, "start_byte": 15922, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/di.ts_22177_29855
unction searchTokensOnInjector<T>( injectorIndex: number, lView: LView, token: ProviderToken<T>, previousTView: TView | null, flags: InjectFlags, hostTElementNode: TNode | null, ) { const currentTView = lView[TVIEW]; const tNode = currentTView.data[injectorIndex + NodeInjectorOffset.TNODE] as TNode; // First, we need to determine if view providers can be accessed by the starting element. // There are two possibilities const canAccessViewProviders = previousTView == null ? // 1) This is the first invocation `previousTView == null` which means that we are at the // `TNode` of where injector is starting to look. In such a case the only time we are allowed // to look into the ViewProviders is if: // - we are on a component // - AND the injector set `includeViewProviders` to true (implying that the token can see // ViewProviders because it is the Component or a Service which itself was declared in // ViewProviders) isComponentHost(tNode) && includeViewProviders : // 2) `previousTView != null` which means that we are now walking across the parent nodes. // In such a case we are only allowed to look into the ViewProviders if: // - We just crossed from child View to Parent View `previousTView != currentTView` // - AND the parent TNode is an Element. // This means that we just came from the Component's View and therefore are allowed to see // into the ViewProviders. previousTView != currentTView && (tNode.type & TNodeType.AnyRNode) !== 0; // This special case happens when there is a @host on the inject and when we are searching // on the host element node. const isHostSpecialCase = flags & InjectFlags.Host && hostTElementNode === tNode; const injectableIdx = locateDirectiveOrProvider( tNode, currentTView, token, canAccessViewProviders, isHostSpecialCase, ); if (injectableIdx !== null) { return getNodeInjectable(lView, currentTView, injectableIdx, tNode as TElementNode); } else { return NOT_FOUND; } } /** * Searches for the given token among the node's directives and providers. * * @param tNode TNode on which directives are present. * @param tView The tView we are currently processing * @param token Provider token or type of a directive to look for. * @param canAccessViewProviders Whether view providers should be considered. * @param isHostSpecialCase Whether the host special case applies. * @returns Index of a found directive or provider, or null when none found. */ export function locateDirectiveOrProvider<T>( tNode: TNode, tView: TView, token: ProviderToken<T> | string, canAccessViewProviders: boolean, isHostSpecialCase: boolean | number, ): number | null { const nodeProviderIndexes = tNode.providerIndexes; const tInjectables = tView.data; const injectablesStart = nodeProviderIndexes & TNodeProviderIndexes.ProvidersStartIndexMask; const directivesStart = tNode.directiveStart; const directiveEnd = tNode.directiveEnd; const cptViewProvidersCount = nodeProviderIndexes >> TNodeProviderIndexes.CptViewProvidersCountShift; const startingIndex = canAccessViewProviders ? injectablesStart : injectablesStart + cptViewProvidersCount; // When the host special case applies, only the viewProviders and the component are visible const endIndex = isHostSpecialCase ? injectablesStart + cptViewProvidersCount : directiveEnd; for (let i = startingIndex; i < endIndex; i++) { const providerTokenOrDef = tInjectables[i] as ProviderToken<any> | DirectiveDef<any> | string; if ( (i < directivesStart && token === providerTokenOrDef) || (i >= directivesStart && (providerTokenOrDef as DirectiveDef<any>).type === token) ) { return i; } } if (isHostSpecialCase) { const dirDef = tInjectables[directivesStart] as DirectiveDef<any>; if (dirDef && isComponentDef(dirDef) && dirDef.type === token) { return directivesStart; } } return null; } /** * Retrieve or instantiate the injectable from the `LView` at particular `index`. * * This function checks to see if the value has already been instantiated and if so returns the * cached `injectable`. Otherwise if it detects that the value is still a factory it * instantiates the `injectable` and caches the value. */ export function getNodeInjectable( lView: LView, tView: TView, index: number, tNode: TDirectiveHostNode, ): any { let value = lView[index]; const tData = tView.data; if (isFactory(value)) { const factory: NodeInjectorFactory = value; if (factory.resolving) { throwCyclicDependencyError(stringifyForError(tData[index])); } const previousIncludeViewProviders = setIncludeViewProviders(factory.canSeeViewProviders); factory.resolving = true; let prevInjectContext: InjectorProfilerContext | undefined; if (ngDevMode) { // tData indexes mirror the concrete instances in its corresponding LView. // lView[index] here is either the injectable instace itself or a factory, // therefore tData[index] is the constructor of that injectable or a // definition object that contains the constructor in a `.type` field. const token = (tData[index] as DirectiveDef<unknown> | ComponentDef<unknown>).type || tData[index]; const injector = new NodeInjector(tNode, lView); prevInjectContext = setInjectorProfilerContext({injector, token}); } const previousInjectImplementation = factory.injectImpl ? setInjectImplementation(factory.injectImpl) : null; const success = enterDI(lView, tNode, InjectFlags.Default); ngDevMode && assertEqual( success, true, "Because flags do not contain `SkipSelf' we expect this to always succeed.", ); try { value = lView[index] = factory.factory(undefined, tData, lView, tNode); ngDevMode && emitInstanceCreatedByInjectorEvent(value); // This code path is hit for both directives and providers. // For perf reasons, we want to avoid searching for hooks on providers. // It does no harm to try (the hooks just won't exist), but the extra // checks are unnecessary and this is a hot path. So we check to see // if the index of the dependency is in the directive range for this // tNode. If it's not, we know it's a provider and skip hook registration. if (tView.firstCreatePass && index >= tNode.directiveStart) { ngDevMode && assertDirectiveDef(tData[index]); registerPreOrderHooks(index, tData[index] as DirectiveDef<any>, tView); } } finally { ngDevMode && setInjectorProfilerContext(prevInjectContext!); previousInjectImplementation !== null && setInjectImplementation(previousInjectImplementation); setIncludeViewProviders(previousIncludeViewProviders); factory.resolving = false; leaveDI(); } } return value; } /** * Returns the bit in an injector's bloom filter that should be used to determine whether or not * the directive might be provided by the injector. * * When a directive is public, it is added to the bloom filter and given a unique ID that can be * retrieved on the Type. When the directive isn't public or the token is not a directive `null` * is returned as the node injector can not possibly provide that token. * * @param token the injection token * @returns the matching bit to check in the bloom filter or `null` if the token is not known. * When the returned value is negative then it represents special values such as `Injector`. */
{ "end_byte": 29855, "start_byte": 22177, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/di.ts_29856_37657
xport function bloomHashBitOrFactory( token: ProviderToken<any> | string, ): number | Function | undefined { ngDevMode && assertDefined(token, 'token must be defined'); if (typeof token === 'string') { return token.charCodeAt(0) || 0; } const tokenId: number | undefined = // First check with `hasOwnProperty` so we don't get an inherited ID. token.hasOwnProperty(NG_ELEMENT_ID) ? (token as any)[NG_ELEMENT_ID] : undefined; // Negative token IDs are used for special objects such as `Injector` if (typeof tokenId === 'number') { if (tokenId >= 0) { return tokenId & BLOOM_MASK; } else { ngDevMode && assertEqual(tokenId, InjectorMarkers.Injector, 'Expecting to get Special Injector Id'); return createNodeInjector; } } else { return tokenId; } } export function bloomHasToken( bloomHash: number, injectorIndex: number, injectorView: LView | TData, ) { // Create a mask that targets the specific bit associated with the directive we're looking for. // JS bit operations are 32 bits, so this will be a number between 2^0 and 2^31, corresponding // to bit positions 0 - 31 in a 32 bit integer. const mask = 1 << bloomHash; // Each bloom bucket in `injectorView` represents `BLOOM_BUCKET_BITS` number of bits of // `bloomHash`. Any bits in `bloomHash` beyond `BLOOM_BUCKET_BITS` indicate the bucket offset // that should be used. const value = injectorView[injectorIndex + (bloomHash >> BLOOM_BUCKET_BITS)]; // If the bloom filter value has the bit corresponding to the directive's bloomBit flipped on, // this injector is a potential match. return !!(value & mask); } /** Returns true if flags prevent parent injector from being searched for tokens */ function shouldSearchParent(flags: InjectFlags, isFirstHostTNode: boolean): boolean | number { return !(flags & InjectFlags.Self) && !(flags & InjectFlags.Host && isFirstHostTNode); } export function getNodeInjectorLView(nodeInjector: NodeInjector): LView { return (nodeInjector as any)._lView as LView; } export function getNodeInjectorTNode( nodeInjector: NodeInjector, ): TElementNode | TContainerNode | TElementContainerNode | null { return (nodeInjector as any)._tNode as | TElementNode | TContainerNode | TElementContainerNode | null; } export class NodeInjector implements Injector { constructor( private _tNode: TElementNode | TContainerNode | TElementContainerNode | null, private _lView: LView, ) {} get(token: any, notFoundValue?: any, flags?: InjectFlags | InjectOptions): any { return getOrCreateInjectable( this._tNode, this._lView, token, convertToBitFlags(flags), notFoundValue, ); } } /** Creates a `NodeInjector` for the current node. */ export function createNodeInjector(): Injector { return new NodeInjector(getCurrentTNode()! as TDirectiveHostNode, getLView()) as any; } /** * @codeGenApi */ export function ɵɵgetInheritedFactory<T>(type: Type<any>): (type: Type<T>) => T { return noSideEffects(() => { const ownConstructor = type.prototype.constructor; const ownFactory = ownConstructor[NG_FACTORY_DEF] || getFactoryOf(ownConstructor); const objectPrototype = Object.prototype; let parent = Object.getPrototypeOf(type.prototype).constructor; // Go up the prototype until we hit `Object`. while (parent && parent !== objectPrototype) { const factory = parent[NG_FACTORY_DEF] || getFactoryOf(parent); // If we hit something that has a factory and the factory isn't the same as the type, // we've found the inherited factory. Note the check that the factory isn't the type's // own factory is redundant in most cases, but if the user has custom decorators on the // class, this lookup will start one level down in the prototype chain, causing us to // find the own factory first and potentially triggering an infinite loop downstream. if (factory && factory !== ownFactory) { return factory; } parent = Object.getPrototypeOf(parent); } // There is no factory defined. Either this was improper usage of inheritance // (no Angular decorator on the superclass) or there is no constructor at all // in the inheritance chain. Since the two cases cannot be distinguished, the // latter has to be assumed. return (t: Type<T>) => new t(); }); } function getFactoryOf<T>(type: Type<any>): ((type?: Type<T>) => T | null) | null { if (isForwardRef(type)) { return () => { const factory = getFactoryOf<T>(resolveForwardRef(type)); return factory && factory(); }; } return getFactoryDef<T>(type); } /** * Returns a value from the closest embedded or node injector. * * @param tNode The Node where the search for the injector should start * @param lView The `LView` that contains the `tNode` * @param token The token to look for * @param flags Injection flags * @param notFoundValue The value to return when the injection flags is `InjectFlags.Optional` * @returns the value from the injector, `null` when not found, or `notFoundValue` if provided */ function lookupTokenUsingEmbeddedInjector<T>( tNode: TDirectiveHostNode, lView: LView, token: ProviderToken<T>, flags: InjectFlags, notFoundValue?: any, ) { let currentTNode: TDirectiveHostNode | null = tNode; let currentLView: LView | null = lView; // When an LView with an embedded view injector is inserted, it'll likely be interlaced with // nodes who may have injectors (e.g. node injector -> embedded view injector -> node injector). // Since the bloom filters for the node injectors have already been constructed and we don't // have a way of extracting the records from an injector, the only way to maintain the correct // hierarchy when resolving the value is to walk it node-by-node while attempting to resolve // the token at each level. while ( currentTNode !== null && currentLView !== null && currentLView[FLAGS] & LViewFlags.HasEmbeddedViewInjector && !(currentLView[FLAGS] & LViewFlags.IsRoot) ) { ngDevMode && assertTNodeForLView(currentTNode, currentLView); // Note that this lookup on the node injector is using the `Self` flag, because // we don't want the node injector to look at any parent injectors since we // may hit the embedded view injector first. const nodeInjectorValue = lookupTokenUsingNodeInjector( currentTNode, currentLView, token, flags | InjectFlags.Self, NOT_FOUND, ); if (nodeInjectorValue !== NOT_FOUND) { return nodeInjectorValue; } // Has an explicit type due to a TS bug: https://github.com/microsoft/TypeScript/issues/33191 let parentTNode: TElementNode | TContainerNode | null = currentTNode.parent; // `TNode.parent` includes the parent within the current view only. If it doesn't exist, // it means that we've hit the view boundary and we need to go up to the next view. if (!parentTNode) { // Before we go to the next LView, check if the token exists on the current embedded injector. const embeddedViewInjector = currentLView[EMBEDDED_VIEW_INJECTOR]; if (embeddedViewInjector) { const embeddedViewInjectorValue = embeddedViewInjector.get( token, NOT_FOUND as T | {}, flags, ); if (embeddedViewInjectorValue !== NOT_FOUND) { return embeddedViewInjectorValue; } } // Otherwise keep going up the tree. parentTNode = getTNodeFromLView(currentLView); currentLView = currentLView[DECLARATION_VIEW]; } currentTNode = parentTNode; } return notFoundValue; } /** Gets the TNode associated with an LView inside of the declaration view. */ fu
{ "end_byte": 37657, "start_byte": 29856, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/di.ts_37658_38343
ction getTNodeFromLView(lView: LView): TElementNode | TElementContainerNode | null { const tView = lView[TVIEW]; const tViewType = tView.type; // The parent pointer differs based on `TView.type`. if (tViewType === TViewType.Embedded) { ngDevMode && assertDefined(tView.declTNode, 'Embedded TNodes should have declaration parents.'); return tView.declTNode as TElementContainerNode; } else if (tViewType === TViewType.Component) { // Components don't have `TView.declTNode` because each instance of component could be // inserted in different location, hence `TView.declTNode` is meaningless. return lView[T_HOST] as TElementNode; } return null; }
{ "end_byte": 38343, "start_byte": 37658, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/di.ts" }
angular/packages/core/src/render3/context_discovery.ts_0_8410
/** * @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 {assertDefined, assertDomNode} from '../util/assert'; import {EMPTY_ARRAY} from '../util/empty'; import {assertLView} from './assert'; import {LContext} from './interfaces/context'; import {getLViewById, registerLView} from './interfaces/lview_tracking'; import {TNode} from './interfaces/node'; import {RElement, RNode} from './interfaces/renderer_dom'; import {isLView} from './interfaces/type_checks'; import {CONTEXT, HEADER_OFFSET, HOST, ID, LView, TVIEW} from './interfaces/view'; import {getComponentLViewByIndex, unwrapRNode} from './util/view_utils'; /** * Returns the matching `LContext` data for a given DOM node, directive or component instance. * * This function will examine the provided DOM element, component, or directive instance\'s * monkey-patched property to derive the `LContext` data. Once called then the monkey-patched * value will be that of the newly created `LContext`. * * If the monkey-patched value is the `LView` instance then the context value for that * target will be created and the monkey-patch reference will be updated. Therefore when this * function is called it may mutate the provided element\'s, component\'s or any of the associated * directive\'s monkey-patch values. * * If the monkey-patch value is not detected then the code will walk up the DOM until an element * is found which contains a monkey-patch reference. When that occurs then the provided element * will be updated with a new context (which is then returned). If the monkey-patch value is not * detected for a component/directive instance then it will throw an error (all components and * directives should be automatically monkey-patched by ivy). * * @param target Component, Directive or DOM Node. */ export function getLContext(target: any): LContext | null { let mpValue = readPatchedData(target); if (mpValue) { // only when it's an array is it considered an LView instance // ... otherwise it's an already constructed LContext instance if (isLView(mpValue)) { const lView: LView = mpValue!; let nodeIndex: number; let component: any = undefined; let directives: any[] | null | undefined = undefined; if (isComponentInstance(target)) { nodeIndex = findViaComponent(lView, target); if (nodeIndex == -1) { throw new Error('The provided component was not found in the application'); } component = target; } else if (isDirectiveInstance(target)) { nodeIndex = findViaDirective(lView, target); if (nodeIndex == -1) { throw new Error('The provided directive was not found in the application'); } directives = getDirectivesAtNodeIndex(nodeIndex, lView); } else { nodeIndex = findViaNativeElement(lView, target as RElement); if (nodeIndex == -1) { return null; } } // the goal is not to fill the entire context full of data because the lookups // are expensive. Instead, only the target data (the element, component, container, ICU // expression or directive details) are filled into the context. If called multiple times // with different target values then the missing target data will be filled in. const native = unwrapRNode(lView[nodeIndex]); const existingCtx = readPatchedData(native); const context: LContext = existingCtx && !Array.isArray(existingCtx) ? existingCtx : createLContext(lView, nodeIndex, native); // only when the component has been discovered then update the monkey-patch if (component && context.component === undefined) { context.component = component; attachPatchData(context.component, context); } // only when the directives have been discovered then update the monkey-patch if (directives && context.directives === undefined) { context.directives = directives; for (let i = 0; i < directives.length; i++) { attachPatchData(directives[i], context); } } attachPatchData(context.native, context); mpValue = context; } } else { const rElement = target as RElement; ngDevMode && assertDomNode(rElement); // if the context is not found then we need to traverse upwards up the DOM // to find the nearest element that has already been monkey patched with data let parent = rElement as any; while ((parent = parent.parentNode)) { const parentContext = readPatchedData(parent); if (parentContext) { const lView = Array.isArray(parentContext) ? (parentContext as LView) : parentContext.lView; // the edge of the app was also reached here through another means // (maybe because the DOM was changed manually). if (!lView) { return null; } const index = findViaNativeElement(lView, rElement); if (index >= 0) { const native = unwrapRNode(lView[index]); const context = createLContext(lView, index, native); attachPatchData(native, context); mpValue = context; break; } } } } return (mpValue as LContext) || null; } /** * Creates an empty instance of a `LContext` context */ function createLContext(lView: LView, nodeIndex: number, native: RNode): LContext { return new LContext(lView[ID], nodeIndex, native); } /** * Takes a component instance and returns the view for that component. * * @param componentInstance * @returns The component's view */ export function getComponentViewByInstance(componentInstance: {}): LView { let patchedData = readPatchedData(componentInstance); let lView: LView; if (isLView(patchedData)) { const contextLView: LView = patchedData; const nodeIndex = findViaComponent(contextLView, componentInstance); lView = getComponentLViewByIndex(nodeIndex, contextLView); const context = createLContext(contextLView, nodeIndex, lView[HOST] as RElement); context.component = componentInstance; attachPatchData(componentInstance, context); attachPatchData(context.native, context); } else { const context = patchedData as unknown as LContext; const contextLView = context.lView!; ngDevMode && assertLView(contextLView); lView = getComponentLViewByIndex(context.nodeIndex, contextLView); } return lView; } /** * This property will be monkey-patched on elements, components and directives. */ const MONKEY_PATCH_KEY_NAME = '__ngContext__'; export function attachLViewId(target: any, data: LView) { target[MONKEY_PATCH_KEY_NAME] = data[ID]; } /** * Returns the monkey-patch value data present on the target (which could be * a component, directive or a DOM node). */ export function readLView(target: any): LView | null { const data = readPatchedData(target); if (isLView(data)) { return data; } return data ? data.lView : null; } /** * Assigns the given data to the given target (which could be a component, * directive or DOM node instance) using monkey-patching. */ export function attachPatchData(target: any, data: LView | LContext) { ngDevMode && assertDefined(target, 'Target expected'); // Only attach the ID of the view in order to avoid memory leaks (see #41047). We only do this // for `LView`, because we have control over when an `LView` is created and destroyed, whereas // we can't know when to remove an `LContext`. if (isLView(data)) { target[MONKEY_PATCH_KEY_NAME] = data[ID]; registerLView(data); } else { target[MONKEY_PATCH_KEY_NAME] = data; } } /** * Returns the monkey-patch value data present on the target (which could be * a component, directive or a DOM node). */ export function readPatchedData(target: any): LView | LContext | null { ngDevMode && assertDefined(target, 'Target expected'); const data = target[MONKEY_PATCH_KEY_NAME]; return typeof data === 'number' ? getLViewById(data) : data || null; } export function readPatchedLView<T>(target: any): LView<T> | null { const value = readPatchedData(target); if (value) { return (isLView(value) ? value : value.lView) as LView<T>; } return null; }
{ "end_byte": 8410, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/context_discovery.ts" }
angular/packages/core/src/render3/context_discovery.ts_8412_13068
export function isComponentInstance(instance: any): boolean { return instance && instance.constructor && instance.constructor.ɵcmp; } export function isDirectiveInstance(instance: any): boolean { return instance && instance.constructor && instance.constructor.ɵdir; } /** * Locates the element within the given LView and returns the matching index */ function findViaNativeElement(lView: LView, target: RElement): number { const tView = lView[TVIEW]; for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { if (unwrapRNode(lView[i]) === target) { return i; } } return -1; } /** * Locates the next tNode (child, sibling or parent). */ function traverseNextElement(tNode: TNode): TNode | null { if (tNode.child) { return tNode.child; } else if (tNode.next) { return tNode.next; } else { // Let's take the following template: <div><span>text</span></div><component/> // After checking the text node, we need to find the next parent that has a "next" TNode, // in this case the parent `div`, so that we can find the component. while (tNode.parent && !tNode.parent.next) { tNode = tNode.parent; } return tNode.parent && tNode.parent.next; } } /** * Locates the component within the given LView and returns the matching index */ function findViaComponent(lView: LView, componentInstance: {}): number { const componentIndices = lView[TVIEW].components; if (componentIndices) { for (let i = 0; i < componentIndices.length; i++) { const elementComponentIndex = componentIndices[i]; const componentView = getComponentLViewByIndex(elementComponentIndex, lView); if (componentView[CONTEXT] === componentInstance) { return elementComponentIndex; } } } else { const rootComponentView = getComponentLViewByIndex(HEADER_OFFSET, lView); const rootComponent = rootComponentView[CONTEXT]; if (rootComponent === componentInstance) { // we are dealing with the root element here therefore we know that the // element is the very first element after the HEADER data in the lView return HEADER_OFFSET; } } return -1; } /** * Locates the directive within the given LView and returns the matching index */ function findViaDirective(lView: LView, directiveInstance: {}): number { // if a directive is monkey patched then it will (by default) // have a reference to the LView of the current view. The // element bound to the directive being search lives somewhere // in the view data. We loop through the nodes and check their // list of directives for the instance. let tNode = lView[TVIEW].firstChild; while (tNode) { const directiveIndexStart = tNode.directiveStart; const directiveIndexEnd = tNode.directiveEnd; for (let i = directiveIndexStart; i < directiveIndexEnd; i++) { if (lView[i] === directiveInstance) { return tNode.index; } } tNode = traverseNextElement(tNode); } return -1; } /** * Returns a list of directives applied to a node at a specific index. The list includes * directives matched by selector and any host directives, but it excludes components. * Use `getComponentAtNodeIndex` to find the component applied to a node. * * @param nodeIndex The node index * @param lView The target view data */ export function getDirectivesAtNodeIndex(nodeIndex: number, lView: LView): any[] | null { const tNode = lView[TVIEW].data[nodeIndex] as TNode; if (tNode.directiveStart === 0) return EMPTY_ARRAY; const results: any[] = []; for (let i = tNode.directiveStart; i < tNode.directiveEnd; i++) { const directiveInstance = lView[i]; if (!isComponentInstance(directiveInstance)) { results.push(directiveInstance); } } return results; } export function getComponentAtNodeIndex(nodeIndex: number, lView: LView): {} | null { const tNode = lView[TVIEW].data[nodeIndex] as TNode; const {directiveStart, componentOffset} = tNode; return componentOffset > -1 ? lView[directiveStart + componentOffset] : null; } /** * Returns a map of local references (local reference name => element or directive instance) that * exist on a given element. */ export function discoverLocalRefs(lView: LView, nodeIndex: number): {[key: string]: any} | null { const tNode = lView[TVIEW].data[nodeIndex] as TNode; if (tNode && tNode.localNames) { const result: {[key: string]: any} = {}; let localIndex = tNode.index + 1; for (let i = 0; i < tNode.localNames.length; i += 2) { result[tNode.localNames[i]] = lView[localIndex]; localIndex++; } return result; } return null; }
{ "end_byte": 13068, "start_byte": 8412, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/context_discovery.ts" }
angular/packages/core/src/render3/query_reactive.ts_0_5532
/** * @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 {ComputedNode, createComputed, SIGNAL} from '@angular/core/primitives/signals'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import {unwrapElementRef} from '../linker/element_ref'; import {QueryList} from '../linker/query_list'; import {EMPTY_ARRAY} from '../util/empty'; import {FLAGS, LView, LViewFlags} from './interfaces/view'; import {getQueryResults, loadQueryInternal} from './query'; import {Signal} from './reactivity/api'; import {signal, WritableSignal} from './reactivity/signal'; import {getLView} from './state'; interface QuerySignalNode<T> extends ComputedNode<T | ReadonlyArray<T>> { _lView?: LView; _queryIndex?: number; _queryList?: QueryList<T>; _dirtyCounter: WritableSignal<number>; /** * Stores the last seen, flattened results for a query. This is to avoid marking the signal result * computed as dirty when there was view manipulation that didn't impact final results. */ _flatValue?: T | ReadonlyArray<T>; } /** * A signal factory function in charge of creating a new computed signal capturing query * results. This centralized creation function is used by all types of queries (child / children, * required / optional). * * @param firstOnly indicates if all or only the first result should be returned * @param required indicates if at least one result is required * @returns a read-only signal with query results */ function createQuerySignalFn<V>( firstOnly: boolean, required: boolean, opts?: {debugName?: string}, ) { let node: QuerySignalNode<V>; const signalFn = createComputed(() => { // A dedicated signal that increments its value every time a query changes its dirty status. By // using this signal we can implement a query as computed and avoid creation of a specialized // reactive node type. Please note that a query gets marked dirty under the following // circumstances: // - a view (where a query is active) finished its first creation pass; // - a new view is inserted / deleted and it impacts query results. node._dirtyCounter(); const value = refreshSignalQuery<V>(node, firstOnly); if (required && value === undefined) { throw new RuntimeError( RuntimeErrorCode.REQUIRED_QUERY_NO_VALUE, ngDevMode && 'Child query result is required but no value is available.', ); } return value; }); node = signalFn[SIGNAL] as QuerySignalNode<V>; node._dirtyCounter = signal(0); node._flatValue = undefined; if (ngDevMode) { signalFn.toString = () => `[Query Signal]`; node.debugName = opts?.debugName; } return signalFn; } export function createSingleResultOptionalQuerySignalFn<ReadT>(opts?: { debugName?: string; }): Signal<ReadT | undefined> { return createQuerySignalFn(/* firstOnly */ true, /* required */ false, opts) as Signal< ReadT | undefined >; } export function createSingleResultRequiredQuerySignalFn<ReadT>(opts?: { debugName?: string; }): Signal<ReadT> { return createQuerySignalFn(/* firstOnly */ true, /* required */ true, opts) as Signal<ReadT>; } export function createMultiResultQuerySignalFn<ReadT>(opts?: { debugName?: string; }): Signal<ReadonlyArray<ReadT>> { return createQuerySignalFn(/* firstOnly */ false, /* required */ false, opts) as Signal< ReadonlyArray<ReadT> >; } export function bindQueryToSignal(target: Signal<unknown>, queryIndex: number): void { const node = target[SIGNAL] as QuerySignalNode<unknown>; node._lView = getLView(); node._queryIndex = queryIndex; node._queryList = loadQueryInternal(node._lView, queryIndex); node._queryList.onDirty(() => node._dirtyCounter.update((v) => v + 1)); } function refreshSignalQuery<V>(node: QuerySignalNode<V>, firstOnly: boolean): V | ReadonlyArray<V> { const lView = node._lView; const queryIndex = node._queryIndex; // There are 2 conditions under which we want to return "empty" results instead of the ones // collected by a query: // // 1) a given query wasn't created yet (this is a period of time between the directive creation // and execution of the query creation function) - in this case a query doesn't exist yet and we // don't have any results to return. // // 2) we are in the process of constructing a view (the first // creation pass didn't finish) and a query might have partial results, but we don't want to // return those - instead we do delay results collection until all nodes had a chance of matching // and we can present consistent, "atomic" (on a view level) results. if (lView === undefined || queryIndex === undefined || lView[FLAGS] & LViewFlags.CreationMode) { return (firstOnly ? undefined : EMPTY_ARRAY) as V; } const queryList = loadQueryInternal<V>(lView, queryIndex); const results = getQueryResults<V>(lView, queryIndex); queryList.reset(results, unwrapElementRef); if (firstOnly) { return queryList.first; } else { // TODO: remove access to the private _changesDetected field by abstracting / removing usage of // QueryList in the signal-based queries (perf follow-up) const resultChanged = (queryList as any as {_changesDetected: boolean})._changesDetected; if (resultChanged || node._flatValue === undefined) { return (node._flatValue = queryList.toArray()); } return node._flatValue; } }
{ "end_byte": 5532, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/query_reactive.ts" }
angular/packages/core/src/render3/global_utils_api.ts_0_892
/** * @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 */ /** * @fileoverview * This file is the index file collecting all of the symbols published on the global.ng namespace. * * The reason why this file/module is separate global_utils.ts file is that we use this file * to generate a d.ts file containing all the published symbols that is then compared to the golden * file in the public_api_guard test. */ export {applyChanges} from './util/change_detection_utils'; export { ComponentDebugMetadata, DirectiveDebugMetadata, getComponent, getContext, getDirectiveMetadata, getDirectives, getHostElement, getInjector, getListeners, getOwningComponent, getRootComponents, Listener, } from './util/discovery_utils';
{ "end_byte": 892, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/global_utils_api.ts" }
angular/packages/core/src/render3/list_reconciliation.ts_0_3831
/** * @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 {TrackByFunction} from '../change_detection'; import {formatRuntimeError, RuntimeErrorCode} from '../errors'; import {assertNotSame} from '../util/assert'; import {stringifyForError} from './util/stringify_utils'; /** * A type representing the live collection to be reconciled with any new (incoming) collection. This * is an adapter class that makes it possible to work with different internal data structures, * regardless of the actual values of the incoming collection. */ export abstract class LiveCollection<T, V> { abstract get length(): number; abstract at(index: number): V; abstract attach(index: number, item: T): void; abstract detach(index: number): T; abstract create(index: number, value: V): T; destroy(item: T): void { // noop by default } updateValue(index: number, value: V): void { // noop by default } // operations below could be implemented on top of the operations defined so far, but having // them explicitly allow clear expression of intent and potentially more performant // implementations swap(index1: number, index2: number): void { const startIdx = Math.min(index1, index2); const endIdx = Math.max(index1, index2); const endItem = this.detach(endIdx); if (endIdx - startIdx > 1) { const startItem = this.detach(startIdx); this.attach(startIdx, endItem); this.attach(endIdx, startItem); } else { this.attach(startIdx, endItem); } } move(prevIndex: number, newIdx: number): void { this.attach(newIdx, this.detach(prevIndex)); } } function valuesMatching<V>( liveIdx: number, liveValue: V, newIdx: number, newValue: V, trackBy: TrackByFunction<V>, ): number { if (liveIdx === newIdx && Object.is(liveValue, newValue)) { // matching and no value identity to update return 1; } else if (Object.is(trackBy(liveIdx, liveValue), trackBy(newIdx, newValue))) { // matching but requires value identity update return -1; } return 0; } function recordDuplicateKeys(keyToIdx: Map<unknown, Set<number>>, key: unknown, idx: number): void { const idxSoFar = keyToIdx.get(key); if (idxSoFar !== undefined) { idxSoFar.add(idx); } else { keyToIdx.set(key, new Set([idx])); } } /** * The live collection reconciliation algorithm that perform various in-place operations, so it * reflects the content of the new (incoming) collection. * * The reconciliation algorithm has 2 code paths: * - "fast" path that don't require any memory allocation; * - "slow" path that requires additional memory allocation for intermediate data structures used to * collect additional information about the live collection. * It might happen that the algorithm switches between the two modes in question in a single * reconciliation path - generally it tries to stay on the "fast" path as much as possible. * * The overall complexity of the algorithm is O(n + m) for speed and O(n) for memory (where n is the * length of the live collection and m is the length of the incoming collection). Given the problem * at hand the complexity / performance constraints makes it impossible to perform the absolute * minimum of operation to reconcile the 2 collections. The algorithm makes different tradeoffs to * stay within reasonable performance bounds and may apply sub-optimal number of operations in * certain situations. * * @param liveCollection the current, live collection; * @param newCollection the new, incoming collection; * @param trackByFn key generation function that determines equality between items in the life and * incoming collection; */
{ "end_byte": 3831, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/list_reconciliation.ts" }
angular/packages/core/src/render3/list_reconciliation.ts_3832_12253
export function reconcile<T, V>( liveCollection: LiveCollection<T, V>, newCollection: Iterable<V> | undefined | null, trackByFn: TrackByFunction<V>, ): void { let detachedItems: UniqueValueMultiKeyMap<unknown, T> | undefined = undefined; let liveKeysInTheFuture: Set<unknown> | undefined = undefined; let liveStartIdx = 0; let liveEndIdx = liveCollection.length - 1; const duplicateKeys = ngDevMode ? new Map<unknown, Set<number>>() : undefined; if (Array.isArray(newCollection)) { let newEndIdx = newCollection.length - 1; while (liveStartIdx <= liveEndIdx && liveStartIdx <= newEndIdx) { // compare from the beginning const liveStartValue = liveCollection.at(liveStartIdx); const newStartValue = newCollection[liveStartIdx]; if (ngDevMode) { recordDuplicateKeys(duplicateKeys!, trackByFn(liveStartIdx, newStartValue), liveStartIdx); } const isStartMatching = valuesMatching( liveStartIdx, liveStartValue, liveStartIdx, newStartValue, trackByFn, ); if (isStartMatching !== 0) { if (isStartMatching < 0) { liveCollection.updateValue(liveStartIdx, newStartValue); } liveStartIdx++; continue; } // compare from the end // TODO(perf): do _all_ the matching from the end const liveEndValue = liveCollection.at(liveEndIdx); const newEndValue = newCollection[newEndIdx]; if (ngDevMode) { recordDuplicateKeys(duplicateKeys!, trackByFn(newEndIdx, newEndValue), newEndIdx); } const isEndMatching = valuesMatching( liveEndIdx, liveEndValue, newEndIdx, newEndValue, trackByFn, ); if (isEndMatching !== 0) { if (isEndMatching < 0) { liveCollection.updateValue(liveEndIdx, newEndValue); } liveEndIdx--; newEndIdx--; continue; } // Detect swap and moves: const liveStartKey = trackByFn(liveStartIdx, liveStartValue); const liveEndKey = trackByFn(liveEndIdx, liveEndValue); const newStartKey = trackByFn(liveStartIdx, newStartValue); if (Object.is(newStartKey, liveEndKey)) { const newEndKey = trackByFn(newEndIdx, newEndValue); // detect swap on both ends; if (Object.is(newEndKey, liveStartKey)) { liveCollection.swap(liveStartIdx, liveEndIdx); liveCollection.updateValue(liveEndIdx, newEndValue); newEndIdx--; liveEndIdx--; } else { // the new item is the same as the live item with the end pointer - this is a move forward // to an earlier index; liveCollection.move(liveEndIdx, liveStartIdx); } liveCollection.updateValue(liveStartIdx, newStartValue); liveStartIdx++; continue; } // Fallback to the slow path: we need to learn more about the content of the live and new // collections. detachedItems ??= new UniqueValueMultiKeyMap(); liveKeysInTheFuture ??= initLiveItemsInTheFuture( liveCollection, liveStartIdx, liveEndIdx, trackByFn, ); // Check if I'm inserting a previously detached item: if so, attach it here if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newStartKey)) { liveCollection.updateValue(liveStartIdx, newStartValue); liveStartIdx++; liveEndIdx++; } else if (!liveKeysInTheFuture.has(newStartKey)) { // Check if we seen a new item that doesn't exist in the old collection and must be INSERTED const newItem = liveCollection.create(liveStartIdx, newCollection[liveStartIdx]); liveCollection.attach(liveStartIdx, newItem); liveStartIdx++; liveEndIdx++; } else { // We know that the new item exists later on in old collection but we don't know its index // and as the consequence can't move it (don't know where to find it). Detach the old item, // hoping that it unlocks the fast path again. detachedItems.set(liveStartKey, liveCollection.detach(liveStartIdx)); liveEndIdx--; } } // Final cleanup steps: // - more items in the new collection => insert while (liveStartIdx <= newEndIdx) { createOrAttach( liveCollection, detachedItems, trackByFn, liveStartIdx, newCollection[liveStartIdx], ); liveStartIdx++; } } else if (newCollection != null) { // iterable - immediately fallback to the slow path const newCollectionIterator = newCollection[Symbol.iterator](); let newIterationResult = newCollectionIterator.next(); while (!newIterationResult.done && liveStartIdx <= liveEndIdx) { const liveValue = liveCollection.at(liveStartIdx); const newValue = newIterationResult.value; if (ngDevMode) { recordDuplicateKeys(duplicateKeys!, trackByFn(liveStartIdx, newValue), liveStartIdx); } const isStartMatching = valuesMatching( liveStartIdx, liveValue, liveStartIdx, newValue, trackByFn, ); if (isStartMatching !== 0) { // found a match - move on, but update value if (isStartMatching < 0) { liveCollection.updateValue(liveStartIdx, newValue); } liveStartIdx++; newIterationResult = newCollectionIterator.next(); } else { detachedItems ??= new UniqueValueMultiKeyMap(); liveKeysInTheFuture ??= initLiveItemsInTheFuture( liveCollection, liveStartIdx, liveEndIdx, trackByFn, ); // Check if I'm inserting a previously detached item: if so, attach it here const newKey = trackByFn(liveStartIdx, newValue); if (attachPreviouslyDetached(liveCollection, detachedItems, liveStartIdx, newKey)) { liveCollection.updateValue(liveStartIdx, newValue); liveStartIdx++; liveEndIdx++; newIterationResult = newCollectionIterator.next(); } else if (!liveKeysInTheFuture.has(newKey)) { liveCollection.attach(liveStartIdx, liveCollection.create(liveStartIdx, newValue)); liveStartIdx++; liveEndIdx++; newIterationResult = newCollectionIterator.next(); } else { // it is a move forward - detach the current item without advancing in collections const liveKey = trackByFn(liveStartIdx, liveValue); detachedItems.set(liveKey, liveCollection.detach(liveStartIdx)); liveEndIdx--; } } } // this is a new item as we run out of the items in the old collection - create or attach a // previously detached one while (!newIterationResult.done) { createOrAttach( liveCollection, detachedItems, trackByFn, liveCollection.length, newIterationResult.value, ); newIterationResult = newCollectionIterator.next(); } } // Cleanups common to the array and iterable: // - more items in the live collection => delete starting from the end; while (liveStartIdx <= liveEndIdx) { liveCollection.destroy(liveCollection.detach(liveEndIdx--)); } // - destroy items that were detached but never attached again. detachedItems?.forEach((item) => { liveCollection.destroy(item); }); // report duplicate keys (dev mode only) if (ngDevMode) { let duplicatedKeysMsg = []; for (const [key, idxSet] of duplicateKeys!) { if (idxSet.size > 1) { const idx = [...idxSet].sort((a, b) => a - b); for (let i = 1; i < idx.length; i++) { duplicatedKeysMsg.push( `key "${stringifyForError(key)}" at index "${idx[i - 1]}" and "${idx[i]}"`, ); } } } if (duplicatedKeysMsg.length > 0) { const message = formatRuntimeError( RuntimeErrorCode.LOOP_TRACK_DUPLICATE_KEYS, 'The provided track expression resulted in duplicated keys for a given collection. ' + 'Adjust the tracking expression such that it uniquely identifies all the items in the collection. ' + 'Duplicated keys were: \n' + duplicatedKeysMsg.join(', \n') + '.', ); // tslint:disable-next-line:no-console console.warn(message); } } }
{ "end_byte": 12253, "start_byte": 3832, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/list_reconciliation.ts" }
angular/packages/core/src/render3/list_reconciliation.ts_12255_15843
function attachPreviouslyDetached<T, V>( prevCollection: LiveCollection<T, V>, detachedItems: UniqueValueMultiKeyMap<unknown, T> | undefined, index: number, key: unknown, ): boolean { if (detachedItems !== undefined && detachedItems.has(key)) { prevCollection.attach(index, detachedItems.get(key)!); detachedItems.delete(key); return true; } return false; } function createOrAttach<T, V>( liveCollection: LiveCollection<T, V>, detachedItems: UniqueValueMultiKeyMap<unknown, T> | undefined, trackByFn: TrackByFunction<unknown>, index: number, value: V, ) { if (!attachPreviouslyDetached(liveCollection, detachedItems, index, trackByFn(index, value))) { const newItem = liveCollection.create(index, value); liveCollection.attach(index, newItem); } else { liveCollection.updateValue(index, value); } } function initLiveItemsInTheFuture<T>( liveCollection: LiveCollection<unknown, unknown>, start: number, end: number, trackByFn: TrackByFunction<unknown>, ): Set<unknown> { const keys = new Set(); for (let i = start; i <= end; i++) { keys.add(trackByFn(i, liveCollection.at(i))); } return keys; } /** * A specific, partial implementation of the Map interface with the following characteristics: * - allows multiple values for a given key; * - maintain FIFO order for multiple values corresponding to a given key; * - assumes that all values are unique. * * The implementation aims at having the minimal overhead for cases where keys are _not_ duplicated * (the most common case in the list reconciliation algorithm). To achieve this, the first value for * a given key is stored in a regular map. Then, when more values are set for a given key, we * maintain a form of linked list in a separate map. To maintain this linked list we assume that all * values (in the entire collection) are unique. */ export class UniqueValueMultiKeyMap<K, V> { // A map from a key to the first value corresponding to this key. private kvMap = new Map<K, V>(); // A map that acts as a linked list of values - each value maps to the next value in this "linked // list" (this only works if values are unique). Allocated lazily to avoid memory consumption when // there are no duplicated values. private _vMap: Map<V, V> | undefined = undefined; has(key: K): boolean { return this.kvMap.has(key); } delete(key: K): boolean { if (!this.has(key)) return false; const value = this.kvMap.get(key)!; if (this._vMap !== undefined && this._vMap.has(value)) { this.kvMap.set(key, this._vMap.get(value)!); this._vMap.delete(value); } else { this.kvMap.delete(key); } return true; } get(key: K): V | undefined { return this.kvMap.get(key); } set(key: K, value: V): void { if (this.kvMap.has(key)) { let prevValue = this.kvMap.get(key)!; ngDevMode && assertNotSame(prevValue, value, `Detected a duplicated value ${value} for the key ${key}`); if (this._vMap === undefined) { this._vMap = new Map(); } const vMap = this._vMap; while (vMap.has(prevValue)) { prevValue = vMap.get(prevValue)!; } vMap.set(prevValue, value); } else { this.kvMap.set(key, value); } } forEach(cb: (v: V, k: K) => void) { for (let [key, value] of this.kvMap) { cb(value, key); if (this._vMap !== undefined) { const vMap = this._vMap; while (vMap.has(value)) { value = vMap.get(value)!; cb(value, key); } } } } }
{ "end_byte": 15843, "start_byte": 12255, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/list_reconciliation.ts" }
angular/packages/core/src/render3/definition_factory.ts_0_1268
/** * @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 {stringify} from '../util/stringify'; import {NG_FACTORY_DEF} from './fields'; /** * Definition of what a factory function should look like. */ export type FactoryFn<T> = { /** * Subclasses without an explicit constructor call through to the factory of their base * definition, providing it with their own constructor to instantiate. */ <U extends T>(t?: Type<U>): U; /** * If no constructor to instantiate is provided, an instance of type T itself is created. */ (t?: undefined): T; }; export function getFactoryDef<T>(type: any, throwNotFound: true): FactoryFn<T>; export function getFactoryDef<T>(type: any): FactoryFn<T> | null; export function getFactoryDef<T>(type: any, throwNotFound?: boolean): FactoryFn<T> | null { const hasFactoryDef = type.hasOwnProperty(NG_FACTORY_DEF); if (!hasFactoryDef && throwNotFound === true && ngDevMode) { throw new Error(`Type ${stringify(type)} does not have 'ɵfac' property.`); } return hasFactoryDef ? type[NG_FACTORY_DEF] : null; }
{ "end_byte": 1268, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/definition_factory.ts" }
angular/packages/core/src/render3/node_assert.ts_0_1256
/** * @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 {assertDefined, throwError} from '../util/assert'; import {TNode, TNodeType, toTNodeTypeAsString} from './interfaces/node'; export function assertTNodeType( tNode: TNode | null, expectedTypes: TNodeType, message?: string, ): void { assertDefined(tNode, 'should be called with a TNode'); if ((tNode.type & expectedTypes) === 0) { throwError( message || `Expected [${toTNodeTypeAsString(expectedTypes)}] but got ${toTNodeTypeAsString( tNode.type, )}.`, ); } } export function assertPureTNodeType(type: TNodeType) { if ( !( type === TNodeType.Element || type === TNodeType.Text || type === TNodeType.Container || type === TNodeType.ElementContainer || type === TNodeType.Icu || type === TNodeType.Projection || type === TNodeType.Placeholder || type === TNodeType.LetDeclaration ) ) { throwError( `Expected TNodeType to have only a single type selected, but got ${toTNodeTypeAsString( type, )}.`, ); } }
{ "end_byte": 1256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_assert.ts" }
angular/packages/core/src/render3/VIEW_DATA.md_0_5961
# View Data Explanation `LView` and `TView.data` are how the Ivy renderer keeps track of the internal data needed to render the template. `LView` is designed so that a single array can contain all of the necessary data for the template rendering in a compact form. `TView.data` is a corollary to the `LView` and contains information which can be shared across the template instances. ## `LView` / `TView.data` layout. Both `LView` and `TView.data` are arrays whose indices refer to the same item. For example index `123` may point to a component instance in the `LView` but a component type in `TView.data`. The layout is as such: | Section | `LView` | `TView.data` | ---------- | ------------------------------------------------------------ | -------------------------------------------------- | `HEADER` | contextual data | mostly `null` | `DECLS` | DOM, pipe, and local ref instances | | `VARS` | binding values | property names | `EXPANDO` | host bindings; directive instances; providers; dynamic nodes | host prop names; directive tokens; provider tokens; `null` ## `HEADER` `HEADER` is a fixed array size which contains contextual information about the template. Mostly information such as parent `LView`, `Sanitizer`, `TView`, and many more bits of information needed for template rendering. ## `DECLS` `DECLS` contain the DOM elements, pipe instances, and local refs. The size of the `DECLS` section is declared in the property `decls` of the component definition. ```typescript @Component({ template: `<div>Hello <b>World</b>!</div>` }) class MyApp { static ɵcmp = ɵɵdefineComponent({ ..., decls: 5, template: function(rf: RenderFlags, ctx: MyApp) { if (rf & RenderFlags.Create) { ɵɵelementStart(0, 'div'); ɵɵtext(1, 'Hello '); ɵɵelementStart(2, 'b'); ɵɵtext(3, 'World'); ɵɵelementEnd(); ɵɵtext(4, '!'); ɵɵelementEnd(); } ... } }); } ``` The above will create following layout: | Index | `LView` | `TView.data` | ----: | ----------- | ------------ | `HEADER` | `DECLS` | 10 | `<div>` | `{type: Element, index: 10, parent: null}` | 11 | `#text(Hello )` | `{type: Element, index: 11, parent: tView.data[10]}` | 12 | `<b>` | `{type: Element, index: 12, parent: tView.data[10]}` | 13 | `#text(World)` | `{type: Element, index: 13, parent: tView.data[12]}` | 14 | `#text(!)` | `{type: Element, index: 14, parent: tView.data[10]}` | ... | ... | ... NOTE: - The `10` is not the actual size of `HEADER` but it is left here for simplification. - `LView` contains DOM instances only - `TView.data` contains information on relationships such as where the parent is. You need the `TView.data` information to make sense of the `LView` information. ## `VARS` `VARS` contains information on how to process the bindings. The size of the `VARS `section is declared in the property `vars` of the component definition. ```typescript @Component({ template: `<div title="{{name}}">Hello {{name}}!</div>` }) class MyApp { name = 'World'; static ɵcmp = ɵɵdefineComponent({ ..., decls: 2, // Two DOM Elements. vars: 2, // Two bindings. template: function(rf: RenderFlags, ctx: MyApp) { if (rf & RenderFlags.Create) { ɵɵelementStart(0, 'div'); ɵɵtext(1); ɵɵelementEnd(); } if (rf & RenderFlags.Update) { ɵɵproperty('title', ctx.name); ɵɵadvance(); ɵɵtextInterpolate1('Hello ', ctx.name, '!'); } ... } }); } ``` The above will create following layout: | Index | `LView` | `TView.data` | ----: | ----------- | ------------ | `HEADER` | `DECLS` | 10 | `<div>` | `{type: Element, index: 10, parent: null}` | 11 | `#text()` | `{type: Element, index: 11, parent: tView.data[10]}` | `VARS` | 12 | `'World'` | `'title'` | 13 | `'World'` | `null` | ... | ... | ... NOTE: - `LView` contain DOM instances and previous binding values only - `TView.data` contains information on relationships and property labels. ## `EXPANDO` `EXPANDO` contains information on data which size is not known at compile time. Examples include: - `Component`/`Directives` since we don't know at compile time which directives will match. - Host bindings, since until we match the directives it is unclear how many host bindings need to be allocated. ```typescript @Component({ template: `<child tooltip></child>` }) class MyApp { static ɵcmp = ɵɵdefineComponent({ ..., decls: 1, template: function(rf: RenderFlags, ctx: MyApp) { if (rf & RenderFlags.Create) { ɵɵelement(0, 'child', ['tooltip', null]); } ... }, directives: [Child, Tooltip] }); } @Component({ selector: 'child', ... }) class Child { @HostBinding('tooltip') hostTitle = 'Hello World!'; static ɵcmp = ɵɵdefineComponent({ ... hostVars: 1 }); ... } @Directive({ selector: '[tooltip]' }) class Tooltip { @HostBinding('title') hostTitle = 'greeting'; static ɵdir = ɵɵdefineDirective({ ... hostVars: 1 }); ... } ``` The above will create the following layout: | Index | `LView` | `TView.data` | ----: | ----------- | ------------ | `HEADER` | `DECLS` | 10 | `[<child>, ...]` | `{type: Element, index: 10, parent: null}` | `VARS` | `EXPANDO` | 11..18| cumulativeBloom | templateBloom | 19 | `new Child()` | `Child` | 20 | `new Tooltip()` | `Tooltip` | 21 | `'Hello World!'` | `'tooltip'` | 22 | `'greeting'` | `'title'` | ... | ... | ... ## `EXPANDO` and Injection `EXPANDO` will
{ "end_byte": 5961, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/VIEW_DATA.md" }
angular/packages/core/src/render3/VIEW_DATA.md_5961_13112
also store the injection information for the element. This is because at the time of compilation we don't know about all of the injection tokens which will need to be created. (The injection tokens are part of the Component hence hide behind a selector and are not available to the parent component.) Injection needs to store three things: - The injection token stored in `TView.data` - The token factory stored in `LProtoViewData` and subsequently in `LView` - The value for the injection token stored in `LView`. (Replacing token factory upon creation). To save time when creating `LView` we use an array clone operation to copy data from `LProtoViewdata` to `LView`. The `LProtoViewData` is initialized by the `ProvidesFeature`. Injection tokens are sorted into three sections: 1. `directives`: Used to denote eagerly created items representing directives and component. 2. `providers`: Used to denote items visible to component, component's view and component's content. 3. `viewProviders`: Used to denote items only visible to the component's view. ```typescript @Component({ template: `<child></child>` }) class MyApp { static ɵcmp = ɵɵdefineComponent({ ..., decls: 1, template: function(rf: RenderFlags, ctx: MyApp) { if (rf & RenderFlags.Create) { ɵɵelement(0, 'child'); } ... }, directives: [Child] }); } @Component({ selector: 'child', providers: [ ServiceA, {provide: ServiceB, useValue: 'someServiceBValue'}, ], viewProviders: [ {provide: ServiceC, useFactory: () => new ServiceC)} {provide: ServiceD, useClass: ServiceE}, ] ... }) class Child { construction(injector: Injector) {} static ɵcmp = ɵɵdefineComponent({ ... features: [ ProvidesFeature( [ ServiceA, {provide: ServiceB, useValue: 'someServiceBValue'}, ],[ {provide: ServiceC, useFactory: () => new ServiceC())} {provide: ServiceD, useClass: ServiceE}, ] ) ] }); ... } ``` The above will create the following layout: | Index | `LView` | `TView.data` | ----: | ------------ | ------------- | `HEADER` | `DECLS` | 10 | `[<child>, ...]` | `{type: Element, index: 10, parent: null, expandoIndex: 11, directivesIndex: 19, providersIndex: 20, viewProvidersIndex: 22, expandoEnd: 23}` | `VARS` | `EXPANDO` | 11..18| cumulativeBloom | templateBloom | | *sub-section: `component` and `directives`* | 19 | `factory(Child.ɵcmp.factory)`* | `Child` | | *sub-section: `providers`* | 20 | `factory(ServiceA.ɵprov.factory)`* | `ServiceA` | 22 | `'someServiceBValue'`* | `ServiceB` | | *sub-section: `viewProviders`* | 22 | `factory(()=> new Service())`* | `ServiceC` | 22 | `factory(()=> directiveInject(ServiceE))`* | `ServiceD` | ... | ... | ... NOTICE: - `*` denotes initial value copied from the `LProtoViewData`, as the tokens get instantiated the factories are replaced with actual value. - That `TView.data` has `expando` and `expandoInjectorCount` properties which point to where the element injection data is stored. - That all injectable tokens are stored in linear sequence making it easy to search for instances to match. - That `directive` sub-section gets eagerly instantiated. Where `factory` is a function which wraps the factory into object which can be monomorphically detected at runtime in an efficient way. ```TypeScript class Factory { /// Marker set to true during factory invocation to see if we get into recursive loop. /// Recursive loop causes an error to be displayed. resolving = false; constructor(public factory: Function) { } } function factory(fn) { return new Factory(fn); } const FactoryPrototype = Factory.prototype; function isFactory(obj: any): obj is Factory { // See: https://jsperf.com/instanceof-vs-getprototypeof return typeof obj === 'object' && Object.getPrototypeOf(obj) === FactoryPrototype; } ``` Pseudo code: 1. Check if bloom filter has the value of the token. (If not exit) 2. Locate the token in the expando honoring `directives`, `providers` and `viewProvider` rules by limiting the search scope. 3. Read the value of `lView[index]` at that location. - if `isFactory(lView[index])` then mark it as resolving and invoke it. Replace `lView[index]` with the value returned from factory (caching mechanism). - if `!isFactory(lView[index])` then return the cached value as is. # `EXPANDO` and Injecting Special Objects. There are several special objects such as `ElementRef`, `ViewContainerRef`, etc... These objects behave as if they are always included in the `providers` array of every component and directive. Adding them always there would prevent tree shaking so they need to be lazily included. NOTE: An interesting thing about these objects is that they are not memoized `injector.get(ElementRef) !== injector.get(ElementRef)`. This could be considered a bug, it means that we don't have to allocate storage space for them. We should treat these special objects like any other token. `directiveInject()` already reads a special `NG_ELEMENT_ID` property set on directives to locate their bit in the bloom filter. We can set this same property on special objects, but point to a factory function rather than an element ID number. When we check that property in `directiveInject()` and see that it's a function, we know to invoke the factory function directly instead of searching the node tree. ```typescript class ElementRef { ... static __NG_ELEMENT_ID__ = () => injectElementRef(); } ``` Consequence of the above is that `directiveInject(ElementRef)` returns an instance of `ElementRef` without `Injector` having to know about `ElementRef` at compile time. # `EXPANDO` and Injecting the `Injector`. `Injector` can be injected using `inject(Injector)` method. To achieve this in tree shakable way we can declare the `Injector` in this way: ```typescript @Injectable({ provideIn: '__node_injector__' as any // Special token not available to the developer }) class Injector { ... } ``` NOTE: We can't declare `useFactory` in this case because it would make the generic DI system depend on the Ivy renderer. Instead we have unique token `'__node_injector__'` which we use for recognizing the `Injector` in tree shakable way. ## `inject` Implementation A pseudo-implementation of `inject` function. ```typescript function inject(token: any): any { let injectableDef; if (typeof token === 'function' && injectableDef = token.ɵprov) { const provideIn = injectableDef.provideIn; if (provideIn === '__node_injector__') { // if we are injecting `Injector` than create a wrapper object around the inject but which // is bound to the current node. return createInjector(); } } return lookupTokenInExpando(token); } ``` # `LContainer` TODO ## Combining `LContainer` with `LView` TODO
{ "end_byte": 13112, "start_byte": 5961, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/VIEW_DATA.md" }
angular/packages/core/src/render3/index.ts_0_6007
/** * @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 {LifecycleHooksFeature} from './component_ref'; import {ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineNgModule, ɵɵdefinePipe} from './definition'; import {ɵɵCopyDefinitionFeature} from './features/copy_definition_feature'; import {ɵɵHostDirectivesFeature} from './features/host_directives_feature'; import {ɵɵInheritDefinitionFeature} from './features/inherit_definition_feature'; import {ɵɵInputTransformsFeature} from './features/input_transforms_feature'; import {ɵɵNgOnChangesFeature} from './features/ng_onchanges_feature'; import {ɵɵProvidersFeature} from './features/providers_feature'; import {ɵɵExternalStylesFeature} from './features/external_styles_feature'; import { ComponentDef, ComponentTemplate, ComponentType, DirectiveDef, DirectiveType, PipeDef, } from './interfaces/definition'; import { ɵɵComponentDeclaration, ɵɵDirectiveDeclaration, ɵɵFactoryDeclaration, ɵɵInjectorDeclaration, ɵɵNgModuleDeclaration, ɵɵPipeDeclaration, } from './interfaces/public_definitions'; import {ɵɵsetComponentScope, ɵɵsetNgModuleScope} from './scope'; import { ComponentDebugMetadata, DirectiveDebugMetadata, getComponent, getDirectiveMetadata, getDirectives, getHostElement, getRenderedText, } from './util/discovery_utils'; export {NgModuleType} from '../metadata/ng_module_def'; export {ComponentFactory, ComponentFactoryResolver, ComponentRef} from './component_ref'; export {ɵɵgetInheritedFactory} from './di'; export {getLocaleId, setLocaleId} from './i18n/i18n_locale_id'; export { store, ɵɵadvance, ɵɵattribute, ɵɵattributeInterpolate1, ɵɵattributeInterpolate2, ɵɵattributeInterpolate3, ɵɵattributeInterpolate4, ɵɵattributeInterpolate5, ɵɵattributeInterpolate6, ɵɵattributeInterpolate7, ɵɵattributeInterpolate8, ɵɵattributeInterpolateV, ɵɵclassMap, ɵɵclassMapInterpolate1, ɵɵclassMapInterpolate2, ɵɵclassMapInterpolate3, ɵɵclassMapInterpolate4, ɵɵclassMapInterpolate5, ɵɵclassMapInterpolate6, ɵɵclassMapInterpolate7, ɵɵclassMapInterpolate8, ɵɵclassMapInterpolateV, ɵɵclassProp, ɵɵcomponentInstance, ɵɵdirectiveInject, ɵɵelement, ɵɵelementContainer, ɵɵelementContainerEnd, ɵɵelementContainerStart, ɵɵelementEnd, ɵɵelementStart, ɵɵgetCurrentView, ɵɵhostProperty, ɵɵinjectAttribute, ɵɵinvalidFactory, ɵɵlistener, ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG, ɵɵnextContext, ɵɵprojection, ɵɵprojectionDef, ɵɵproperty, ɵɵpropertyInterpolate, ɵɵpropertyInterpolate1, ɵɵpropertyInterpolate2, ɵɵpropertyInterpolate3, ɵɵpropertyInterpolate4, ɵɵpropertyInterpolate5, ɵɵpropertyInterpolate6, ɵɵpropertyInterpolate7, ɵɵpropertyInterpolate8, ɵɵpropertyInterpolateV, ɵɵcontentQuery, ɵɵcontentQuerySignal, ɵɵloadQuery, ɵɵqueryRefresh, ɵɵqueryAdvance, ɵɵviewQuery, ɵɵviewQuerySignal, ɵɵreference, ɵɵrepeater, ɵɵrepeaterCreate, ɵɵrepeaterTrackByIdentity, ɵɵrepeaterTrackByIndex, ɵɵstyleMap, ɵɵstyleMapInterpolate1, ɵɵstyleMapInterpolate2, ɵɵstyleMapInterpolate3, ɵɵstyleMapInterpolate4, ɵɵstyleMapInterpolate5, ɵɵstyleMapInterpolate6, ɵɵstyleMapInterpolate7, ɵɵstyleMapInterpolate8, ɵɵstyleMapInterpolateV, ɵɵstyleProp, ɵɵstylePropInterpolate1, ɵɵstylePropInterpolate2, ɵɵstylePropInterpolate3, ɵɵstylePropInterpolate4, ɵɵstylePropInterpolate5, ɵɵstylePropInterpolate6, ɵɵstylePropInterpolate7, ɵɵstylePropInterpolate8, ɵɵstylePropInterpolateV, ɵɵsyntheticHostListener, ɵɵsyntheticHostProperty, ɵɵtemplate, ɵɵconditional, ɵɵdefer, ɵɵdeferWhen, ɵɵdeferOnIdle, ɵɵdeferOnImmediate, ɵɵdeferOnTimer, ɵɵdeferOnHover, ɵɵdeferOnInteraction, ɵɵdeferOnViewport, ɵɵdeferPrefetchWhen, ɵɵdeferPrefetchOnIdle, ɵɵdeferPrefetchOnImmediate, ɵɵdeferPrefetchOnTimer, ɵɵdeferPrefetchOnHover, ɵɵdeferPrefetchOnInteraction, ɵɵdeferPrefetchOnViewport, ɵɵdeferHydrateWhen, ɵɵdeferHydrateNever, ɵɵdeferHydrateOnIdle, ɵɵdeferHydrateOnImmediate, ɵɵdeferHydrateOnTimer, ɵɵdeferHydrateOnHover, ɵɵdeferHydrateOnInteraction, ɵɵdeferHydrateOnViewport, ɵɵdeferEnableTimerScheduling, ɵɵtext, ɵɵtextInterpolate, ɵɵtextInterpolate1, ɵɵtextInterpolate2, ɵɵtextInterpolate3, ɵɵtextInterpolate4, ɵɵtextInterpolate5, ɵɵtextInterpolate6, ɵɵtextInterpolate7, ɵɵtextInterpolate8, ɵɵtextInterpolateV, ɵɵtwoWayProperty, ɵɵtwoWayBindingSet, ɵɵtwoWayListener, ɵgetUnknownElementStrictMode, ɵsetUnknownElementStrictMode, ɵgetUnknownPropertyStrictMode, ɵsetUnknownPropertyStrictMode, ɵɵdeclareLet, ɵɵstoreLet, ɵɵreadContextLet, } from './instructions/all'; export { DEFER_BLOCK_DEPENDENCY_INTERCEPTOR as ɵDEFER_BLOCK_DEPENDENCY_INTERCEPTOR, DEFER_BLOCK_CONFIG as ɵDEFER_BLOCK_CONFIG, } from '../defer/instructions'; export {DeferBlockDependencyInterceptor as ɵDeferBlockDependencyInterceptor} from '../defer/interfaces'; export { ɵɵi18n, ɵɵi18nApply, ɵɵi18nAttributes, ɵɵi18nEnd, ɵɵi18nExp, ɵɵi18nPostprocess, ɵɵi18nStart, } from './instructions/i18n'; export {RenderFlags} from './interfaces/definition'; export {AttributeMarker} from './interfaces/attribute_marker'; export {CssSelectorList, ProjectionSlots} from './interfaces/projection'; export {setClassMetadata, setClassMetadataAsync} from './metadata'; export {NgModuleFactory, NgModuleRef, createEnvironmentInjector} from './ng_module_ref'; export {ɵɵpipe, ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV} from './pipe'; export { ɵɵpureFunction0, ɵɵpureFunction1, ɵɵpureFunction2, ɵɵpureFunction3, ɵɵpureFunction4, ɵɵpureFunction5, ɵɵpureFunction6, ɵɵpureFunction7, ɵɵpureFunction8, ɵɵpureFunctionV, } from './pure_function'; export {ɵɵdisableBindings, ɵɵenableBindings, ɵɵresetView, ɵɵrestoreView} from './state'; export {NO_CHANG
{ "end_byte": 6007, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/index.ts" }
angular/packages/core/src/render3/index.ts_6008_7498
} from './tokens'; export {ɵɵresolveBody, ɵɵresolveDocument, ɵɵresolveWindow} from './util/misc_utils'; export {ɵɵtemplateRefExtractor} from './view_engine_compatibility_prebound'; export {ɵɵgetComponentDepsFactory} from './local_compilation'; export {ɵsetClassDebugInfo} from './debug/set_debug_info'; export {ɵɵreplaceMetadata} from './hmr'; export { ComponentDebugMetadata, ComponentDef, ComponentTemplate, ComponentType, DirectiveDebugMetadata, DirectiveDef, DirectiveType, getComponent, getDirectiveMetadata, getDirectives, getHostElement, getRenderedText, LifecycleHooksFeature, PipeDef, ɵɵComponentDeclaration, ɵɵCopyDefinitionFeature, ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineNgModule, ɵɵdefinePipe, ɵɵDirectiveDeclaration, ɵɵFactoryDeclaration, ɵɵHostDirectivesFeature, ɵɵInheritDefinitionFeature, ɵɵInjectorDeclaration, ɵɵInputTransformsFeature, ɵɵNgModuleDeclaration, ɵɵNgOnChangesFeature, ɵɵPipeDeclaration, ɵɵProvidersFeature, ɵɵsetComponentScope, ɵɵsetNgModuleScope, ɵɵExternalStylesFeature, };
{ "end_byte": 7498, "start_byte": 6008, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/index.ts" }
angular/packages/core/src/render3/fields.ts_0_1592
/** * @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 {getClosureSafeProperty} from '../util/property'; export const NG_COMP_DEF = getClosureSafeProperty({ɵcmp: getClosureSafeProperty}); export const NG_DIR_DEF = getClosureSafeProperty({ɵdir: getClosureSafeProperty}); export const NG_PIPE_DEF = getClosureSafeProperty({ɵpipe: getClosureSafeProperty}); export const NG_MOD_DEF = getClosureSafeProperty({ɵmod: getClosureSafeProperty}); export const NG_FACTORY_DEF = getClosureSafeProperty({ɵfac: getClosureSafeProperty}); /** * If a directive is diPublic, bloomAdd sets a property on the type with this constant as * the key and the directive's unique ID as the value. This allows us to map directives to their * bloom filter bit for DI. */ // TODO(misko): This is wrong. The NG_ELEMENT_ID should never be minified. export const NG_ELEMENT_ID = getClosureSafeProperty({__NG_ELEMENT_ID__: getClosureSafeProperty}); /** * The `NG_ENV_ID` field on a DI token indicates special processing in the `EnvironmentInjector`: * getting such tokens from the `EnvironmentInjector` will bypass the standard DI resolution * strategy and instead will return implementation produced by the `NG_ENV_ID` factory function. * * This particular retrieval of DI tokens is mostly done to eliminate circular dependencies and * improve tree-shaking. */ export const NG_ENV_ID = getClosureSafeProperty({__NG_ENV_ID__: getClosureSafeProperty});
{ "end_byte": 1592, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/fields.ts" }
angular/packages/core/src/render3/query.ts_0_5642
/** * @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 */ // We are temporarily importing the existing viewEngine_from core so we can be sure we are // correctly implementing its interfaces for backwards compatibility. import {ProviderToken} from '../di/provider_token'; import {createElementRef, ElementRef as ViewEngine_ElementRef} from '../linker/element_ref'; import {QueryList} from '../linker/query_list'; import {createTemplateRef, TemplateRef as ViewEngine_TemplateRef} from '../linker/template_ref'; import {createContainerRef, ViewContainerRef} from '../linker/view_container_ref'; import {assertDefined, assertIndexInRange, assertNumber, throwError} from '../util/assert'; import {stringify} from '../util/stringify'; import {assertFirstCreatePass, assertLContainer} from './assert'; import {getNodeInjectable, locateDirectiveOrProvider} from './di'; import {storeCleanupWithContext} from './instructions/shared'; import {CONTAINER_HEADER_OFFSET, LContainer, MOVED_VIEWS} from './interfaces/container'; import { TContainerNode, TElementContainerNode, TElementNode, TNode, TNodeType, } from './interfaces/node'; import {LQueries, LQuery, QueryFlags, TQueries, TQuery, TQueryMetadata} from './interfaces/query'; import {DECLARATION_LCONTAINER, LView, PARENT, QUERIES, TVIEW, TView} from './interfaces/view'; import {assertTNodeType} from './node_assert'; import {getCurrentTNode, getLView, getTView} from './state'; class LQuery_<T> implements LQuery<T> { matches: (T | null)[] | null = null; constructor(public queryList: QueryList<T>) {} clone(): LQuery<T> { return new LQuery_(this.queryList); } setDirty(): void { this.queryList.setDirty(); } } class LQueries_ implements LQueries { constructor(public queries: LQuery<any>[] = []) {} createEmbeddedView(tView: TView): LQueries | null { const tQueries = tView.queries; if (tQueries !== null) { const noOfInheritedQueries = tView.contentQueries !== null ? tView.contentQueries[0] : tQueries.length; const viewLQueries: LQuery<any>[] = []; // An embedded view has queries propagated from a declaration view at the beginning of the // TQueries collection and up until a first content query declared in the embedded view. Only // propagated LQueries are created at this point (LQuery corresponding to declared content // queries will be instantiated from the content query instructions for each directive). for (let i = 0; i < noOfInheritedQueries; i++) { const tQuery = tQueries.getByIndex(i); const parentLQuery = this.queries[tQuery.indexInDeclarationView]; viewLQueries.push(parentLQuery.clone()); } return new LQueries_(viewLQueries); } return null; } insertView(tView: TView): void { this.dirtyQueriesWithMatches(tView); } detachView(tView: TView): void { this.dirtyQueriesWithMatches(tView); } finishViewCreation(tView: TView): void { this.dirtyQueriesWithMatches(tView); } private dirtyQueriesWithMatches(tView: TView) { for (let i = 0; i < this.queries.length; i++) { if (getTQuery(tView, i).matches !== null) { this.queries[i].setDirty(); } } } } export class TQueryMetadata_ implements TQueryMetadata { public predicate: ProviderToken<unknown> | string[]; constructor( predicate: ProviderToken<unknown> | string[] | string, public flags: QueryFlags, public read: any = null, ) { // Compiler might not be able to pre-optimize and split multiple selectors. if (typeof predicate === 'string') { this.predicate = splitQueryMultiSelectors(predicate); } else { this.predicate = predicate; } } } class TQueries_ implements TQueries { constructor(private queries: TQuery[] = []) {} elementStart(tView: TView, tNode: TNode): void { ngDevMode && assertFirstCreatePass( tView, 'Queries should collect results on the first template pass only', ); for (let i = 0; i < this.queries.length; i++) { this.queries[i].elementStart(tView, tNode); } } elementEnd(tNode: TNode): void { for (let i = 0; i < this.queries.length; i++) { this.queries[i].elementEnd(tNode); } } embeddedTView(tNode: TNode): TQueries | null { let queriesForTemplateRef: TQuery[] | null = null; for (let i = 0; i < this.length; i++) { const childQueryIndex = queriesForTemplateRef !== null ? queriesForTemplateRef.length : 0; const tqueryClone = this.getByIndex(i).embeddedTView(tNode, childQueryIndex); if (tqueryClone) { tqueryClone.indexInDeclarationView = i; if (queriesForTemplateRef !== null) { queriesForTemplateRef.push(tqueryClone); } else { queriesForTemplateRef = [tqueryClone]; } } } return queriesForTemplateRef !== null ? new TQueries_(queriesForTemplateRef) : null; } template(tView: TView, tNode: TNode): void { ngDevMode && assertFirstCreatePass( tView, 'Queries should collect results on the first template pass only', ); for (let i = 0; i < this.queries.length; i++) { this.queries[i].template(tView, tNode); } } getByIndex(index: number): TQuery { ngDevMode && assertIndexInRange(this.queries, index); return this.queries[index]; } get length(): number { return this.queries.length; } track(tquery: TQuery): void { this.queries.push(tquery); } }
{ "end_byte": 5642, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/query.ts" }
angular/packages/core/src/render3/query.ts_5644_13042
class TQuery_ implements TQuery { matches: number[] | null = null; indexInDeclarationView = -1; crossesNgTemplate = false; /** * A node index on which a query was declared (-1 for view queries and ones inherited from the * declaration template). We use this index (alongside with _appliesToNextNode flag) to know * when to apply content queries to elements in a template. */ private _declarationNodeIndex: number; /** * A flag indicating if a given query still applies to nodes it is crossing. We use this flag * (alongside with _declarationNodeIndex) to know when to stop applying content queries to * elements in a template. */ private _appliesToNextNode = true; constructor( public metadata: TQueryMetadata, nodeIndex: number = -1, ) { this._declarationNodeIndex = nodeIndex; } elementStart(tView: TView, tNode: TNode): void { if (this.isApplyingToNode(tNode)) { this.matchTNode(tView, tNode); } } elementEnd(tNode: TNode): void { if (this._declarationNodeIndex === tNode.index) { this._appliesToNextNode = false; } } template(tView: TView, tNode: TNode): void { this.elementStart(tView, tNode); } embeddedTView(tNode: TNode, childQueryIndex: number): TQuery | null { if (this.isApplyingToNode(tNode)) { this.crossesNgTemplate = true; // A marker indicating a `<ng-template>` element (a placeholder for query results from // embedded views created based on this `<ng-template>`). this.addMatch(-tNode.index, childQueryIndex); return new TQuery_(this.metadata); } return null; } private isApplyingToNode(tNode: TNode): boolean { if ( this._appliesToNextNode && (this.metadata.flags & QueryFlags.descendants) !== QueryFlags.descendants ) { const declarationNodeIdx = this._declarationNodeIndex; let parent = tNode.parent; // Determine if a given TNode is a "direct" child of a node on which a content query was // declared (only direct children of query's host node can match with the descendants: false // option). There are 3 main use-case / conditions to consider here: // - <needs-target><i #target></i></needs-target>: here <i #target> parent node is a query // host node; // - <needs-target><ng-template [ngIf]="true"><i #target></i></ng-template></needs-target>: // here <i #target> parent node is null; // - <needs-target><ng-container><i #target></i></ng-container></needs-target>: here we need // to go past `<ng-container>` to determine <i #target> parent node (but we shouldn't traverse // up past the query's host node!). while ( parent !== null && parent.type & TNodeType.ElementContainer && parent.index !== declarationNodeIdx ) { parent = parent.parent; } return declarationNodeIdx === (parent !== null ? parent.index : -1); } return this._appliesToNextNode; } private matchTNode(tView: TView, tNode: TNode): void { const predicate = this.metadata.predicate; if (Array.isArray(predicate)) { for (let i = 0; i < predicate.length; i++) { const name = predicate[i]; this.matchTNodeWithReadOption(tView, tNode, getIdxOfMatchingSelector(tNode, name)); // Also try matching the name to a provider since strings can be used as DI tokens too. this.matchTNodeWithReadOption( tView, tNode, locateDirectiveOrProvider(tNode, tView, name, false, false), ); } } else { if ((predicate as any) === ViewEngine_TemplateRef) { if (tNode.type & TNodeType.Container) { this.matchTNodeWithReadOption(tView, tNode, -1); } } else { this.matchTNodeWithReadOption( tView, tNode, locateDirectiveOrProvider(tNode, tView, predicate, false, false), ); } } } private matchTNodeWithReadOption(tView: TView, tNode: TNode, nodeMatchIdx: number | null): void { if (nodeMatchIdx !== null) { const read = this.metadata.read; if (read !== null) { if ( read === ViewEngine_ElementRef || read === ViewContainerRef || (read === ViewEngine_TemplateRef && tNode.type & TNodeType.Container) ) { this.addMatch(tNode.index, -2); } else { const directiveOrProviderIdx = locateDirectiveOrProvider( tNode, tView, read, false, false, ); if (directiveOrProviderIdx !== null) { this.addMatch(tNode.index, directiveOrProviderIdx); } } } else { this.addMatch(tNode.index, nodeMatchIdx); } } } private addMatch(tNodeIdx: number, matchIdx: number) { if (this.matches === null) { this.matches = [tNodeIdx, matchIdx]; } else { this.matches.push(tNodeIdx, matchIdx); } } } /** * Iterates over local names for a given node and returns directive index * (or -1 if a local name points to an element). * * @param tNode static data of a node to check * @param selector selector to match * @returns directive index, -1 or null if a selector didn't match any of the local names */ function getIdxOfMatchingSelector(tNode: TNode, selector: string): number | null { const localNames = tNode.localNames; if (localNames !== null) { for (let i = 0; i < localNames.length; i += 2) { if (localNames[i] === selector) { return localNames[i + 1] as number; } } } return null; } function createResultByTNodeType(tNode: TNode, currentView: LView): any { if (tNode.type & (TNodeType.AnyRNode | TNodeType.ElementContainer)) { return createElementRef(tNode, currentView); } else if (tNode.type & TNodeType.Container) { return createTemplateRef(tNode, currentView); } return null; } function createResultForNode(lView: LView, tNode: TNode, matchingIdx: number, read: any): any { if (matchingIdx === -1) { // if read token and / or strategy is not specified, detect it using appropriate tNode type return createResultByTNodeType(tNode, lView); } else if (matchingIdx === -2) { // read a special token from a node injector return createSpecialToken(lView, tNode, read); } else { // read a token return getNodeInjectable(lView, lView[TVIEW], matchingIdx, tNode as TElementNode); } } function createSpecialToken(lView: LView, tNode: TNode, read: any): any { if (read === ViewEngine_ElementRef) { return createElementRef(tNode, lView); } else if (read === ViewEngine_TemplateRef) { return createTemplateRef(tNode, lView); } else if (read === ViewContainerRef) { ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode | TNodeType.AnyContainer); return createContainerRef( tNode as TElementNode | TContainerNode | TElementContainerNode, lView, ); } else { ngDevMode && throwError( `Special token to read should be one of ElementRef, TemplateRef or ViewContainerRef but got ${stringify( read, )}.`, ); } } /** * A helper function that creates query results for a given view. This function is meant to do the * processing once and only once for a given view instance (a set of results for a given view * doesn't change). */
{ "end_byte": 13042, "start_byte": 5644, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/query.ts" }
angular/packages/core/src/render3/query.ts_13043_19368
function materializeViewResults<T>( tView: TView, lView: LView, tQuery: TQuery, queryIndex: number, ): T[] { const lQuery = lView[QUERIES]!.queries![queryIndex]; if (lQuery.matches === null) { const tViewData = tView.data; const tQueryMatches = tQuery.matches; const result: Array<T | null> = []; for (let i = 0; tQueryMatches !== null && i < tQueryMatches.length; i += 2) { const matchedNodeIdx = tQueryMatches[i]; if (matchedNodeIdx < 0) { // we at the <ng-template> marker which might have results in views created based on this // <ng-template> - those results will be in separate views though, so here we just leave // null as a placeholder result.push(null); } else { ngDevMode && assertIndexInRange(tViewData, matchedNodeIdx); const tNode = tViewData[matchedNodeIdx] as TNode; result.push(createResultForNode(lView, tNode, tQueryMatches[i + 1], tQuery.metadata.read)); } } lQuery.matches = result; } return lQuery.matches; } /** * A helper function that collects (already materialized) query results from a tree of views, * starting with a provided LView. */ function collectQueryResults<T>(tView: TView, lView: LView, queryIndex: number, result: T[]): T[] { const tQuery = tView.queries!.getByIndex(queryIndex); const tQueryMatches = tQuery.matches; if (tQueryMatches !== null) { const lViewResults = materializeViewResults<T>(tView, lView, tQuery, queryIndex); for (let i = 0; i < tQueryMatches.length; i += 2) { const tNodeIdx = tQueryMatches[i]; if (tNodeIdx > 0) { result.push(lViewResults[i / 2] as T); } else { const childQueryIndex = tQueryMatches[i + 1]; const declarationLContainer = lView[-tNodeIdx] as LContainer; ngDevMode && assertLContainer(declarationLContainer); // collect matches for views inserted in this container for (let i = CONTAINER_HEADER_OFFSET; i < declarationLContainer.length; i++) { const embeddedLView = declarationLContainer[i]; if (embeddedLView[DECLARATION_LCONTAINER] === embeddedLView[PARENT]) { collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result); } } // collect matches for views created from this declaration container and inserted into // different containers if (declarationLContainer[MOVED_VIEWS] !== null) { const embeddedLViews = declarationLContainer[MOVED_VIEWS]!; for (let i = 0; i < embeddedLViews.length; i++) { const embeddedLView = embeddedLViews[i]; collectQueryResults(embeddedLView[TVIEW], embeddedLView, childQueryIndex, result); } } } } } return result; } export function loadQueryInternal<T>(lView: LView, queryIndex: number): QueryList<T> { ngDevMode && assertDefined(lView[QUERIES], 'LQueries should be defined when trying to load a query'); ngDevMode && assertIndexInRange(lView[QUERIES]!.queries, queryIndex); return lView[QUERIES]!.queries[queryIndex].queryList; } /** * Creates a new instance of LQuery and returns its index in the collection of LQuery objects. * * @returns index in the collection of LQuery objects */ function createLQuery<T>(tView: TView, lView: LView, flags: QueryFlags): number { const queryList = new QueryList<T>( (flags & QueryFlags.emitDistinctChangesOnly) === QueryFlags.emitDistinctChangesOnly, ); storeCleanupWithContext(tView, lView, queryList, queryList.destroy); const lQueries = (lView[QUERIES] ??= new LQueries_()).queries; return lQueries.push(new LQuery_(queryList)) - 1; } export function createViewQuery<T>( predicate: ProviderToken<unknown> | string[] | string, flags: QueryFlags, read?: any, ): number { ngDevMode && assertNumber(flags, 'Expecting flags'); const tView = getTView(); if (tView.firstCreatePass) { createTQuery(tView, new TQueryMetadata_(predicate, flags, read), -1); if ((flags & QueryFlags.isStatic) === QueryFlags.isStatic) { tView.staticViewQueries = true; } } return createLQuery<T>(tView, getLView(), flags); } export function createContentQuery<T>( directiveIndex: number, predicate: ProviderToken<unknown> | string[] | string, flags: QueryFlags, read?: ProviderToken<T>, ): number { ngDevMode && assertNumber(flags, 'Expecting flags'); const tView = getTView(); if (tView.firstCreatePass) { const tNode = getCurrentTNode()!; createTQuery(tView, new TQueryMetadata_(predicate, flags, read), tNode.index); saveContentQueryAndDirectiveIndex(tView, directiveIndex); if ((flags & QueryFlags.isStatic) === QueryFlags.isStatic) { tView.staticContentQueries = true; } } return createLQuery<T>(tView, getLView(), flags); } /** Splits multiple selectors in the locator. */ function splitQueryMultiSelectors(locator: string): string[] { return locator.split(',').map((s) => s.trim()); } export function createTQuery(tView: TView, metadata: TQueryMetadata, nodeIndex: number): void { if (tView.queries === null) tView.queries = new TQueries_(); tView.queries.track(new TQuery_(metadata, nodeIndex)); } export function saveContentQueryAndDirectiveIndex(tView: TView, directiveIndex: number) { const tViewContentQueries = tView.contentQueries || (tView.contentQueries = []); const lastSavedDirectiveIndex = tViewContentQueries.length ? tViewContentQueries[tViewContentQueries.length - 1] : -1; if (directiveIndex !== lastSavedDirectiveIndex) { tViewContentQueries.push(tView.queries!.length - 1, directiveIndex); } } export function getTQuery(tView: TView, index: number): TQuery { ngDevMode && assertDefined(tView.queries, 'TQueries must be defined to retrieve a TQuery'); return tView.queries!.getByIndex(index); } /** * A helper function collecting results from all the views where a given query was active. * @param lView * @param queryIndex */ export function getQueryResults<V>(lView: LView, queryIndex: number): V[] { const tView = lView[TVIEW]; const tQuery = getTQuery(tView, queryIndex); return tQuery.crossesNgTemplate ? collectQueryResults<V>(tView, lView, queryIndex, []) : materializeViewResults<V>(tView, lView, tQuery, queryIndex); }
{ "end_byte": 19368, "start_byte": 13043, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/query.ts" }
angular/packages/core/src/render3/metadata.ts_0_4135
/** * @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 '../util/closure'; interface TypeWithMetadata extends Type<any> { decorators?: any[]; ctorParameters?: () => any[]; propDecorators?: {[field: string]: any}; } /** * The name of a field that Angular monkey-patches onto a component * class to store a function that loads defer-loadable dependencies * and applies metadata to a class. */ const ASYNC_COMPONENT_METADATA_FN = '__ngAsyncComponentMetadataFn__'; /** * If a given component has unresolved async metadata - returns a reference * to a function that applies component metadata after resolving defer-loadable * dependencies. Otherwise - this function returns `null`. */ export function getAsyncClassMetadataFn( type: Type<unknown>, ): (() => Promise<Array<Type<unknown>>>) | null { const componentClass = type as any; // cast to `any`, so that we can read a monkey-patched field return componentClass[ASYNC_COMPONENT_METADATA_FN] ?? null; } /** * Handles the process of applying metadata info to a component class in case * component template has defer blocks (thus some dependencies became deferrable). * * @param type Component class where metadata should be added * @param dependencyLoaderFn Function that loads dependencies * @param metadataSetterFn Function that forms a scope in which the `setClassMetadata` is invoked */ export function setClassMetadataAsync( type: Type<any>, dependencyLoaderFn: () => Array<Promise<Type<unknown>>>, metadataSetterFn: (...types: Type<unknown>[]) => void, ): () => Promise<Array<Type<unknown>>> { const componentClass = type as any; // cast to `any`, so that we can monkey-patch it componentClass[ASYNC_COMPONENT_METADATA_FN] = () => Promise.all(dependencyLoaderFn()).then((dependencies) => { metadataSetterFn(...dependencies); // Metadata is now set, reset field value to indicate that this component // can by used/compiled synchronously. componentClass[ASYNC_COMPONENT_METADATA_FN] = null; return dependencies; }); return componentClass[ASYNC_COMPONENT_METADATA_FN]; } /** * Adds decorator, constructor, and property metadata to a given type via static metadata fields * on the type. * * These metadata fields can later be read with Angular's `ReflectionCapabilities` API. * * Calls to `setClassMetadata` can be guarded by ngDevMode, resulting in the metadata assignments * being tree-shaken away during production builds. */ export function setClassMetadata( type: Type<any>, decorators: any[] | null, ctorParameters: (() => any[]) | null, propDecorators: {[field: string]: any} | null, ): void { return noSideEffects(() => { const clazz = type as TypeWithMetadata; if (decorators !== null) { if (clazz.hasOwnProperty('decorators') && clazz.decorators !== undefined) { clazz.decorators.push(...decorators); } else { clazz.decorators = decorators; } } if (ctorParameters !== null) { // Rather than merging, clobber the existing parameters. If other projects exist which // use tsickle-style annotations and reflect over them in the same way, this could // cause issues, but that is vanishingly unlikely. clazz.ctorParameters = ctorParameters; } if (propDecorators !== null) { // The property decorator objects are merged as it is possible different fields have // different decorator types. Decorators on individual fields are not merged, as it's // also incredibly unlikely that a field will be decorated both with an Angular // decorator and a non-Angular decorator that's also been downleveled. if (clazz.hasOwnProperty('propDecorators') && clazz.propDecorators !== undefined) { clazz.propDecorators = {...clazz.propDecorators, ...propDecorators}; } else { clazz.propDecorators = propDecorators; } } }) as never; }
{ "end_byte": 4135, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/metadata.ts" }
angular/packages/core/src/render3/reactive_lview_consumer.ts_0_4585
/** * @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 {REACTIVE_NODE, ReactiveNode} from '@angular/core/primitives/signals'; import { LView, PARENT, REACTIVE_TEMPLATE_CONSUMER, TVIEW, TView, TViewType, } from './interfaces/view'; import {getLViewParent, markAncestorsForTraversal, markViewForRefresh} from './util/view_utils'; import {assertDefined} from '../util/assert'; let freeConsumers: ReactiveNode[] = []; export interface ReactiveLViewConsumer extends ReactiveNode { lView: LView | null; } /** * Create a new template consumer pointing at the specified LView. * Sometimes, a previously created consumer may be reused, in order to save on allocations. In that * case, the LView will be updated. */ export function getOrBorrowReactiveLViewConsumer(lView: LView): ReactiveLViewConsumer { return lView[REACTIVE_TEMPLATE_CONSUMER] ?? borrowReactiveLViewConsumer(lView); } function borrowReactiveLViewConsumer(lView: LView): ReactiveLViewConsumer { const consumer = freeConsumers.pop() ?? Object.create(REACTIVE_LVIEW_CONSUMER_NODE); consumer.lView = lView; return consumer; } export function maybeReturnReactiveLViewConsumer(consumer: ReactiveLViewConsumer): void { if (consumer.lView![REACTIVE_TEMPLATE_CONSUMER] === consumer) { // The consumer got committed. return; } consumer.lView = null; freeConsumers.push(consumer); } const REACTIVE_LVIEW_CONSUMER_NODE: Omit<ReactiveLViewConsumer, 'lView'> = { ...REACTIVE_NODE, consumerIsAlwaysLive: true, consumerMarkedDirty: (node: ReactiveLViewConsumer) => { markAncestorsForTraversal(node.lView!); }, consumerOnSignalRead(this: ReactiveLViewConsumer): void { this.lView![REACTIVE_TEMPLATE_CONSUMER] = this; }, }; /** * Creates a temporary consumer for use with `LView`s that should not have consumers. * If the LView already has a consumer, returns the existing one instead. * * This is necessary because some APIs may cause change detection directly on an LView * that we do not want to have a consumer (Embedded views today). As a result, there * would be no active consumer from running change detection on its host component * and any signals in the LView template would be untracked. Instead, we create * this temporary consumer that marks the first parent that _should_ have a consumer * for refresh. Once change detection runs as part of that refresh, we throw away * this consumer because its signals will then be tracked by the parent's consumer. */ export function getOrCreateTemporaryConsumer(lView: LView): ReactiveLViewConsumer { const consumer = lView[REACTIVE_TEMPLATE_CONSUMER] ?? Object.create(TEMPORARY_CONSUMER_NODE); consumer.lView = lView; return consumer; } const TEMPORARY_CONSUMER_NODE = { ...REACTIVE_NODE, consumerIsAlwaysLive: true, consumerMarkedDirty: (node: ReactiveLViewConsumer) => { let parent = getLViewParent(node.lView!); while (parent && !viewShouldHaveReactiveConsumer(parent[TVIEW])) { parent = getLViewParent(parent); } if (!parent) { // If we can't find an appropriate parent that should have a consumer, we // don't have a way of appropriately refreshing this LView as part of application synchronization. return; } markViewForRefresh(parent); }, consumerOnSignalRead(this: ReactiveLViewConsumer): void { this.lView![REACTIVE_TEMPLATE_CONSUMER] = this; }, }; /** * Indicates if the view should get its own reactive consumer node. * * In the current design, all embedded views share a consumer with the component view. This allows * us to refresh at the component level rather than at a per-view level. In addition, root views get * their own reactive node because root component will have a host view that executes the * component's host bindings. This needs to be tracked in a consumer as well. * * To get a more granular change detection than per-component, all we would just need to update the * condition here so that a given view gets a reactive consumer which can become dirty independently * from its parent component. For example embedded views for signal components could be created with * a new type "SignalEmbeddedView" and the condition here wouldn't even need updating in order to * get granular per-view change detection for signal components. */ export function viewShouldHaveReactiveConsumer(tView: TView) { return tView.type !== TViewType.Embedded; }
{ "end_byte": 4585, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactive_lview_consumer.ts" }
angular/packages/core/src/render3/PERF_NOTES.md_0_5682
## General Notes Each Array costs 70 bytes and is composed of `Array` and `(array)` object * `Array` javascript visible object: 32 bytes * `(array)` VM object where the array is actually stored in: 38 bytes Each Object cost is 24 bytes plus 8 bytes per property. For small arrays, it is more efficient to store the data as a linked list of items rather than small arrays. However, the array access is faster as shown here: https://jsperf.com/small-arrays-vs-linked-objects ## Monomorphic vs Megamorphic code Great reads: - [What's up with monomorphism?](https://mrale.ph/blog/2015/01/11/whats-up-with-monomorphism.html) - [Impact of polymorphism on component-based frameworks like React](https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/) 1) Monomorphic prop access is 100 times faster than megamorphic. 2) Monomorphic call is 4 times faster the megamorphic call. See benchmark [here](https://jsperf.com/mono-vs-megamorphic-property-access). ## Packed vs. holey Array V8 represents arrays internally in a different way depending on: - type of elements in the array; - presence of holes (indexes that were never assigned). Generally speaking packed arrays (a set of continuous, initialized indexes) perform better as compared to arrays with holes. To assure that arrays are packed follow those guidelines: * create array literals with known values whenever possible (ex. `a = [0];` is better than `a = []; a.push[0];`; * don't use `Array` constructor with the size value (ex. `new Array(5)`) - this will create a `HOLEY_ELEMENTS` array (even if this array is filled in later on!); * don't delete elements from an array (ex. `delete a[0]`) - this will create a hole; * don't write past the array length as this will create holes; Great reads: - [Elements kinds in V8](https://v8.dev/blog/elements-kinds) ## Exporting top level variables Exporting top level variables should be avoided where possible where performance and code size matters: ``` // Typescript export let exported = 0; let notExported = 0; notExported = exported; // Would be compiled to exports.exported = 0; var notExported = 0; notExported = exports.exported; ``` Most minifiers do not rename properties (closure is an exception here). What could be done instead is: ``` let exported = 0; export function getExported() { return exported; } export function setExported(v) { exported = v; } ``` Also writing to a property of `exports` might change its hidden class resulting in megamorphic access. ## Iterating over Keys of an Object. https://jsperf.com/object-keys-vs-for-in-with-closure/3 implies that `Object.keys` is the fastest way of iterating over properties of an object. ``` for (var i = 0, keys = Object.keys(obj); i < keys.length; i++) { const key = keys[i]; } ``` ## Recursive functions Avoid recursive functions when possible because they cannot be inlined. https://jsperf.com/cost-of-recursion ## Function Inlining VMs gain a lot of speed by inlining functions which are small (such as getters). This is because the cost of the value retrieval (getter) is often way less than the cost of making a function call. VMs use the heuristic of size to determine whether a function should be inline. Thinking is that large functions probably will not benefit inlining because the overhead of function call is not significant to the overall function execution. Our goal should be that all of the instructions which are in template function should be inlinable. Here is an example of code which breaks the inlining and a way to fix it. ``` export function i18nStart(index: number, message: string, subTemplateIndex?: number): void { const tView = getTView(); if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) { // LOTS OF CODE HERE WHICH PREVENTS INLINING. } } ``` Notice that the above function almost never runs because `tView.firstCreatePass` is usually false. The application would benefit from inlining, but the large code inside `if` prevents it. Simple refactoring will fix it. ``` export function i18nStart(index: number, message: string, subTemplateIndex?: number): void { const tView = getTView(); if (tView.firstCreatePass && tView.data[index + HEADER_OFFSET] === null) { i18nStartfirstCreatePass(tView, index, message, subTemplateIndex) } } export function i18nStartfirstCreatePass(tView: TView, index: number, message: string, subTemplateIndex?: number): void { // LOTS OF CODE HERE WHICH PREVENTS INLINING. } ``` ## Loops Don't use `forEach`, it can cause megamorphic function calls (depending on the browser) and function allocations. It is [a lot slower than regular `for` loops](https://jsperf.com/for-vs-foreach-misko) ## Limit global state access Ivy implementation uses some variables in `packages/core/src/render3/state.ts` that could be considered "global state" (those are not truly global variables exposed on `window` but still those variables are easily accessible from anywhere in the ivy codebase). Usage of this global state should be limited to avoid unnecessary function calls (state getters) and improve code readability. As a rule, the global state should be accessed _only_ from instructions (functions invoked from the generated code). ## Instructions should be only called from the generated code Instruction functions should be called only from the generated template code. As a consequence of this rule, instructions shouldn't call other instructions. Calling instructions from other instructions (or any part of the ivy codebase) multiplies global state access (see previous rule) and makes reasoning about code more difficult.
{ "end_byte": 5682, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/PERF_NOTES.md" }
angular/packages/core/src/render3/standalone_service.ts_0_2258
/** * @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 as inject} from '../di/injector_compatibility'; import {ɵɵdefineInjectable as defineInjectable} from '../di/interface/defs'; import {internalImportProvidersFrom} from '../di/provider_collection'; import {EnvironmentInjector} from '../di/r3_injector'; import {OnDestroy} from '../interface/lifecycle_hooks'; import {ComponentDef} from './interfaces/definition'; import {createEnvironmentInjector} from './ng_module_ref'; /** * A service used by the framework to create instances of standalone injectors. Those injectors are * created on demand in case of dynamic component instantiation and contain ambient providers * collected from the imports graph rooted at a given standalone component. */ export class StandaloneService implements OnDestroy { cachedInjectors = new Map<ComponentDef<unknown>, EnvironmentInjector | null>(); constructor(private _injector: EnvironmentInjector) {} getOrCreateStandaloneInjector(componentDef: ComponentDef<unknown>): EnvironmentInjector | null { if (!componentDef.standalone) { return null; } if (!this.cachedInjectors.has(componentDef)) { const providers = internalImportProvidersFrom(false, componentDef.type); const standaloneInjector = providers.length > 0 ? createEnvironmentInjector( [providers], this._injector, `Standalone[${componentDef.type.name}]`, ) : null; this.cachedInjectors.set(componentDef, standaloneInjector); } return this.cachedInjectors.get(componentDef)!; } ngOnDestroy() { try { for (const injector of this.cachedInjectors.values()) { if (injector !== null) { injector.destroy(); } } } finally { this.cachedInjectors.clear(); } } /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ defineInjectable({ token: StandaloneService, providedIn: 'environment', factory: () => new StandaloneService(inject(EnvironmentInjector)), }); }
{ "end_byte": 2258, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/standalone_service.ts" }
angular/packages/core/src/render3/hooks.ts_0_7792
/** * @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 { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, DoCheck, OnChanges, OnDestroy, OnInit, } from '../interface/lifecycle_hooks'; import {assertDefined, assertEqual, assertNotEqual} from '../util/assert'; import {assertFirstCreatePass} from './assert'; import {NgOnChangesFeatureImpl} from './features/ng_onchanges_feature'; import {DirectiveDef} from './interfaces/definition'; import {TNode} from './interfaces/node'; import { FLAGS, HookData, InitPhaseState, LView, LViewFlags, PREORDER_HOOK_FLAGS, PreOrderHookFlags, TView, } from './interfaces/view'; import {profiler} from './profiler'; import {ProfilerEvent} from './profiler_types'; import {isInCheckNoChangesMode} from './state'; /** * Adds all directive lifecycle hooks from the given `DirectiveDef` to the given `TView`. * * Must be run *only* on the first template pass. * * Sets up the pre-order hooks on the provided `tView`, * see {@link HookData} for details about the data structure. * * @param directiveIndex The index of the directive in LView * @param directiveDef The definition containing the hooks to setup in tView * @param tView The current TView */ export function registerPreOrderHooks( directiveIndex: number, directiveDef: DirectiveDef<any>, tView: TView, ): void { ngDevMode && assertFirstCreatePass(tView); const {ngOnChanges, ngOnInit, ngDoCheck} = directiveDef.type.prototype as OnChanges & OnInit & DoCheck; if (ngOnChanges as Function | undefined) { const wrappedOnChanges = NgOnChangesFeatureImpl(directiveDef); (tView.preOrderHooks ??= []).push(directiveIndex, wrappedOnChanges); (tView.preOrderCheckHooks ??= []).push(directiveIndex, wrappedOnChanges); } if (ngOnInit) { (tView.preOrderHooks ??= []).push(0 - directiveIndex, ngOnInit); } if (ngDoCheck) { (tView.preOrderHooks ??= []).push(directiveIndex, ngDoCheck); (tView.preOrderCheckHooks ??= []).push(directiveIndex, ngDoCheck); } } /** * * Loops through the directives on the provided `tNode` and queues hooks to be * run that are not initialization hooks. * * Should be executed during `elementEnd()` and similar to * preserve hook execution order. Content, view, and destroy hooks for projected * components and directives must be called *before* their hosts. * * Sets up the content, view, and destroy hooks on the provided `tView`, * see {@link HookData} for details about the data structure. * * NOTE: This does not set up `onChanges`, `onInit` or `doCheck`, those are set up * separately at `elementStart`. * * @param tView The current TView * @param tNode The TNode whose directives are to be searched for hooks to queue */ export function registerPostOrderHooks(tView: TView, tNode: TNode): void { ngDevMode && assertFirstCreatePass(tView); // It's necessary to loop through the directives at elementEnd() (rather than processing in // directiveCreate) so we can preserve the current hook order. Content, view, and destroy // hooks for projected components and directives must be called *before* their hosts. for (let i = tNode.directiveStart, end = tNode.directiveEnd; i < end; i++) { const directiveDef = tView.data[i] as DirectiveDef<any>; ngDevMode && assertDefined(directiveDef, 'Expecting DirectiveDef'); const lifecycleHooks: AfterContentInit & AfterContentChecked & AfterViewInit & AfterViewChecked & OnDestroy = directiveDef.type.prototype; const { ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy, } = lifecycleHooks; if (ngAfterContentInit) { (tView.contentHooks ??= []).push(-i, ngAfterContentInit); } if (ngAfterContentChecked) { (tView.contentHooks ??= []).push(i, ngAfterContentChecked); (tView.contentCheckHooks ??= []).push(i, ngAfterContentChecked); } if (ngAfterViewInit) { (tView.viewHooks ??= []).push(-i, ngAfterViewInit); } if (ngAfterViewChecked) { (tView.viewHooks ??= []).push(i, ngAfterViewChecked); (tView.viewCheckHooks ??= []).push(i, ngAfterViewChecked); } if (ngOnDestroy != null) { (tView.destroyHooks ??= []).push(i, ngOnDestroy); } } } /** * Executing hooks requires complex logic as we need to deal with 2 constraints. * * 1. Init hooks (ngOnInit, ngAfterContentInit, ngAfterViewInit) must all be executed once and only * once, across many change detection cycles. This must be true even if some hooks throw, or if * some recursively trigger a change detection cycle. * To solve that, it is required to track the state of the execution of these init hooks. * This is done by storing and maintaining flags in the view: the {@link InitPhaseState}, * and the index within that phase. They can be seen as a cursor in the following structure: * [[onInit1, onInit2], [afterContentInit1], [afterViewInit1, afterViewInit2, afterViewInit3]] * They are stored as flags in LView[FLAGS]. * * 2. Pre-order hooks can be executed in batches, because of the select instruction. * To be able to pause and resume their execution, we also need some state about the hook's array * that is being processed: * - the index of the next hook to be executed * - the number of init hooks already found in the processed part of the array * They are stored as flags in LView[PREORDER_HOOK_FLAGS]. */ /** * Executes pre-order check hooks ( OnChanges, DoChanges) given a view where all the init hooks were * executed once. This is a light version of executeInitAndCheckPreOrderHooks where we can skip read * / write of the init-hooks related flags. * @param lView The LView where hooks are defined * @param hooks Hooks to be run * @param nodeIndex 3 cases depending on the value: * - undefined: all hooks from the array should be executed (post-order case) * - null: execute hooks only from the saved index until the end of the array (pre-order case, when * flushing the remaining hooks) * - number: execute hooks only from the saved index until that node index exclusive (pre-order * case, when executing select(number)) */ export function executeCheckHooks(lView: LView, hooks: HookData, nodeIndex?: number | null) { callHooks(lView, hooks, InitPhaseState.InitPhaseCompleted, nodeIndex); } /** * Executes post-order init and check hooks (one of AfterContentInit, AfterContentChecked, * AfterViewInit, AfterViewChecked) given a view where there are pending init hooks to be executed. * @param lView The LView where hooks are defined * @param hooks Hooks to be run * @param initPhase A phase for which hooks should be run * @param nodeIndex 3 cases depending on the value: * - undefined: all hooks from the array should be executed (post-order case) * - null: execute hooks only from the saved index until the end of the array (pre-order case, when * flushing the remaining hooks) * - number: execute hooks only from the saved index until that node index exclusive (pre-order * case, when executing select(number)) */ export function executeInitAndCheckHooks( lView: LView, hooks: HookData, initPhase: InitPhaseState, nodeIndex?: number | null, ) { ngDevMode && assertNotEqual( initPhase, InitPhaseState.InitPhaseCompleted, 'Init pre-order hooks should not be called more than once', ); if ((lView[FLAGS] & LViewFlags.InitPhaseStateMask) === initPhase) { callHooks(lView, hooks, initPhase, nodeIndex); } }
{ "end_byte": 7792, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hooks.ts" }
angular/packages/core/src/render3/hooks.ts_7794_12064
export function incrementInitPhaseFlags(lView: LView, initPhase: InitPhaseState): void { ngDevMode && assertNotEqual( initPhase, InitPhaseState.InitPhaseCompleted, 'Init hooks phase should not be incremented after all init hooks have been run.', ); let flags = lView[FLAGS]; if ((flags & LViewFlags.InitPhaseStateMask) === initPhase) { flags &= LViewFlags.IndexWithinInitPhaseReset; flags += LViewFlags.InitPhaseStateIncrementer; lView[FLAGS] = flags; } } /** * Calls lifecycle hooks with their contexts, skipping init hooks if it's not * the first LView pass * * @param currentView The current view * @param arr The array in which the hooks are found * @param initPhaseState the current state of the init phase * @param currentNodeIndex 3 cases depending on the value: * - undefined: all hooks from the array should be executed (post-order case) * - null: execute hooks only from the saved index until the end of the array (pre-order case, when * flushing the remaining hooks) * - number: execute hooks only from the saved index until that node index exclusive (pre-order * case, when executing select(number)) */ function callHooks( currentView: LView, arr: HookData, initPhase: InitPhaseState, currentNodeIndex: number | null | undefined, ): void { ngDevMode && assertEqual( isInCheckNoChangesMode(), false, 'Hooks should never be run when in check no changes mode.', ); const startIndex = currentNodeIndex !== undefined ? currentView[PREORDER_HOOK_FLAGS] & PreOrderHookFlags.IndexOfTheNextPreOrderHookMaskMask : 0; const nodeIndexLimit = currentNodeIndex != null ? currentNodeIndex : -1; const max = arr.length - 1; // Stop the loop at length - 1, because we look for the hook at i + 1 let lastNodeIndexFound = 0; for (let i = startIndex; i < max; i++) { const hook = arr[i + 1] as number | (() => void); if (typeof hook === 'number') { lastNodeIndexFound = arr[i] as number; if (currentNodeIndex != null && lastNodeIndexFound >= currentNodeIndex) { break; } } else { const isInitHook = (arr[i] as number) < 0; if (isInitHook) { currentView[PREORDER_HOOK_FLAGS] += PreOrderHookFlags.NumberOfInitHooksCalledIncrementer; } if (lastNodeIndexFound < nodeIndexLimit || nodeIndexLimit == -1) { callHook(currentView, initPhase, arr, i); currentView[PREORDER_HOOK_FLAGS] = (currentView[PREORDER_HOOK_FLAGS] & PreOrderHookFlags.NumberOfInitHooksCalledMask) + i + 2; } i++; } } } /** * Executes a single lifecycle hook, making sure that: * - it is called in the non-reactive context; * - profiling data are registered. */ function callHookInternal(directive: any, hook: () => void) { profiler(ProfilerEvent.LifecycleHookStart, directive, hook); const prevConsumer = setActiveConsumer(null); try { hook.call(directive); } finally { setActiveConsumer(prevConsumer); profiler(ProfilerEvent.LifecycleHookEnd, directive, hook); } } /** * Execute one hook against the current `LView`. * * @param currentView The current view * @param initPhaseState the current state of the init phase * @param arr The array in which the hooks are found * @param i The current index within the hook data array */ function callHook(currentView: LView, initPhase: InitPhaseState, arr: HookData, i: number) { const isInitHook = (arr[i] as number) < 0; const hook = arr[i + 1] as () => void; const directiveIndex = isInitHook ? -arr[i] : (arr[i] as number); const directive = currentView[directiveIndex]; if (isInitHook) { const indexWithintInitPhase = currentView[FLAGS] >> LViewFlags.IndexWithinInitPhaseShift; // The init phase state must be always checked here as it may have been recursively updated. if ( indexWithintInitPhase < currentView[PREORDER_HOOK_FLAGS] >> PreOrderHookFlags.NumberOfInitHooksCalledShift && (currentView[FLAGS] & LViewFlags.InitPhaseStateMask) === initPhase ) { currentView[FLAGS] += LViewFlags.IndexWithinInitPhaseIncrementer; callHookInternal(directive, hook); } } else { callHookInternal(directive, hook); } }
{ "end_byte": 12064, "start_byte": 7794, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hooks.ts" }
angular/packages/core/src/render3/chained_injector.ts_0_1665
/** * @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 {convertToBitFlags} from '../di/injector_compatibility'; import {InjectFlags, InjectOptions} from '../di/interface/injector'; import {ProviderToken} from '../di/provider_token'; import {NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR} from '../view/provider_flags'; /** * Injector that looks up a value using a specific injector, before falling back to the module * injector. Used primarily when creating components or embedded views dynamically. */ export class ChainedInjector implements Injector { constructor( public injector: Injector, public parentInjector: Injector, ) {} get<T>(token: ProviderToken<T>, notFoundValue?: T, flags?: InjectFlags | InjectOptions): T { flags = convertToBitFlags(flags); const value = this.injector.get<T | typeof NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR>( token, NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR, flags, ); if ( value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR || notFoundValue === (NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR as unknown as T) ) { // Return the value from the root element injector when // - it provides it // (value !== NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) // - the module injector should not be checked // (notFoundValue === NOT_FOUND_CHECK_ONLY_ELEMENT_INJECTOR) return value as T; } return this.parentInjector.get(token, notFoundValue, flags); } }
{ "end_byte": 1665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/chained_injector.ts" }
angular/packages/core/src/render3/ng_module_ref.ts_0_7103
/** * @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 {createInjectorWithoutInjectorInstances} from '../di/create_injector'; import {Injector} from '../di/injector'; import {EnvironmentProviders, Provider, StaticProvider} from '../di/interface/provider'; import {EnvironmentInjector, getNullInjector, R3Injector} from '../di/r3_injector'; import {Type} from '../interface/type'; import {ComponentFactoryResolver as viewEngine_ComponentFactoryResolver} from '../linker/component_factory_resolver'; import { InternalNgModuleRef, NgModuleFactory as viewEngine_NgModuleFactory, NgModuleRef as viewEngine_NgModuleRef, } from '../linker/ng_module_factory'; import {assertDefined} from '../util/assert'; import {stringify} from '../util/stringify'; import {ComponentFactoryResolver} from './component_ref'; import {getNgModuleDef} from './def_getters'; import {maybeUnwrapFn} from './util/misc_utils'; /** * Returns a new NgModuleRef instance based on the NgModule class and parent injector provided. * * @param ngModule NgModule class. * @param parentInjector Optional injector instance to use as a parent for the module injector. If * not provided, `NullInjector` will be used instead. * @returns NgModuleRef that represents an NgModule instance. * * @publicApi */ export function createNgModule<T>( ngModule: Type<T>, parentInjector?: Injector, ): viewEngine_NgModuleRef<T> { return new NgModuleRef<T>(ngModule, parentInjector ?? null, []); } /** * The `createNgModule` function alias for backwards-compatibility. * Please avoid using it directly and use `createNgModule` instead. * * @deprecated Use `createNgModule` instead. */ export const createNgModuleRef = createNgModule; export class NgModuleRef<T> extends viewEngine_NgModuleRef<T> implements InternalNgModuleRef<T> { // tslint:disable-next-line:require-internal-with-underscore _bootstrapComponents: Type<any>[] = []; // tslint:disable-next-line:require-internal-with-underscore private readonly _r3Injector: R3Injector; override instance!: T; destroyCbs: (() => void)[] | null = []; // When bootstrapping a module we have a dependency graph that looks like this: // ApplicationRef -> ComponentFactoryResolver -> NgModuleRef. The problem is that if the // module being resolved tries to inject the ComponentFactoryResolver, it'll create a // circular dependency which will result in a runtime error, because the injector doesn't // exist yet. We work around the issue by creating the ComponentFactoryResolver ourselves // and providing it, rather than letting the injector resolve it. override readonly componentFactoryResolver: ComponentFactoryResolver = new ComponentFactoryResolver(this); constructor( private readonly ngModuleType: Type<T>, public _parent: Injector | null, additionalProviders: StaticProvider[], runInjectorInitializers = true, ) { super(); const ngModuleDef = getNgModuleDef(ngModuleType); ngDevMode && assertDefined( ngModuleDef, `NgModule '${stringify(ngModuleType)}' is not a subtype of 'NgModuleType'.`, ); this._bootstrapComponents = maybeUnwrapFn(ngModuleDef!.bootstrap); this._r3Injector = createInjectorWithoutInjectorInstances( ngModuleType, _parent, [ {provide: viewEngine_NgModuleRef, useValue: this}, { provide: viewEngine_ComponentFactoryResolver, useValue: this.componentFactoryResolver, }, ...additionalProviders, ], stringify(ngModuleType), new Set(['environment']), ) as R3Injector; // We need to resolve the injector types separately from the injector creation, because // the module might be trying to use this ref in its constructor for DI which will cause a // circular error that will eventually error out, because the injector isn't created yet. if (runInjectorInitializers) { this.resolveInjectorInitializers(); } } resolveInjectorInitializers() { this._r3Injector.resolveInjectorInitializers(); this.instance = this._r3Injector.get(this.ngModuleType); } override get injector(): EnvironmentInjector { return this._r3Injector; } override destroy(): void { ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed'); const injector = this._r3Injector; !injector.destroyed && injector.destroy(); this.destroyCbs!.forEach((fn) => fn()); this.destroyCbs = null; } override onDestroy(callback: () => void): void { ngDevMode && assertDefined(this.destroyCbs, 'NgModule already destroyed'); this.destroyCbs!.push(callback); } } export class NgModuleFactory<T> extends viewEngine_NgModuleFactory<T> { constructor(public moduleType: Type<T>) { super(); } override create(parentInjector: Injector | null): viewEngine_NgModuleRef<T> { return new NgModuleRef(this.moduleType, parentInjector, []); } } export function createNgModuleRefWithProviders<T>( moduleType: Type<T>, parentInjector: Injector | null, additionalProviders: StaticProvider[], ): InternalNgModuleRef<T> { return new NgModuleRef(moduleType, parentInjector, additionalProviders, false); } export class EnvironmentNgModuleRefAdapter extends viewEngine_NgModuleRef<null> { override readonly injector: R3Injector; override readonly componentFactoryResolver: ComponentFactoryResolver = new ComponentFactoryResolver(this); override readonly instance = null; constructor(config: { providers: Array<Provider | EnvironmentProviders>; parent: EnvironmentInjector | null; debugName: string | null; runEnvironmentInitializers: boolean; }) { super(); const injector = new R3Injector( [ ...config.providers, {provide: viewEngine_NgModuleRef, useValue: this}, {provide: viewEngine_ComponentFactoryResolver, useValue: this.componentFactoryResolver}, ], config.parent || getNullInjector(), config.debugName, new Set(['environment']), ); this.injector = injector; if (config.runEnvironmentInitializers) { injector.resolveInjectorInitializers(); } } override destroy(): void { this.injector.destroy(); } override onDestroy(callback: () => void): void { this.injector.onDestroy(callback); } } /** * Create a new environment injector. * * @param providers An array of providers. * @param parent A parent environment injector. * @param debugName An optional name for this injector instance, which will be used in error * messages. * * @publicApi */ export function createEnvironmentInjector( providers: Array<Provider | EnvironmentProviders>, parent: EnvironmentInjector, debugName: string | null = null, ): EnvironmentInjector { const adapter = new EnvironmentNgModuleRefAdapter({ providers, parent, debugName, runEnvironmentInitializers: true, }); return adapter.injector; }
{ "end_byte": 7103, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/ng_module_ref.ts" }
angular/packages/core/src/render3/node_selector_matcher.ts_0_7300
/** * @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 {assertDefined, assertEqual, assertNotEqual} from '../util/assert'; import {AttributeMarker} from './interfaces/attribute_marker'; import {TAttributes, TNode, TNodeType} from './interfaces/node'; import {CssSelector, CssSelectorList, SelectorFlags} from './interfaces/projection'; import {classIndexOf} from './styling/class_differ'; import {isNameOnlyAttributeMarker} from './util/attrs_utils'; const NG_TEMPLATE_SELECTOR = 'ng-template'; /** * Search the `TAttributes` to see if it contains `cssClassToMatch` (case insensitive) * * @param tNode static data of the node to match * @param attrs `TAttributes` to search through. * @param cssClassToMatch class to match (lowercase) * @param isProjectionMode Whether or not class matching should look into the attribute `class` in * addition to the `AttributeMarker.Classes`. */ function isCssClassMatching( tNode: TNode, attrs: TAttributes, cssClassToMatch: string, isProjectionMode: boolean, ): boolean { ngDevMode && assertEqual( cssClassToMatch, cssClassToMatch.toLowerCase(), 'Class name expected to be lowercase.', ); let i = 0; if (isProjectionMode) { for (; i < attrs.length && typeof attrs[i] === 'string'; i += 2) { // Search for an implicit `class` attribute and check if its value matches `cssClassToMatch`. if ( attrs[i] === 'class' && classIndexOf((attrs[i + 1] as string).toLowerCase(), cssClassToMatch, 0) !== -1 ) { return true; } } } else if (isInlineTemplate(tNode)) { // Matching directives (i.e. when not matching for projection mode) should not consider the // class bindings that are present on inline templates, as those class bindings only target // the root node of the template, not the template itself. return false; } // Resume the search for classes after the `Classes` marker. i = attrs.indexOf(AttributeMarker.Classes, i); if (i > -1) { // We found the classes section. Start searching for the class. let item: TAttributes[number]; while (++i < attrs.length && typeof (item = attrs[i]) === 'string') { if (item.toLowerCase() === cssClassToMatch) { return true; } } } return false; } /** * Checks whether the `tNode` represents an inline template (e.g. `*ngFor`). * * @param tNode current TNode */ export function isInlineTemplate(tNode: TNode): boolean { return tNode.type === TNodeType.Container && tNode.value !== NG_TEMPLATE_SELECTOR; } /** * Function that checks whether a given tNode matches tag-based selector and has a valid type. * * Matching can be performed in 2 modes: projection mode (when we project nodes) and regular * directive matching mode: * - in the "directive matching" mode we do _not_ take TContainer's tagName into account if it is * different from NG_TEMPLATE_SELECTOR (value different from NG_TEMPLATE_SELECTOR indicates that a * tag name was extracted from * syntax so we would match the same directive twice); * - in the "projection" mode, we use a tag name potentially extracted from the * syntax processing * (applicable to TNodeType.Container only). */ function hasTagAndTypeMatch( tNode: TNode, currentSelector: string, isProjectionMode: boolean, ): boolean { const tagNameToCompare = tNode.type === TNodeType.Container && !isProjectionMode ? NG_TEMPLATE_SELECTOR : tNode.value; return currentSelector === tagNameToCompare; } /** * A utility function to match an Ivy node static data against a simple CSS selector * * @param tNode static data of the node to match * @param selector The selector to try matching against the node. * @param isProjectionMode if `true` we are matching for content projection, otherwise we are doing * directive matching. * @returns true if node matches the selector. */ export function isNodeMatchingSelector( tNode: TNode, selector: CssSelector, isProjectionMode: boolean, ): boolean { ngDevMode && assertDefined(selector[0], 'Selector should have a tag name'); let mode: SelectorFlags = SelectorFlags.ELEMENT; const nodeAttrs = tNode.attrs; // Find the index of first attribute that has no value, only a name. const nameOnlyMarkerIdx = nodeAttrs !== null ? getNameOnlyMarkerIndex(nodeAttrs) : 0; // When processing ":not" selectors, we skip to the next ":not" if the // current one doesn't match let skipToNextSelector = false; for (let i = 0; i < selector.length; i++) { const current = selector[i]; if (typeof current === 'number') { // If we finish processing a :not selector and it hasn't failed, return false if (!skipToNextSelector && !isPositive(mode) && !isPositive(current)) { return false; } // If we are skipping to the next :not() and this mode flag is positive, // it's a part of the current :not() selector, and we should keep skipping if (skipToNextSelector && isPositive(current)) continue; skipToNextSelector = false; mode = (current as number) | (mode & SelectorFlags.NOT); continue; } if (skipToNextSelector) continue; if (mode & SelectorFlags.ELEMENT) { mode = SelectorFlags.ATTRIBUTE | (mode & SelectorFlags.NOT); if ( (current !== '' && !hasTagAndTypeMatch(tNode, current, isProjectionMode)) || (current === '' && selector.length === 1) ) { if (isPositive(mode)) return false; skipToNextSelector = true; } } else if (mode & SelectorFlags.CLASS) { if (nodeAttrs === null || !isCssClassMatching(tNode, nodeAttrs, current, isProjectionMode)) { if (isPositive(mode)) return false; skipToNextSelector = true; } } else { const selectorAttrValue = selector[++i]; const attrIndexInNode = findAttrIndexInNode( current, nodeAttrs, isInlineTemplate(tNode), isProjectionMode, ); if (attrIndexInNode === -1) { if (isPositive(mode)) return false; skipToNextSelector = true; continue; } if (selectorAttrValue !== '') { let nodeAttrValue: string; if (attrIndexInNode > nameOnlyMarkerIdx) { nodeAttrValue = ''; } else { ngDevMode && assertNotEqual( nodeAttrs![attrIndexInNode], AttributeMarker.NamespaceURI, 'We do not match directives on namespaced attributes', ); // we lowercase the attribute value to be able to match // selectors without case-sensitivity // (selectors are already in lowercase when generated) nodeAttrValue = (nodeAttrs![attrIndexInNode + 1] as string).toLowerCase(); } if (mode & SelectorFlags.ATTRIBUTE && selectorAttrValue !== nodeAttrValue) { if (isPositive(mode)) return false; skipToNextSelector = true; } } } } return isPositive(mode) || skipToNextSelector; } function isPositive(mode: SelectorFlags): boolean { return (mode & SelectorFlags.NOT) === 0; }
{ "end_byte": 7300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_selector_matcher.ts" }
angular/packages/core/src/render3/node_selector_matcher.ts_7302_16040
/** * Examines the attribute's definition array for a node to find the index of the * attribute that matches the given `name`. * * NOTE: This will not match namespaced attributes. * * Attribute matching depends upon `isInlineTemplate` and `isProjectionMode`. * The following table summarizes which types of attributes we attempt to match: * * =========================================================================================================== * Modes | Normal Attributes | Bindings Attributes | Template Attributes | I18n * Attributes * =========================================================================================================== * Inline + Projection | YES | YES | NO | YES * ----------------------------------------------------------------------------------------------------------- * Inline + Directive | NO | NO | YES | NO * ----------------------------------------------------------------------------------------------------------- * Non-inline + Projection | YES | YES | NO | YES * ----------------------------------------------------------------------------------------------------------- * Non-inline + Directive | YES | YES | NO | YES * =========================================================================================================== * * @param name the name of the attribute to find * @param attrs the attribute array to examine * @param isInlineTemplate true if the node being matched is an inline template (e.g. `*ngFor`) * rather than a manually expanded template node (e.g `<ng-template>`). * @param isProjectionMode true if we are matching against content projection otherwise we are * matching against directives. */ function findAttrIndexInNode( name: string, attrs: TAttributes | null, isInlineTemplate: boolean, isProjectionMode: boolean, ): number { if (attrs === null) return -1; let i = 0; if (isProjectionMode || !isInlineTemplate) { let bindingsMode = false; while (i < attrs.length) { const maybeAttrName = attrs[i]; if (maybeAttrName === name) { return i; } else if ( maybeAttrName === AttributeMarker.Bindings || maybeAttrName === AttributeMarker.I18n ) { bindingsMode = true; } else if ( maybeAttrName === AttributeMarker.Classes || maybeAttrName === AttributeMarker.Styles ) { let value = attrs[++i]; // We should skip classes here because we have a separate mechanism for // matching classes in projection mode. while (typeof value === 'string') { value = attrs[++i]; } continue; } else if (maybeAttrName === AttributeMarker.Template) { // We do not care about Template attributes in this scenario. break; } else if (maybeAttrName === AttributeMarker.NamespaceURI) { // Skip the whole namespaced attribute and value. This is by design. i += 4; continue; } // In binding mode there are only names, rather than name-value pairs. i += bindingsMode ? 1 : 2; } // We did not match the attribute return -1; } else { return matchTemplateAttribute(attrs, name); } } export function isNodeMatchingSelectorList( tNode: TNode, selector: CssSelectorList, isProjectionMode: boolean = false, ): boolean { for (let i = 0; i < selector.length; i++) { if (isNodeMatchingSelector(tNode, selector[i], isProjectionMode)) { return true; } } return false; } export function getProjectAsAttrValue(tNode: TNode): CssSelector | null { const nodeAttrs = tNode.attrs; if (nodeAttrs != null) { const ngProjectAsAttrIdx = nodeAttrs.indexOf(AttributeMarker.ProjectAs); // only check for ngProjectAs in attribute names, don't accidentally match attribute's value // (attribute names are stored at even indexes) if ((ngProjectAsAttrIdx & 1) === 0) { return nodeAttrs[ngProjectAsAttrIdx + 1] as CssSelector; } } return null; } function getNameOnlyMarkerIndex(nodeAttrs: TAttributes) { for (let i = 0; i < nodeAttrs.length; i++) { const nodeAttr = nodeAttrs[i]; if (isNameOnlyAttributeMarker(nodeAttr)) { return i; } } return nodeAttrs.length; } function matchTemplateAttribute(attrs: TAttributes, name: string): number { let i = attrs.indexOf(AttributeMarker.Template); if (i > -1) { i++; while (i < attrs.length) { const attr = attrs[i]; // Return in case we checked all template attrs and are switching to the next section in the // attrs array (that starts with a number that represents an attribute marker). if (typeof attr === 'number') return -1; if (attr === name) return i; i++; } } return -1; } /** * Checks whether a selector is inside a CssSelectorList * @param selector Selector to be checked. * @param list List in which to look for the selector. */ export function isSelectorInSelectorList(selector: CssSelector, list: CssSelectorList): boolean { selectorListLoop: for (let i = 0; i < list.length; i++) { const currentSelectorInList = list[i]; if (selector.length !== currentSelectorInList.length) { continue; } for (let j = 0; j < selector.length; j++) { if (selector[j] !== currentSelectorInList[j]) { continue selectorListLoop; } } return true; } return false; } function maybeWrapInNotSelector(isNegativeMode: boolean, chunk: string): string { return isNegativeMode ? ':not(' + chunk.trim() + ')' : chunk; } function stringifyCSSSelector(selector: CssSelector): string { let result = selector[0] as string; let i = 1; let mode = SelectorFlags.ATTRIBUTE; let currentChunk = ''; let isNegativeMode = false; while (i < selector.length) { let valueOrMarker = selector[i]; if (typeof valueOrMarker === 'string') { if (mode & SelectorFlags.ATTRIBUTE) { const attrValue = selector[++i] as string; currentChunk += '[' + valueOrMarker + (attrValue.length > 0 ? '="' + attrValue + '"' : '') + ']'; } else if (mode & SelectorFlags.CLASS) { currentChunk += '.' + valueOrMarker; } else if (mode & SelectorFlags.ELEMENT) { currentChunk += ' ' + valueOrMarker; } } else { // // Append current chunk to the final result in case we come across SelectorFlag, which // indicates that the previous section of a selector is over. We need to accumulate content // between flags to make sure we wrap the chunk later in :not() selector if needed, e.g. // ``` // ['', Flags.CLASS, '.classA', Flags.CLASS | Flags.NOT, '.classB', '.classC'] // ``` // should be transformed to `.classA :not(.classB .classC)`. // // Note: for negative selector part, we accumulate content between flags until we find the // next negative flag. This is needed to support a case where `:not()` rule contains more than // one chunk, e.g. the following selector: // ``` // ['', Flags.ELEMENT | Flags.NOT, 'p', Flags.CLASS, 'foo', Flags.CLASS | Flags.NOT, 'bar'] // ``` // should be stringified to `:not(p.foo) :not(.bar)` // if (currentChunk !== '' && !isPositive(valueOrMarker)) { result += maybeWrapInNotSelector(isNegativeMode, currentChunk); currentChunk = ''; } mode = valueOrMarker; // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative // mode is maintained for remaining chunks of a selector. isNegativeMode = isNegativeMode || !isPositive(mode); } i++; } if (currentChunk !== '') { result += maybeWrapInNotSelector(isNegativeMode, currentChunk); } return result; } /** * Generates string representation of CSS selector in parsed form. * * ComponentDef and DirectiveDef are generated with the selector in parsed form to avoid doing * additional parsing at runtime (for example, for directive matching). However in some cases (for * example, while bootstrapping a component), a string version of the selector is required to query * for the host element on the page. This function takes the parsed form of a selector and returns * its string representation. * * @param selectorList selector in parsed form * @returns string representation of a given selector */ export function stringifyCSSSelectorList(selectorList: CssSelectorList): string { return selectorList.map(stringifyCSSSelector).join(','); }
{ "end_byte": 16040, "start_byte": 7302, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_selector_matcher.ts" }
angular/packages/core/src/render3/node_selector_matcher.ts_16042_17490
/** * Extracts attributes and classes information from a given CSS selector. * * This function is used while creating a component dynamically. In this case, the host element * (that is created dynamically) should contain attributes and classes specified in component's CSS * selector. * * @param selector CSS selector in parsed form (in a form of array) * @returns object with `attrs` and `classes` fields that contain extracted information */ export function extractAttrsAndClassesFromSelector(selector: CssSelector): { attrs: string[]; classes: string[]; } { const attrs: string[] = []; const classes: string[] = []; let i = 1; let mode = SelectorFlags.ATTRIBUTE; while (i < selector.length) { let valueOrMarker = selector[i]; if (typeof valueOrMarker === 'string') { if (mode === SelectorFlags.ATTRIBUTE) { if (valueOrMarker !== '') { attrs.push(valueOrMarker, selector[++i] as string); } } else if (mode === SelectorFlags.CLASS) { classes.push(valueOrMarker); } } else { // According to CssSelector spec, once we come across `SelectorFlags.NOT` flag, the negative // mode is maintained for remaining chunks of a selector. Since attributes and classes are // extracted only for "positive" part of the selector, we can stop here. if (!isPositive(mode)) break; mode = valueOrMarker; } i++; } return {attrs, classes}; }
{ "end_byte": 17490, "start_byte": 16042, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_selector_matcher.ts" }
angular/packages/core/src/render3/node_manipulation.ts_0_7761
/** * @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 { consumerDestroy, getActiveConsumer, setActiveConsumer, } from '@angular/core/primitives/signals'; import {NotificationSource} from '../change_detection/scheduling/zoneless_scheduling'; import {hasInSkipHydrationBlockFlag} from '../hydration/skip_hydration'; import {ViewEncapsulation} from '../metadata/view'; import {RendererStyleFlags2} from '../render/api_flags'; import {addToArray, removeFromArray} from '../util/array_utils'; import { assertDefined, assertEqual, assertFunction, assertNotReactive, assertNumber, assertString, } from '../util/assert'; import {escapeCommentText} from '../util/dom'; import { assertLContainer, assertLView, assertParentView, assertProjectionSlots, assertTNodeForLView, } from './assert'; import {attachPatchData} from './context_discovery'; import {icuContainerIterate} from './i18n/i18n_tree_shaking'; import { CONTAINER_HEADER_OFFSET, LContainer, LContainerFlags, MOVED_VIEWS, NATIVE, } from './interfaces/container'; import {ComponentDef} from './interfaces/definition'; import {NodeInjectorFactory} from './interfaces/injector'; import {unregisterLView} from './interfaces/lview_tracking'; import { TElementNode, TIcuContainerNode, TNode, TNodeFlags, TNodeType, TProjectionNode, } from './interfaces/node'; import {Renderer} from './interfaces/renderer'; import {RComment, RElement, RNode, RTemplate, RText} from './interfaces/renderer_dom'; import {isLContainer, isLView} from './interfaces/type_checks'; import { CHILD_HEAD, CLEANUP, DECLARATION_COMPONENT_VIEW, DECLARATION_LCONTAINER, DestroyHookData, EFFECTS, ENVIRONMENT, FLAGS, HookData, HookFn, HOST, LView, LViewFlags, NEXT, ON_DESTROY_HOOKS, PARENT, QUERIES, REACTIVE_TEMPLATE_CONSUMER, RENDERER, T_HOST, TVIEW, TView, TViewType, } from './interfaces/view'; import {assertTNodeType} from './node_assert'; import {profiler} from './profiler'; import {ProfilerEvent} from './profiler_types'; import {setUpAttributes} from './util/attrs_utils'; import { getLViewParent, getNativeByTNode, unwrapRNode, updateAncestorTraversalFlagsOnAttach, } from './util/view_utils'; import {EMPTY_ARRAY} from '../util/empty'; const enum WalkTNodeTreeAction { /** node create in the native environment. Run on initial creation. */ Create = 0, /** * node insert in the native environment. * Run when existing node has been detached and needs to be re-attached. */ Insert = 1, /** node detach from the native environment */ Detach = 2, /** node destruction using the renderer's API */ Destroy = 3, } /** * NOTE: for performance reasons, the possible actions are inlined within the function instead of * being passed as an argument. */ function applyToElementOrContainer( action: WalkTNodeTreeAction, renderer: Renderer, parent: RElement | null, lNodeToHandle: RNode | LContainer | LView, beforeNode?: RNode | null, ) { // If this slot was allocated for a text node dynamically created by i18n, the text node itself // won't be created until i18nApply() in the update block, so this node should be skipped. // For more info, see "ICU expressions should work inside an ngTemplateOutlet inside an ngFor" // in `i18n_spec.ts`. if (lNodeToHandle != null) { let lContainer: LContainer | undefined; let isComponent = false; // We are expecting an RNode, but in the case of a component or LContainer the `RNode` is // wrapped in an array which needs to be unwrapped. We need to know if it is a component and if // it has LContainer so that we can process all of those cases appropriately. if (isLContainer(lNodeToHandle)) { lContainer = lNodeToHandle; } else if (isLView(lNodeToHandle)) { isComponent = true; ngDevMode && assertDefined(lNodeToHandle[HOST], 'HOST must be defined for a component LView'); lNodeToHandle = lNodeToHandle[HOST]!; } const rNode: RNode = unwrapRNode(lNodeToHandle); if (action === WalkTNodeTreeAction.Create && parent !== null) { if (beforeNode == null) { nativeAppendChild(renderer, parent, rNode); } else { nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true); } } else if (action === WalkTNodeTreeAction.Insert && parent !== null) { nativeInsertBefore(renderer, parent, rNode, beforeNode || null, true); } else if (action === WalkTNodeTreeAction.Detach) { nativeRemoveNode(renderer, rNode, isComponent); } else if (action === WalkTNodeTreeAction.Destroy) { ngDevMode && ngDevMode.rendererDestroyNode++; renderer.destroyNode!(rNode); } if (lContainer != null) { applyContainer(renderer, action, lContainer, parent, beforeNode); } } } export function createTextNode(renderer: Renderer, value: string): RText { ngDevMode && ngDevMode.rendererCreateTextNode++; ngDevMode && ngDevMode.rendererSetText++; return renderer.createText(value); } export function updateTextNode(renderer: Renderer, rNode: RText, value: string): void { ngDevMode && ngDevMode.rendererSetText++; renderer.setValue(rNode, value); } export function createCommentNode(renderer: Renderer, value: string): RComment { ngDevMode && ngDevMode.rendererCreateComment++; return renderer.createComment(escapeCommentText(value)); } /** * Creates a native element from a tag name, using a renderer. * @param renderer A renderer to use * @param name the tag name * @param namespace Optional namespace for element. * @returns the element created */ export function createElementNode( renderer: Renderer, name: string, namespace: string | null, ): RElement { ngDevMode && ngDevMode.rendererCreateElement++; return renderer.createElement(name, namespace); } /** * Removes all DOM elements associated with a view. * * Because some root nodes of the view may be containers, we sometimes need * to propagate deeply into the nested containers to remove all elements in the * views beneath it. * * @param tView The `TView' of the `LView` from which elements should be added or removed * @param lView The view from which elements should be added or removed */ export function removeViewFromDOM(tView: TView, lView: LView): void { detachViewFromDOM(tView, lView); lView[HOST] = null; lView[T_HOST] = null; } /** * Adds all DOM elements associated with a view. * * Because some root nodes of the view may be containers, we sometimes need * to propagate deeply into the nested containers to add all elements in the * views beneath it. * * @param tView The `TView' of the `LView` from which elements should be added or removed * @param parentTNode The `TNode` where the `LView` should be attached to. * @param renderer Current renderer to use for DOM manipulations. * @param lView The view from which elements should be added or removed * @param parentNativeNode The parent `RElement` where it should be inserted into. * @param beforeNode The node before which elements should be added, if insert mode */ export function addViewToDOM( tView: TView, parentTNode: TNode, renderer: Renderer, lView: LView, parentNativeNode: RElement, beforeNode: RNode | null, ): void { lView[HOST] = parentNativeNode; lView[T_HOST] = parentTNode; applyView(tView, lView, renderer, WalkTNodeTreeAction.Insert, parentNativeNode, beforeNode); } /** * Detach a `LView` from the DOM by detaching its nodes. * * @param tView The `TView' of the `LView` to be detached * @param lView the `LView` to be detached. */
{ "end_byte": 7761, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_7762_15619
export function detachViewFromDOM(tView: TView, lView: LView) { // When we remove a view from the DOM, we need to rerun afterRender hooks // We don't necessarily needs to run change detection. DOM removal only requires // change detection if animations are enabled (this notification is handled by animations). lView[ENVIRONMENT].changeDetectionScheduler?.notify(NotificationSource.ViewDetachedFromDOM); applyView(tView, lView, lView[RENDERER], WalkTNodeTreeAction.Detach, null, null); } /** * Traverses down and up the tree of views and containers to remove listeners and * call onDestroy callbacks. * * Notes: * - Because it's used for onDestroy calls, it needs to be bottom-up. * - Must process containers instead of their views to avoid splicing * when views are destroyed and re-added. * - Using a while loop because it's faster than recursion * - Destroy only called on movement to sibling or movement to parent (laterally or up) * * @param rootView The view to destroy */ export function destroyViewTree(rootView: LView): void { // If the view has no children, we can clean it up and return early. let lViewOrLContainer = rootView[CHILD_HEAD]; if (!lViewOrLContainer) { return cleanUpView(rootView[TVIEW], rootView); } while (lViewOrLContainer) { let next: LView | LContainer | null = null; if (isLView(lViewOrLContainer)) { // If LView, traverse down to child. next = lViewOrLContainer[CHILD_HEAD]; } else { ngDevMode && assertLContainer(lViewOrLContainer); // If container, traverse down to its first LView. const firstView: LView | undefined = lViewOrLContainer[CONTAINER_HEADER_OFFSET]; if (firstView) next = firstView; } if (!next) { // Only clean up view when moving to the side or up, as destroy hooks // should be called in order from the bottom up. while (lViewOrLContainer && !lViewOrLContainer![NEXT] && lViewOrLContainer !== rootView) { if (isLView(lViewOrLContainer)) { cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer); } lViewOrLContainer = lViewOrLContainer[PARENT]; } if (lViewOrLContainer === null) lViewOrLContainer = rootView; if (isLView(lViewOrLContainer)) { cleanUpView(lViewOrLContainer[TVIEW], lViewOrLContainer); } next = lViewOrLContainer && lViewOrLContainer![NEXT]; } lViewOrLContainer = next; } } /** * Inserts a view into a container. * * This adds the view to the container's array of active views in the correct * position. It also adds the view's elements to the DOM if the container isn't a * root node of another view (in that case, the view's elements will be added when * the container's parent view is added later). * * @param tView The `TView' of the `LView` to insert * @param lView The view to insert * @param lContainer The container into which the view should be inserted * @param index Which index in the container to insert the child view into */ export function insertView(tView: TView, lView: LView, lContainer: LContainer, index: number) { ngDevMode && assertLView(lView); ngDevMode && assertLContainer(lContainer); const indexInContainer = CONTAINER_HEADER_OFFSET + index; const containerLength = lContainer.length; if (index > 0) { // This is a new view, we need to add it to the children. lContainer[indexInContainer - 1][NEXT] = lView; } if (index < containerLength - CONTAINER_HEADER_OFFSET) { lView[NEXT] = lContainer[indexInContainer]; addToArray(lContainer, CONTAINER_HEADER_OFFSET + index, lView); } else { lContainer.push(lView); lView[NEXT] = null; } lView[PARENT] = lContainer; // track views where declaration and insertion points are different const declarationLContainer = lView[DECLARATION_LCONTAINER]; if (declarationLContainer !== null && lContainer !== declarationLContainer) { trackMovedView(declarationLContainer, lView); } // notify query that a new view has been added const lQueries = lView[QUERIES]; if (lQueries !== null) { lQueries.insertView(tView); } updateAncestorTraversalFlagsOnAttach(lView); // Sets the attached flag lView[FLAGS] |= LViewFlags.Attached; } /** * Track views created from the declaration container (TemplateRef) and inserted into a * different LContainer or attached directly to ApplicationRef. */ export function trackMovedView(declarationContainer: LContainer, lView: LView) { ngDevMode && assertDefined(lView, 'LView required'); ngDevMode && assertLContainer(declarationContainer); const movedViews = declarationContainer[MOVED_VIEWS]; const parent = lView[PARENT]!; ngDevMode && assertDefined(parent, 'missing parent'); if (isLView(parent)) { declarationContainer[FLAGS] |= LContainerFlags.HasTransplantedViews; } else { const insertedComponentLView = parent[PARENT]![DECLARATION_COMPONENT_VIEW]; ngDevMode && assertDefined(insertedComponentLView, 'Missing insertedComponentLView'); const declaredComponentLView = lView[DECLARATION_COMPONENT_VIEW]; ngDevMode && assertDefined(declaredComponentLView, 'Missing declaredComponentLView'); if (declaredComponentLView !== insertedComponentLView) { // At this point the declaration-component is not same as insertion-component; this means that // this is a transplanted view. Mark the declared lView as having transplanted views so that // those views can participate in CD. declarationContainer[FLAGS] |= LContainerFlags.HasTransplantedViews; } } if (movedViews === null) { declarationContainer[MOVED_VIEWS] = [lView]; } else { movedViews.push(lView); } } export function detachMovedView(declarationContainer: LContainer, lView: LView) { ngDevMode && assertLContainer(declarationContainer); ngDevMode && assertDefined( declarationContainer[MOVED_VIEWS], 'A projected view should belong to a non-empty projected views collection', ); const movedViews = declarationContainer[MOVED_VIEWS]!; const declarationViewIndex = movedViews.indexOf(lView); movedViews.splice(declarationViewIndex, 1); } /** * Detaches a view from a container. * * This method removes the view from the container's array of active views. It also * removes the view's elements from the DOM. * * @param lContainer The container from which to detach a view * @param removeIndex The index of the view to detach * @returns Detached LView instance. */ export function detachView(lContainer: LContainer, removeIndex: number): LView | undefined { if (lContainer.length <= CONTAINER_HEADER_OFFSET) return; const indexInContainer = CONTAINER_HEADER_OFFSET + removeIndex; const viewToDetach = lContainer[indexInContainer]; if (viewToDetach) { const declarationLContainer = viewToDetach[DECLARATION_LCONTAINER]; if (declarationLContainer !== null && declarationLContainer !== lContainer) { detachMovedView(declarationLContainer, viewToDetach); } if (removeIndex > 0) { lContainer[indexInContainer - 1][NEXT] = viewToDetach[NEXT] as LView; } const removedLView = removeFromArray(lContainer, CONTAINER_HEADER_OFFSET + removeIndex); removeViewFromDOM(viewToDetach[TVIEW], viewToDetach); // notify query that a view has been removed const lQueries = removedLView[QUERIES]; if (lQueries !== null) { lQueries.detachView(removedLView[TVIEW]); } viewToDetach[PARENT] = null; viewToDetach[NEXT] = null; // Unsets the attached flag viewToDetach[FLAGS] &= ~LViewFlags.Attached; } return viewToDetach; } /** * A standalone function which destroys an LView, * conducting clean up (e.g. removing listeners, calling onDestroys). * * @param tView The `TView' of the `LView` to be destroyed * @param lView The view to be destroyed. */
{ "end_byte": 15619, "start_byte": 7762, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_15620_23238
export function destroyLView(tView: TView, lView: LView) { if (!(lView[FLAGS] & LViewFlags.Destroyed)) { const renderer = lView[RENDERER]; if (renderer.destroyNode) { applyView(tView, lView, renderer, WalkTNodeTreeAction.Destroy, null, null); } destroyViewTree(lView); } } /** * Calls onDestroys hooks for all directives and pipes in a given view and then removes all * listeners. Listeners are removed as the last step so events delivered in the onDestroys hooks * can be propagated to @Output listeners. * * @param tView `TView` for the `LView` to clean up. * @param lView The LView to clean up */ function cleanUpView(tView: TView, lView: LView): void { if (lView[FLAGS] & LViewFlags.Destroyed) { return; } const prevConsumer = setActiveConsumer(null); try { // Usually the Attached flag is removed when the view is detached from its parent, however // if it's a root view, the flag won't be unset hence why we're also removing on destroy. lView[FLAGS] &= ~LViewFlags.Attached; // Mark the LView as destroyed *before* executing the onDestroy hooks. An onDestroy hook // runs arbitrary user code, which could include its own `viewRef.destroy()` (or similar). If // We don't flag the view as destroyed before the hooks, this could lead to an infinite loop. // This also aligns with the ViewEngine behavior. It also means that the onDestroy hook is // really more of an "afterDestroy" hook if you think about it. lView[FLAGS] |= LViewFlags.Destroyed; lView[REACTIVE_TEMPLATE_CONSUMER] && consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]); executeOnDestroys(tView, lView); processCleanups(tView, lView); // For component views only, the local renderer is destroyed at clean up time. if (lView[TVIEW].type === TViewType.Component) { ngDevMode && ngDevMode.rendererDestroy++; lView[RENDERER].destroy(); } const declarationContainer = lView[DECLARATION_LCONTAINER]; // we are dealing with an embedded view that is still inserted into a container if (declarationContainer !== null && isLContainer(lView[PARENT])) { // and this is a projected view if (declarationContainer !== lView[PARENT]) { detachMovedView(declarationContainer, lView); } // For embedded views still attached to a container: remove query result from this view. const lQueries = lView[QUERIES]; if (lQueries !== null) { lQueries.detachView(tView); } } // Unregister the view once everything else has been cleaned up. unregisterLView(lView); } finally { setActiveConsumer(prevConsumer); } } /** Removes listeners and unsubscribes from output subscriptions */ function processCleanups(tView: TView, lView: LView): void { ngDevMode && assertNotReactive(processCleanups.name); const tCleanup = tView.cleanup; const lCleanup = lView[CLEANUP]!; if (tCleanup !== null) { for (let i = 0; i < tCleanup.length - 1; i += 2) { if (typeof tCleanup[i] === 'string') { // This is a native DOM listener. It will occupy 4 entries in the TCleanup array (hence i += // 2 at the end of this block). const targetIdx = tCleanup[i + 3]; ngDevMode && assertNumber(targetIdx, 'cleanup target must be a number'); if (targetIdx >= 0) { // Destroy anything whose teardown is a function call (e.g. QueryList, ModelSignal). lCleanup[targetIdx](); } else { // Subscription lCleanup[-targetIdx].unsubscribe(); } i += 2; } else { // This is a cleanup function that is grouped with the index of its context const context = lCleanup[tCleanup[i + 1]]; tCleanup[i].call(context); } } } if (lCleanup !== null) { lView[CLEANUP] = null; } const destroyHooks = lView[ON_DESTROY_HOOKS]; if (destroyHooks !== null) { // Reset the ON_DESTROY_HOOKS array before iterating over it to prevent hooks that unregister // themselves from mutating the array during iteration. lView[ON_DESTROY_HOOKS] = null; for (let i = 0; i < destroyHooks.length; i++) { const destroyHooksFn = destroyHooks[i]; ngDevMode && assertFunction(destroyHooksFn, 'Expecting destroy hook to be a function.'); destroyHooksFn(); } } // Destroy effects registered to the view. Many of these will have been processed above. const effects = lView[EFFECTS]; if (effects !== null) { lView[EFFECTS] = null; for (const effect of effects) { effect.destroy(); } } } /** Calls onDestroy hooks for this view */ function executeOnDestroys(tView: TView, lView: LView): void { ngDevMode && assertNotReactive(executeOnDestroys.name); let destroyHooks: DestroyHookData | null; if (tView != null && (destroyHooks = tView.destroyHooks) != null) { for (let i = 0; i < destroyHooks.length; i += 2) { const context = lView[destroyHooks[i] as number]; // Only call the destroy hook if the context has been requested. if (!(context instanceof NodeInjectorFactory)) { const toCall = destroyHooks[i + 1] as HookFn | HookData; if (Array.isArray(toCall)) { for (let j = 0; j < toCall.length; j += 2) { const callContext = context[toCall[j] as number]; const hook = toCall[j + 1] as HookFn; profiler(ProfilerEvent.LifecycleHookStart, callContext, hook); try { hook.call(callContext); } finally { profiler(ProfilerEvent.LifecycleHookEnd, callContext, hook); } } } else { profiler(ProfilerEvent.LifecycleHookStart, context, toCall); try { toCall.call(context); } finally { profiler(ProfilerEvent.LifecycleHookEnd, context, toCall); } } } } } } /** * Returns a native element if a node can be inserted into the given parent. * * There are two reasons why we may not be able to insert a element immediately. * - Projection: When creating a child content element of a component, we have to skip the * insertion because the content of a component will be projected. * `<component><content>delayed due to projection</content></component>` * - Parent container is disconnected: This can happen when we are inserting a view into * parent container, which itself is disconnected. For example the parent container is part * of a View which has not be inserted or is made for projection but has not been inserted * into destination. * * @param tView: Current `TView`. * @param tNode: `TNode` for which we wish to retrieve render parent. * @param lView: Current `LView`. */ export function getParentRElement(tView: TView, tNode: TNode, lView: LView): RElement | null { return getClosestRElement(tView, tNode.parent, lView); } /** * Get closest `RElement` or `null` if it can't be found. * * If `TNode` is `TNodeType.Element` => return `RElement` at `LView[tNode.index]` location. * If `TNode` is `TNodeType.ElementContainer|IcuContain` => return the parent (recursively). * If `TNode` is `null` then return host `RElement`: * - return `null` if projection * - return `null` if parent container is disconnected (we have no parent.) * * @param tView: Current `TView`. * @param tNode: `TNode` for which we wish to retrieve `RElement` (or `null` if host element is * needed). * @param lView: Current `LView`. * @returns `null` if the `RElement` can't be determined at this time (no parent / projection) */
{ "end_byte": 23238, "start_byte": 15620, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_23239_30325
export function getClosestRElement( tView: TView, tNode: TNode | null, lView: LView, ): RElement | null { let parentTNode: TNode | null = tNode; // Skip over element and ICU containers as those are represented by a comment node and // can't be used as a render parent. Also skip let declarations since they don't have a // corresponding DOM node at all. while ( parentTNode !== null && parentTNode.type & (TNodeType.ElementContainer | TNodeType.Icu | TNodeType.LetDeclaration) ) { tNode = parentTNode; parentTNode = tNode.parent; } // If the parent tNode is null, then we are inserting across views: either into an embedded view // or a component view. if (parentTNode === null) { // We are inserting a root element of the component view into the component host element and // it should always be eager. return lView[HOST]; } else { ngDevMode && assertTNodeType(parentTNode, TNodeType.AnyRNode | TNodeType.Container); const {componentOffset} = parentTNode; if (componentOffset > -1) { ngDevMode && assertTNodeForLView(parentTNode, lView); const {encapsulation} = tView.data[ parentTNode.directiveStart + componentOffset ] as ComponentDef<unknown>; // We've got a parent which is an element in the current view. We just need to verify if the // parent element is not a component. Component's content nodes are not inserted immediately // because they will be projected, and so doing insert at this point would be wasteful. // Since the projection would then move it to its final destination. Note that we can't // make this assumption when using the Shadow DOM, because the native projection placeholders // (<content> or <slot>) have to be in place as elements are being inserted. if ( encapsulation === ViewEncapsulation.None || encapsulation === ViewEncapsulation.Emulated ) { return null; } } return getNativeByTNode(parentTNode, lView) as RElement; } } /** * Inserts a native node before another native node for a given parent. * This is a utility function that can be used when native nodes were determined. */ export function nativeInsertBefore( renderer: Renderer, parent: RElement, child: RNode, beforeNode: RNode | null, isMove: boolean, ): void { ngDevMode && ngDevMode.rendererInsertBefore++; renderer.insertBefore(parent, child, beforeNode, isMove); } function nativeAppendChild(renderer: Renderer, parent: RElement, child: RNode): void { ngDevMode && ngDevMode.rendererAppendChild++; ngDevMode && assertDefined(parent, 'parent node must be defined'); renderer.appendChild(parent, child); } function nativeAppendOrInsertBefore( renderer: Renderer, parent: RElement, child: RNode, beforeNode: RNode | null, isMove: boolean, ) { if (beforeNode !== null) { nativeInsertBefore(renderer, parent, child, beforeNode, isMove); } else { nativeAppendChild(renderer, parent, child); } } /** * Returns a native parent of a given native node. */ export function nativeParentNode(renderer: Renderer, node: RNode): RElement | null { return renderer.parentNode(node); } /** * Returns a native sibling of a given native node. */ export function nativeNextSibling(renderer: Renderer, node: RNode): RNode | null { return renderer.nextSibling(node); } /** * Find a node in front of which `currentTNode` should be inserted. * * This method determines the `RNode` in front of which we should insert the `currentRNode`. This * takes `TNode.insertBeforeIndex` into account if i18n code has been invoked. * * @param parentTNode parent `TNode` * @param currentTNode current `TNode` (The node which we would like to insert into the DOM) * @param lView current `LView` */ function getInsertInFrontOfRNode( parentTNode: TNode, currentTNode: TNode, lView: LView, ): RNode | null { return _getInsertInFrontOfRNodeWithI18n(parentTNode, currentTNode, lView); } /** * Find a node in front of which `currentTNode` should be inserted. (Does not take i18n into * account) * * This method determines the `RNode` in front of which we should insert the `currentRNode`. This * does not take `TNode.insertBeforeIndex` into account. * * @param parentTNode parent `TNode` * @param currentTNode current `TNode` (The node which we would like to insert into the DOM) * @param lView current `LView` */ export function getInsertInFrontOfRNodeWithNoI18n( parentTNode: TNode, currentTNode: TNode, lView: LView, ): RNode | null { if (parentTNode.type & (TNodeType.ElementContainer | TNodeType.Icu)) { return getNativeByTNode(parentTNode, lView); } return null; } /** * Tree shakable boundary for `getInsertInFrontOfRNodeWithI18n` function. * * This function will only be set if i18n code runs. */ let _getInsertInFrontOfRNodeWithI18n: ( parentTNode: TNode, currentTNode: TNode, lView: LView, ) => RNode | null = getInsertInFrontOfRNodeWithNoI18n; /** * Tree shakable boundary for `processI18nInsertBefore` function. * * This function will only be set if i18n code runs. */ let _processI18nInsertBefore: ( renderer: Renderer, childTNode: TNode, lView: LView, childRNode: RNode | RNode[], parentRElement: RElement | null, ) => void; export function setI18nHandling( getInsertInFrontOfRNodeWithI18n: ( parentTNode: TNode, currentTNode: TNode, lView: LView, ) => RNode | null, processI18nInsertBefore: ( renderer: Renderer, childTNode: TNode, lView: LView, childRNode: RNode | RNode[], parentRElement: RElement | null, ) => void, ) { _getInsertInFrontOfRNodeWithI18n = getInsertInFrontOfRNodeWithI18n; _processI18nInsertBefore = processI18nInsertBefore; } /** * Appends the `child` native node (or a collection of nodes) to the `parent`. * * @param tView The `TView' to be appended * @param lView The current LView * @param childRNode The native child (or children) that should be appended * @param childTNode The TNode of the child element */ export function appendChild( tView: TView, lView: LView, childRNode: RNode | RNode[], childTNode: TNode, ): void { const parentRNode = getParentRElement(tView, childTNode, lView); const renderer = lView[RENDERER]; const parentTNode: TNode = childTNode.parent || lView[T_HOST]!; const anchorNode = getInsertInFrontOfRNode(parentTNode, childTNode, lView); if (parentRNode != null) { if (Array.isArray(childRNode)) { for (let i = 0; i < childRNode.length; i++) { nativeAppendOrInsertBefore(renderer, parentRNode, childRNode[i], anchorNode, false); } } else { nativeAppendOrInsertBefore(renderer, parentRNode, childRNode, anchorNode, false); } } _processI18nInsertBefore !== undefined && _processI18nInsertBefore(renderer, childTNode, lView, childRNode, parentRNode); } /** * Returns the first native node for a given LView, starting from the provided TNode. * * Native nodes are returned in the order in which those appear in the native tree (DOM). */
{ "end_byte": 30325, "start_byte": 23239, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_30326_38266
export function getFirstNativeNode(lView: LView, tNode: TNode | null): RNode | null { if (tNode !== null) { ngDevMode && assertTNodeType( tNode, TNodeType.AnyRNode | TNodeType.AnyContainer | TNodeType.Icu | TNodeType.Projection | TNodeType.LetDeclaration, ); const tNodeType = tNode.type; if (tNodeType & TNodeType.AnyRNode) { return getNativeByTNode(tNode, lView); } else if (tNodeType & TNodeType.Container) { return getBeforeNodeForView(-1, lView[tNode.index]); } else if (tNodeType & TNodeType.ElementContainer) { const elIcuContainerChild = tNode.child; if (elIcuContainerChild !== null) { return getFirstNativeNode(lView, elIcuContainerChild); } else { const rNodeOrLContainer = lView[tNode.index]; if (isLContainer(rNodeOrLContainer)) { return getBeforeNodeForView(-1, rNodeOrLContainer); } else { return unwrapRNode(rNodeOrLContainer); } } } else if (tNodeType & TNodeType.LetDeclaration) { return getFirstNativeNode(lView, tNode.next); } else if (tNodeType & TNodeType.Icu) { let nextRNode = icuContainerIterate(tNode as TIcuContainerNode, lView); let rNode: RNode | null = nextRNode(); // If the ICU container has no nodes, than we use the ICU anchor as the node. return rNode || unwrapRNode(lView[tNode.index]); } else { const projectionNodes = getProjectionNodes(lView, tNode); if (projectionNodes !== null) { if (Array.isArray(projectionNodes)) { return projectionNodes[0]; } const parentView = getLViewParent(lView[DECLARATION_COMPONENT_VIEW]); ngDevMode && assertParentView(parentView); return getFirstNativeNode(parentView!, projectionNodes); } else { return getFirstNativeNode(lView, tNode.next); } } } return null; } export function getProjectionNodes(lView: LView, tNode: TNode | null): TNode | RNode[] | null { if (tNode !== null) { const componentView = lView[DECLARATION_COMPONENT_VIEW]; const componentHost = componentView[T_HOST] as TElementNode; const slotIdx = tNode.projection as number; ngDevMode && assertProjectionSlots(lView); return componentHost.projection![slotIdx]; } return null; } export function getBeforeNodeForView( viewIndexInContainer: number, lContainer: LContainer, ): RNode | null { const nextViewIndex = CONTAINER_HEADER_OFFSET + viewIndexInContainer + 1; if (nextViewIndex < lContainer.length) { const lView = lContainer[nextViewIndex] as LView; const firstTNodeOfView = lView[TVIEW].firstChild; if (firstTNodeOfView !== null) { return getFirstNativeNode(lView, firstTNodeOfView); } } return lContainer[NATIVE]; } /** * Removes a native node itself using a given renderer. To remove the node we are looking up its * parent from the native tree as not all platforms / browsers support the equivalent of * node.remove(). * * @param renderer A renderer to be used * @param rNode The native node that should be removed * @param isHostElement A flag indicating if a node to be removed is a host of a component. */ export function nativeRemoveNode(renderer: Renderer, rNode: RNode, isHostElement?: boolean): void { ngDevMode && ngDevMode.rendererRemoveNode++; renderer.removeChild(null, rNode, isHostElement); } /** * Clears the contents of a given RElement. * * @param rElement the native RElement to be cleared */ export function clearElementContents(rElement: RElement): void { rElement.textContent = ''; } /** * Performs the operation of `action` on the node. Typically this involves inserting or removing * nodes on the LView or projection boundary. */ function applyNodes( renderer: Renderer, action: WalkTNodeTreeAction, tNode: TNode | null, lView: LView, parentRElement: RElement | null, beforeNode: RNode | null, isProjection: boolean, ) { while (tNode != null) { ngDevMode && assertTNodeForLView(tNode, lView); // Let declarations don't have corresponding DOM nodes so we skip over them. if (tNode.type === TNodeType.LetDeclaration) { tNode = tNode.next; continue; } ngDevMode && assertTNodeType( tNode, TNodeType.AnyRNode | TNodeType.AnyContainer | TNodeType.Projection | TNodeType.Icu, ); const rawSlotValue = lView[tNode.index]; const tNodeType = tNode.type; if (isProjection) { if (action === WalkTNodeTreeAction.Create) { rawSlotValue && attachPatchData(unwrapRNode(rawSlotValue), lView); tNode.flags |= TNodeFlags.isProjected; } } if ((tNode.flags & TNodeFlags.isDetached) !== TNodeFlags.isDetached) { if (tNodeType & TNodeType.ElementContainer) { applyNodes(renderer, action, tNode.child, lView, parentRElement, beforeNode, false); applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode); } else if (tNodeType & TNodeType.Icu) { const nextRNode = icuContainerIterate(tNode as TIcuContainerNode, lView); let rNode: RNode | null; while ((rNode = nextRNode())) { applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode); } applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode); } else if (tNodeType & TNodeType.Projection) { applyProjectionRecursive( renderer, action, lView, tNode as TProjectionNode, parentRElement, beforeNode, ); } else { ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode | TNodeType.Container); applyToElementOrContainer(action, renderer, parentRElement, rawSlotValue, beforeNode); } } tNode = isProjection ? tNode.projectionNext : tNode.next; } } /** * `applyView` performs operation on the view as specified in `action` (insert, detach, destroy) * * Inserting a view without projection or containers at top level is simple. Just iterate over the * root nodes of the View, and for each node perform the `action`. * * Things get more complicated with containers and projections. That is because coming across: * - Container: implies that we have to insert/remove/destroy the views of that container as well * which in turn can have their own Containers at the View roots. * - Projection: implies that we have to insert/remove/destroy the nodes of the projection. The * complication is that the nodes we are projecting can themselves have Containers * or other Projections. * * As you can see this is a very recursive problem. Yes recursion is not most efficient but the * code is complicated enough that trying to implemented with recursion becomes unmaintainable. * * @param tView The `TView' which needs to be inserted, detached, destroyed * @param lView The LView which needs to be inserted, detached, destroyed. * @param renderer Renderer to use * @param action action to perform (insert, detach, destroy) * @param parentRElement parent DOM element for insertion (Removal does not need it). * @param beforeNode Before which node the insertions should happen. */ function applyView( tView: TView, lView: LView, renderer: Renderer, action: WalkTNodeTreeAction.Destroy, parentRElement: null, beforeNode: null, ): void; function applyView( tView: TView, lView: LView, renderer: Renderer, action: WalkTNodeTreeAction, parentRElement: RElement | null, beforeNode: RNode | null, ): void; function applyView( tView: TView, lView: LView, renderer: Renderer, action: WalkTNodeTreeAction, parentRElement: RElement | null, beforeNode: RNode | null, ): void { applyNodes(renderer, action, tView.firstChild, lView, parentRElement, beforeNode, false); }
{ "end_byte": 38266, "start_byte": 30326, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_38268_46291
/** * `applyProjection` performs operation on the projection. * * Inserting a projection requires us to locate the projected nodes from the parent component. The * complication is that those nodes themselves could be re-projected from their parent component. * * @param tView The `TView` of `LView` which needs to be inserted, detached, destroyed * @param lView The `LView` which needs to be inserted, detached, destroyed. * @param tProjectionNode node to project */ export function applyProjection(tView: TView, lView: LView, tProjectionNode: TProjectionNode) { const renderer = lView[RENDERER]; const parentRNode = getParentRElement(tView, tProjectionNode, lView); const parentTNode = tProjectionNode.parent || lView[T_HOST]!; let beforeNode = getInsertInFrontOfRNode(parentTNode, tProjectionNode, lView); applyProjectionRecursive( renderer, WalkTNodeTreeAction.Create, lView, tProjectionNode, parentRNode, beforeNode, ); } /** * `applyProjectionRecursive` performs operation on the projection specified by `action` (insert, * detach, destroy) * * Inserting a projection requires us to locate the projected nodes from the parent component. The * complication is that those nodes themselves could be re-projected from their parent component. * * @param renderer Render to use * @param action action to perform (insert, detach, destroy) * @param lView The LView which needs to be inserted, detached, destroyed. * @param tProjectionNode node to project * @param parentRElement parent DOM element for insertion/removal. * @param beforeNode Before which node the insertions should happen. */ function applyProjectionRecursive( renderer: Renderer, action: WalkTNodeTreeAction, lView: LView, tProjectionNode: TProjectionNode, parentRElement: RElement | null, beforeNode: RNode | null, ) { const componentLView = lView[DECLARATION_COMPONENT_VIEW]; const componentNode = componentLView[T_HOST] as TElementNode; ngDevMode && assertEqual(typeof tProjectionNode.projection, 'number', 'expecting projection index'); const nodeToProjectOrRNodes = componentNode.projection![tProjectionNode.projection]!; if (Array.isArray(nodeToProjectOrRNodes)) { // This should not exist, it is a bit of a hack. When we bootstrap a top level node and we // need to support passing projectable nodes, so we cheat and put them in the TNode // of the Host TView. (Yes we put instance info at the T Level). We can get away with it // because we know that TView is not shared and therefore it will not be a problem. // This should be refactored and cleaned up. for (let i = 0; i < nodeToProjectOrRNodes.length; i++) { const rNode = nodeToProjectOrRNodes[i]; applyToElementOrContainer(action, renderer, parentRElement, rNode, beforeNode); } } else { let nodeToProject: TNode | null = nodeToProjectOrRNodes; const projectedComponentLView = componentLView[PARENT] as LView; // If a parent <ng-content> is located within a skip hydration block, // annotate an actual node that is being projected with the same flag too. if (hasInSkipHydrationBlockFlag(tProjectionNode)) { nodeToProject.flags |= TNodeFlags.inSkipHydrationBlock; } applyNodes( renderer, action, nodeToProject, projectedComponentLView, parentRElement, beforeNode, true, ); } } /** * `applyContainer` performs an operation on the container and its views as specified by * `action` (insert, detach, destroy) * * Inserting a Container is complicated by the fact that the container may have Views which * themselves have containers or projections. * * @param renderer Renderer to use * @param action action to perform (insert, detach, destroy) * @param lContainer The LContainer which needs to be inserted, detached, destroyed. * @param parentRElement parent DOM element for insertion/removal. * @param beforeNode Before which node the insertions should happen. */ function applyContainer( renderer: Renderer, action: WalkTNodeTreeAction, lContainer: LContainer, parentRElement: RElement | null, beforeNode: RNode | null | undefined, ) { ngDevMode && assertLContainer(lContainer); const anchor = lContainer[NATIVE]; // LContainer has its own before node. const native = unwrapRNode(lContainer); // An LContainer can be created dynamically on any node by injecting ViewContainerRef. // Asking for a ViewContainerRef on an element will result in a creation of a separate anchor // node (comment in the DOM) that will be different from the LContainer's host node. In this // particular case we need to execute action on 2 nodes: // - container's host node (this is done in the executeActionOnElementOrContainer) // - container's host node (this is done here) if (anchor !== native) { // This is very strange to me (Misko). I would expect that the native is same as anchor. I // don't see a reason why they should be different, but they are. // // If they are we need to process the second anchor as well. applyToElementOrContainer(action, renderer, parentRElement, anchor, beforeNode); } for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) { const lView = lContainer[i] as LView; applyView(lView[TVIEW], lView, renderer, action, parentRElement, anchor); } } /** * Writes class/style to element. * * @param renderer Renderer to use. * @param isClassBased `true` if it should be written to `class` (`false` to write to `style`) * @param rNode The Node to write to. * @param prop Property to write to. This would be the class/style name. * @param value Value to write. If `null`/`undefined`/`false` this is considered a remove (set/add * otherwise). */ export function applyStyling( renderer: Renderer, isClassBased: boolean, rNode: RElement, prop: string, value: any, ) { if (isClassBased) { // We actually want JS true/false here because any truthy value should add the class if (!value) { ngDevMode && ngDevMode.rendererRemoveClass++; renderer.removeClass(rNode, prop); } else { ngDevMode && ngDevMode.rendererAddClass++; renderer.addClass(rNode, prop); } } else { let flags = prop.indexOf('-') === -1 ? undefined : (RendererStyleFlags2.DashCase as number); if (value == null /** || value === undefined */) { ngDevMode && ngDevMode.rendererRemoveStyle++; renderer.removeStyle(rNode, prop, flags); } else { // A value is important if it ends with `!important`. The style // parser strips any semicolons at the end of the value. const isImportant = typeof value === 'string' ? value.endsWith('!important') : false; if (isImportant) { // !important has to be stripped from the value for it to be valid. value = value.slice(0, -10); flags! |= RendererStyleFlags2.Important; } ngDevMode && ngDevMode.rendererSetStyle++; renderer.setStyle(rNode, prop, value, flags); } } } /** * Write `cssText` to `RElement`. * * This function does direct write without any reconciliation. Used for writing initial values, so * that static styling values do not pull in the style parser. * * @param renderer Renderer to use * @param element The element which needs to be updated. * @param newValue The new class list to write. */ export function writeDirectStyle(renderer: Renderer, element: RElement, newValue: string) { ngDevMode && assertString(newValue, "'newValue' should be a string"); renderer.setAttribute(element, 'style', newValue); ngDevMode && ngDevMode.rendererSetStyle++; } /** * Write `className` to `RElement`. * * This function does direct write without any reconciliation. Used for writing initial values, so * that static styling values do not pull in the style parser. * * @param renderer Renderer to use * @param element The element which needs to be updated. * @param newValue The new class list to write. */
{ "end_byte": 46291, "start_byte": 38268, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/node_manipulation.ts_46292_47192
export function writeDirectClass(renderer: Renderer, element: RElement, newValue: string) { ngDevMode && assertString(newValue, "'newValue' should be a string"); if (newValue === '') { // There are tests in `google3` which expect `element.getAttribute('class')` to be `null`. renderer.removeAttribute(element, 'class'); } else { renderer.setAttribute(element, 'class', newValue); } ngDevMode && ngDevMode.rendererSetClassName++; } /** Sets up the static DOM attributes on an `RNode`. */ export function setupStaticAttributes(renderer: Renderer, element: RElement, tNode: TNode) { const {mergedAttrs, classes, styles} = tNode; if (mergedAttrs !== null) { setUpAttributes(renderer, element, mergedAttrs); } if (classes !== null) { writeDirectClass(renderer, element, classes); } if (styles !== null) { writeDirectStyle(renderer, element, styles); } }
{ "end_byte": 47192, "start_byte": 46292, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/node_manipulation.ts" }
angular/packages/core/src/render3/hmr.ts_0_6300
/*! * @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 {assertDefined} from '../util/assert'; import {assertLView} from './assert'; import {ɵɵdefineComponent, ɵɵdefineDirective, ɵɵdefineNgModule, ɵɵdefinePipe} from './definition'; import {getComponentDef} from './def_getters'; import {assertComponentDef} from './errors'; import {refreshView} from './instructions/change_detection'; import {renderView} from './instructions/render'; import { createLView, getInitialLViewFlagsFromDef, getOrCreateComponentTView, } from './instructions/shared'; import {CONTAINER_HEADER_OFFSET} from './interfaces/container'; import {ComponentDef} from './interfaces/definition'; import {getTrackedLViews} from './interfaces/lview_tracking'; import {isTNodeShape, TElementNode, TNodeFlags, TNodeType} from './interfaces/node'; import {isLContainer, isLView} from './interfaces/type_checks'; import { CHILD_HEAD, CHILD_TAIL, CONTEXT, ENVIRONMENT, FLAGS, HEADER_OFFSET, HOST, LView, LViewFlags, NEXT, PARENT, T_HOST, TVIEW, } from './interfaces/view'; import {assertTNodeType} from './node_assert'; import {destroyLView, removeViewFromDOM} from './node_manipulation'; import * as iframe_attrs_validation from '../sanitization/iframe_attrs_validation'; import * as sanitization from '../sanitization/sanitization'; import * as r3 from './instructions/all'; import { ɵɵdefineInjectable, ɵɵdefineInjector, ɵɵinject, ɵɵinvalidFactoryDep, forwardRef, resolveForwardRef, } from '../di'; import {registerNgModuleType} from '../linker/ng_module_registration'; import {ɵɵgetInheritedFactory} from './di'; import {ɵɵgetComponentDepsFactory} from './local_compilation'; import {ɵɵpipeBind1, ɵɵpipeBind2, ɵɵpipeBind3, ɵɵpipeBind4, ɵɵpipeBindV, ɵɵpipe} from './pipe'; import { ɵɵpureFunction0, ɵɵpureFunction1, ɵɵpureFunction2, ɵɵpureFunction3, ɵɵpureFunction4, ɵɵpureFunction5, ɵɵpureFunction6, ɵɵpureFunction7, ɵɵpureFunction8, ɵɵpureFunctionV, } from './pure_function'; import {ɵɵsetComponentScope, ɵɵsetNgModuleScope} from './scope'; import {ɵɵresetView, ɵɵenableBindings, ɵɵdisableBindings, ɵɵrestoreView} from './state'; import {ɵɵtemplateRefExtractor} from './view_engine_compatibility_prebound'; import {ɵɵHostDirectivesFeature} from './features/host_directives_feature'; import {ɵɵNgOnChangesFeature} from './features/ng_onchanges_feature'; import {ɵɵProvidersFeature} from './features/providers_feature'; import {ɵɵCopyDefinitionFeature} from './features/copy_definition_feature'; import {ɵɵInheritDefinitionFeature} from './features/inherit_definition_feature'; import {ɵɵInputTransformsFeature} from './features/input_transforms_feature'; import {ɵɵExternalStylesFeature} from './features/external_styles_feature'; import {ɵɵresolveBody, ɵɵresolveDocument, ɵɵresolveWindow} from './util/misc_utils'; import {ɵsetClassDebugInfo} from './debug/set_debug_info'; /** Cached environment for all HMR calls. */ let hmrEnvironment: Record<string, unknown> | null = null; /** * Replaces the metadata of a component type and re-renders all live instances of the component. * @param type Class whose metadata will be replaced. * @param applyMetadata Callback that will apply a new set of metadata on the `type` when invoked. * @param locals Local symbols from the source location that have to be exposed to the callback. * @codeGenApi */ export function ɵɵreplaceMetadata( type: Type<unknown>, applyMetadata: (...args: [Type<unknown>, Record<string, unknown>, ...unknown[]]) => void, locals: unknown[], ) { ngDevMode && assertComponentDef(type); const oldDef = getComponentDef(type)!; if (hmrEnvironment === null) { hmrEnvironment = getHmrEnv(); } // The reason `applyMetadata` is a callback that is invoked (almost) immediately is because // the compiler usually produces more code than just the component definition, e.g. there // can be functions for embedded views, the variables for the constant pool and `setClassMetadata` // calls. The callback allows us to keep them isolate from the rest of the app and to invoke // them at the right time. applyMetadata.apply(null, [type, hmrEnvironment, ...locals]); // If a `tView` hasn't been created yet, it means that this component hasn't been instantianted // before. In this case there's nothing left for us to do aside from patching it in. if (oldDef.tView) { const trackedViews = getTrackedLViews().values(); for (const root of trackedViews) { // Note: we have the additional check, because `IsRoot` can also indicate // a component created through something like `createComponent`. if (root[FLAGS] & LViewFlags.IsRoot && root[PARENT] === null) { recreateMatchingLViews(oldDef, root); } } } } /** * Finds all LViews matching a specific component definition and recreates them. * @param def Component definition to search for. * @param rootLView View from which to start the search. */ function recreateMatchingLViews(def: ComponentDef<unknown>, rootLView: LView): void { ngDevMode && assertDefined( def.tView, 'Expected a component definition that has been instantiated at least once', ); const tView = rootLView[TVIEW]; // Use `tView` to match the LView since `instanceof` can // produce false positives when using inheritance. if (tView === def.tView) { ngDevMode && assertComponentDef(def.type); recreateLView(getComponentDef(def.type)!, rootLView); return; } for (let i = HEADER_OFFSET; i < tView.bindingStartIndex; i++) { const current = rootLView[i]; if (isLContainer(current)) { for (let i = CONTAINER_HEADER_OFFSET; i < current.length; i++) { recreateMatchingLViews(def, current[i]); } } else if (isLView(current)) { recreateMatchingLViews(def, current); } } } /** * Recreates an LView in-place from a new component definition. * @param def Definition from which to recreate the view. * @param lView View to be recreated. */ function recreateLView(def: ComponentDef<unknown>, lView: LView<unknown>): void { cons
{ "end_byte": 6300, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hmr.ts" }
angular/packages/core/src/render3/hmr.ts_6301_10666
instance = lView[CONTEXT]; const host = lView[HOST]!; // In theory the parent can also be an LContainer, but it appears like that's // only the case for embedded views which we won't be replacing here. const parentLView = lView[PARENT] as LView; ngDevMode && assertLView(parentLView); const tNode = lView[T_HOST] as TElementNode; ngDevMode && assertTNodeType(tNode, TNodeType.Element); // Recreate the TView since the template might've changed. const newTView = getOrCreateComponentTView(def); // Create a new LView from the new TView, but reusing the existing TNode and DOM node. const newLView = createLView( parentLView, newTView, instance, getInitialLViewFlagsFromDef(def), host, tNode, null, lView[ENVIRONMENT].rendererFactory.createRenderer(host, def), null, null, null, ); // Detach the LView from its current place in the tree so we don't // start traversing any siblings and modifying their structure. replaceLViewInTree(parentLView, lView, newLView, tNode.index); // Destroy the detached LView. destroyLView(lView[TVIEW], lView); // Remove the nodes associated with the destroyed LView. This removes the // descendants, but not the host which we want to stay in place. removeViewFromDOM(lView[TVIEW], lView); // Reset the content projection state of the TNode before the first render. // Note that this has to happen after the LView has been destroyed or we // risk some projected nodes not being removed correctly. resetProjectionState(tNode); // Creation pass for the new view. renderView(newTView, newLView, instance); // Update pass for the new view. refreshView(newTView, newLView, newTView.template, instance); } /** * Replaces one LView in the tree with another one. * @param parentLView Parent of the LView being replaced. * @param oldLView LView being replaced. * @param newLView Replacement LView to be inserted. * @param index Index at which the LView should be inserted. */ function replaceLViewInTree( parentLView: LView, oldLView: LView, newLView: LView, index: number, ): void { // Update the sibling whose `NEXT` pointer refers to the old view. for (let i = HEADER_OFFSET; i < parentLView[TVIEW].bindingStartIndex; i++) { const current = parentLView[i]; if ((isLView(current) || isLContainer(current)) && current[NEXT] === oldLView) { current[NEXT] = newLView; break; } } // Set the new view as the head, if the old view was first. if (parentLView[CHILD_HEAD] === oldLView) { parentLView[CHILD_HEAD] = newLView; } // Set the new view as the tail, if the old view was last. if (parentLView[CHILD_TAIL] === oldLView) { parentLView[CHILD_TAIL] = newLView; } // Update the `NEXT` pointer to the same as the old view. newLView[NEXT] = oldLView[NEXT]; // Clear out the `NEXT` of the old view. oldLView[NEXT] = null; // Insert the new LView at the correct index. parentLView[index] = newLView; } /** * Child nodes mutate the `projection` state of their parent node as they're being projected. * This function resets the `project` back to its initial state. * @param tNode */ function resetProjectionState(tNode: TElementNode): void { // The `projection` is mutated by child nodes as they're being projected. We need to // reset it to the initial state so projection works after the template is swapped out. if (tNode.projection !== null) { for (const current of tNode.projection) { if (isTNodeShape(current)) { // Reset `projectionNext` since it can affect the traversal order during projection. current.projectionNext = null; current.flags &= ~TNodeFlags.isProjected; } } tNode.projection = null; } } /** * The HMR replacement function needs access to all of `core`. This is similar to the * `angularCoreEnv`, but without `replaceMetadata` to avoid circular dependencies. Furthermore, * we can't something like a `nonHmrEnv` that is then combined with `replaceMetadata` to form the * full environment, because it seems to break tree shaking internally. * * TODO(crisbeto): this is a temporary solution, we should be able to pass this in directly. */ function getHmrEnv(): Record<string, unknown> { return { 'ɵɵattribute': r3.ɵɵattribute, 'ɵɵattributeInterpolate1': r3.ɵɵattr
{ "end_byte": 10666, "start_byte": 6301, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hmr.ts" }
angular/packages/core/src/render3/hmr.ts_10667_16242
buteInterpolate1, 'ɵɵattributeInterpolate2': r3.ɵɵattributeInterpolate2, 'ɵɵattributeInterpolate3': r3.ɵɵattributeInterpolate3, 'ɵɵattributeInterpolate4': r3.ɵɵattributeInterpolate4, 'ɵɵattributeInterpolate5': r3.ɵɵattributeInterpolate5, 'ɵɵattributeInterpolate6': r3.ɵɵattributeInterpolate6, 'ɵɵattributeInterpolate7': r3.ɵɵattributeInterpolate7, 'ɵɵattributeInterpolate8': r3.ɵɵattributeInterpolate8, 'ɵɵattributeInterpolateV': r3.ɵɵattributeInterpolateV, 'ɵɵdefineComponent': ɵɵdefineComponent, 'ɵɵdefineDirective': ɵɵdefineDirective, 'ɵɵdefineInjectable': ɵɵdefineInjectable, 'ɵɵdefineInjector': ɵɵdefineInjector, 'ɵɵdefineNgModule': ɵɵdefineNgModule, 'ɵɵdefinePipe': ɵɵdefinePipe, 'ɵɵdirectiveInject': r3.ɵɵdirectiveInject, 'ɵɵgetInheritedFactory': ɵɵgetInheritedFactory, 'ɵɵinject': ɵɵinject, 'ɵɵinjectAttribute': r3.ɵɵinjectAttribute, 'ɵɵinvalidFactory': r3.ɵɵinvalidFactory, 'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep, 'ɵɵtemplateRefExtractor': ɵɵtemplateRefExtractor, 'ɵɵresetView': ɵɵresetView, 'ɵɵHostDirectivesFeature': ɵɵHostDirectivesFeature, 'ɵɵNgOnChangesFeature': ɵɵNgOnChangesFeature, 'ɵɵProvidersFeature': ɵɵProvidersFeature, 'ɵɵCopyDefinitionFeature': ɵɵCopyDefinitionFeature, 'ɵɵInheritDefinitionFeature': ɵɵInheritDefinitionFeature, 'ɵɵInputTransformsFeature': ɵɵInputTransformsFeature, 'ɵɵExternalStylesFeature': ɵɵExternalStylesFeature, 'ɵɵnextContext': r3.ɵɵnextContext, 'ɵɵnamespaceHTML': r3.ɵɵnamespaceHTML, 'ɵɵnamespaceMathML': r3.ɵɵnamespaceMathML, 'ɵɵnamespaceSVG': r3.ɵɵnamespaceSVG, 'ɵɵenableBindings': ɵɵenableBindings, 'ɵɵdisableBindings': ɵɵdisableBindings, 'ɵɵelementStart': r3.ɵɵelementStart, 'ɵɵelementEnd': r3.ɵɵelementEnd, 'ɵɵelement': r3.ɵɵelement, 'ɵɵelementContainerStart': r3.ɵɵelementContainerStart, 'ɵɵelementContainerEnd': r3.ɵɵelementContainerEnd, 'ɵɵelementContainer': r3.ɵɵelementContainer, 'ɵɵpureFunction0': ɵɵpureFunction0, 'ɵɵpureFunction1': ɵɵpureFunction1, 'ɵɵpureFunction2': ɵɵpureFunction2, 'ɵɵpureFunction3': ɵɵpureFunction3, 'ɵɵpureFunction4': ɵɵpureFunction4, 'ɵɵpureFunction5': ɵɵpureFunction5, 'ɵɵpureFunction6': ɵɵpureFunction6, 'ɵɵpureFunction7': ɵɵpureFunction7, 'ɵɵpureFunction8': ɵɵpureFunction8, 'ɵɵpureFunctionV': ɵɵpureFunctionV, 'ɵɵgetCurrentView': r3.ɵɵgetCurrentView, 'ɵɵrestoreView': ɵɵrestoreView, 'ɵɵlistener': r3.ɵɵlistener, 'ɵɵprojection': r3.ɵɵprojection, 'ɵɵsyntheticHostProperty': r3.ɵɵsyntheticHostProperty, 'ɵɵsyntheticHostListener': r3.ɵɵsyntheticHostListener, 'ɵɵpipeBind1': ɵɵpipeBind1, 'ɵɵpipeBind2': ɵɵpipeBind2, 'ɵɵpipeBind3': ɵɵpipeBind3, 'ɵɵpipeBind4': ɵɵpipeBind4, 'ɵɵpipeBindV': ɵɵpipeBindV, 'ɵɵprojectionDef': r3.ɵɵprojectionDef, 'ɵɵhostProperty': r3.ɵɵhostProperty, 'ɵɵproperty': r3.ɵɵproperty, 'ɵɵpropertyInterpolate': r3.ɵɵpropertyInterpolate, 'ɵɵpropertyInterpolate1': r3.ɵɵpropertyInterpolate1, 'ɵɵpropertyInterpolate2': r3.ɵɵpropertyInterpolate2, 'ɵɵpropertyInterpolate3': r3.ɵɵpropertyInterpolate3, 'ɵɵpropertyInterpolate4': r3.ɵɵpropertyInterpolate4, 'ɵɵpropertyInterpolate5': r3.ɵɵpropertyInterpolate5, 'ɵɵpropertyInterpolate6': r3.ɵɵpropertyInterpolate6, 'ɵɵpropertyInterpolate7': r3.ɵɵpropertyInterpolate7, 'ɵɵpropertyInterpolate8': r3.ɵɵpropertyInterpolate8, 'ɵɵpropertyInterpolateV': r3.ɵɵpropertyInterpolateV, 'ɵɵpipe': ɵɵpipe, 'ɵɵqueryRefresh': r3.ɵɵqueryRefresh, 'ɵɵqueryAdvance': r3.ɵɵqueryAdvance, 'ɵɵviewQuery': r3.ɵɵviewQuery, 'ɵɵviewQuerySignal': r3.ɵɵviewQuerySignal, 'ɵɵloadQuery': r3.ɵɵloadQuery, 'ɵɵcontentQuery': r3.ɵɵcontentQuery, 'ɵɵcontentQuerySignal': r3.ɵɵcontentQuerySignal, 'ɵɵreference': r3.ɵɵreference, 'ɵɵclassMap': r3.ɵɵclassMap, 'ɵɵclassMapInterpolate1': r3.ɵɵclassMapInterpolate1, 'ɵɵclassMapInterpolate2': r3.ɵɵclassMapInterpolate2, 'ɵɵclassMapInterpolate3': r3.ɵɵclassMapInterpolate3, 'ɵɵclassMapInterpolate4': r3.ɵɵclassMapInterpolate4, 'ɵɵclassMapInterpolate5': r3.ɵɵclassMapInterpolate5, 'ɵɵclassMapInterpolate6': r3.ɵɵclassMapInterpolate6, 'ɵɵclassMapInterpolate7': r3.ɵɵclassMapInterpolate7, 'ɵɵclassMapInterpolate8': r3.ɵɵclassMapInterpolate8, 'ɵɵclassMapInterpolateV': r3.ɵɵclassMapInterpolateV, 'ɵɵstyleMap': r3.ɵɵstyleMap, 'ɵɵstyleMapInterpolate1': r3.ɵɵstyleMapInterpolate1, 'ɵɵstyleMapInterpolate2': r3.ɵɵstyleMapInterpolate2, 'ɵɵstyleMapInterpolate3': r3.ɵɵstyleMapInterpolate3, 'ɵɵstyleMapInterpolate4': r3.ɵɵstyleMapInterpolate4, 'ɵɵstyleMapInterpolate5': r3.ɵɵstyleMapInterpolate5, 'ɵɵstyleMapInterpolate6': r3.ɵɵstyleMapInterpolate6, 'ɵɵstyleMapInterpolate7': r3.ɵɵstyleMapInterpolate7, 'ɵɵstyleMapInterpolate8': r3.ɵɵstyleMapInterpolate8, 'ɵɵstyleMapInterpolateV': r3.ɵɵstyleMapInterpolateV, 'ɵɵstyleProp': r3.ɵɵstyleProp, 'ɵɵstylePropInterpolate1': r3.ɵɵstylePropInterpolate1, 'ɵɵstylePropInterpolate2': r3.ɵɵstylePropInterpolate2, 'ɵɵstylePropInterpolate3': r3.ɵɵstylePropInterpolate3, 'ɵɵstylePropInterpolate4': r3.ɵɵstylePropInterpolate4, 'ɵɵstylePropInterpolate5': r3.ɵɵstylePropInterpolate5, 'ɵɵstylePropInterpolate6': r3.ɵɵstylePropInterpolate6, 'ɵɵstylePropInterpolate7': r3.ɵɵstylePropInterpolate7, 'ɵɵstylePropInterpolate8': r3.ɵɵstylePropInterpolate8, 'ɵɵstylePropInterpolateV': r3.ɵɵstylePropInterpolateV, 'ɵɵclassProp': r3.ɵɵclassProp, 'ɵɵadvanc
{ "end_byte": 16242, "start_byte": 10667, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hmr.ts" }
angular/packages/core/src/render3/hmr.ts_16247_20737
3.ɵɵadvance, 'ɵɵtemplate': r3.ɵɵtemplate, 'ɵɵconditional': r3.ɵɵconditional, 'ɵɵdefer': r3.ɵɵdefer, 'ɵɵdeferWhen': r3.ɵɵdeferWhen, 'ɵɵdeferOnIdle': r3.ɵɵdeferOnIdle, 'ɵɵdeferOnImmediate': r3.ɵɵdeferOnImmediate, 'ɵɵdeferOnTimer': r3.ɵɵdeferOnTimer, 'ɵɵdeferOnHover': r3.ɵɵdeferOnHover, 'ɵɵdeferOnInteraction': r3.ɵɵdeferOnInteraction, 'ɵɵdeferOnViewport': r3.ɵɵdeferOnViewport, 'ɵɵdeferPrefetchWhen': r3.ɵɵdeferPrefetchWhen, 'ɵɵdeferPrefetchOnIdle': r3.ɵɵdeferPrefetchOnIdle, 'ɵɵdeferPrefetchOnImmediate': r3.ɵɵdeferPrefetchOnImmediate, 'ɵɵdeferPrefetchOnTimer': r3.ɵɵdeferPrefetchOnTimer, 'ɵɵdeferPrefetchOnHover': r3.ɵɵdeferPrefetchOnHover, 'ɵɵdeferPrefetchOnInteraction': r3.ɵɵdeferPrefetchOnInteraction, 'ɵɵdeferPrefetchOnViewport': r3.ɵɵdeferPrefetchOnViewport, 'ɵɵdeferHydrateWhen': r3.ɵɵdeferHydrateWhen, 'ɵɵdeferHydrateNever': r3.ɵɵdeferHydrateNever, 'ɵɵdeferHydrateOnIdle': r3.ɵɵdeferHydrateOnIdle, 'ɵɵdeferHydrateOnImmediate': r3.ɵɵdeferHydrateOnImmediate, 'ɵɵdeferHydrateOnTimer': r3.ɵɵdeferHydrateOnTimer, 'ɵɵdeferHydrateOnHover': r3.ɵɵdeferHydrateOnHover, 'ɵɵdeferHydrateOnInteraction': r3.ɵɵdeferHydrateOnInteraction, 'ɵɵdeferHydrateOnViewport': r3.ɵɵdeferHydrateOnViewport, 'ɵɵdeferEnableTimerScheduling': r3.ɵɵdeferEnableTimerScheduling, 'ɵɵrepeater': r3.ɵɵrepeater, 'ɵɵrepeaterCreate': r3.ɵɵrepeaterCreate, 'ɵɵrepeaterTrackByIndex': r3.ɵɵrepeaterTrackByIndex, 'ɵɵrepeaterTrackByIdentity': r3.ɵɵrepeaterTrackByIdentity, 'ɵɵcomponentInstance': r3.ɵɵcomponentInstance, 'ɵɵtext': r3.ɵɵtext, 'ɵɵtextInterpolate': r3.ɵɵtextInterpolate, 'ɵɵtextInterpolate1': r3.ɵɵtextInterpolate1, 'ɵɵtextInterpolate2': r3.ɵɵtextInterpolate2, 'ɵɵtextInterpolate3': r3.ɵɵtextInterpolate3, 'ɵɵtextInterpolate4': r3.ɵɵtextInterpolate4, 'ɵɵtextInterpolate5': r3.ɵɵtextInterpolate5, 'ɵɵtextInterpolate6': r3.ɵɵtextInterpolate6, 'ɵɵtextInterpolate7': r3.ɵɵtextInterpolate7, 'ɵɵtextInterpolate8': r3.ɵɵtextInterpolate8, 'ɵɵtextInterpolateV': r3.ɵɵtextInterpolateV, 'ɵɵi18n': r3.ɵɵi18n, 'ɵɵi18nAttributes': r3.ɵɵi18nAttributes, 'ɵɵi18nExp': r3.ɵɵi18nExp, 'ɵɵi18nStart': r3.ɵɵi18nStart, 'ɵɵi18nEnd': r3.ɵɵi18nEnd, 'ɵɵi18nApply': r3.ɵɵi18nApply, 'ɵɵi18nPostprocess': r3.ɵɵi18nPostprocess, 'ɵɵresolveWindow': ɵɵresolveWindow, 'ɵɵresolveDocument': ɵɵresolveDocument, 'ɵɵresolveBody': ɵɵresolveBody, 'ɵɵsetComponentScope': ɵɵsetComponentScope, 'ɵɵsetNgModuleScope': ɵɵsetNgModuleScope, 'ɵɵregisterNgModuleType': registerNgModuleType, 'ɵɵgetComponentDepsFactory': ɵɵgetComponentDepsFactory, 'ɵsetClassDebugInfo': ɵsetClassDebugInfo, 'ɵɵdeclareLet': r3.ɵɵdeclareLet, 'ɵɵstoreLet': r3.ɵɵstoreLet, 'ɵɵreadContextLet': r3.ɵɵreadContextLet, 'ɵɵsanitizeHtml': sanitization.ɵɵsanitizeHtml, 'ɵɵsanitizeStyle': sanitization.ɵɵsanitizeStyle, 'ɵɵsanitizeResourceUrl': sanitization.ɵɵsanitizeResourceUrl, 'ɵɵsanitizeScript': sanitization.ɵɵsanitizeScript, 'ɵɵsanitizeUrl': sanitization.ɵɵsanitizeUrl, 'ɵɵsanitizeUrlOrResourceUrl': sanitization.ɵɵsanitizeUrlOrResourceUrl, 'ɵɵtrustConstantHtml': sanitization.ɵɵtrustConstantHtml, 'ɵɵtrustConstantResourceUrl': sanitization.ɵɵtrustConstantResourceUrl, 'ɵɵvalidateIframeAttribute': iframe_attrs_validation.ɵɵvalidateIframeAttribute, 'forwardRef': forwardRef, 'resolveForwardRef': resolveForwardRef, 'ɵɵtwoWayProperty': r3.ɵɵtwoWayProperty, 'ɵɵtwoWayBindingSet': r3.ɵɵtwoWayBindingSet, 'ɵɵtwoWayListener': r3.ɵɵtwoWayListener, }; }
{ "end_byte": 20737, "start_byte": 16247, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/hmr.ts" }
angular/packages/core/src/render3/instructions/listener.ts_0_5955
/** * @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 {NotificationSource} from '../../change_detection/scheduling/zoneless_scheduling'; import {assertIndexInRange} from '../../util/assert'; import {NodeOutputBindings, TNode, TNodeType} from '../interfaces/node'; import {GlobalTargetResolver, Renderer} from '../interfaces/renderer'; import {RElement} from '../interfaces/renderer_dom'; import {isDirectiveHost} from '../interfaces/type_checks'; import {CLEANUP, CONTEXT, LView, RENDERER, TView} from '../interfaces/view'; import {assertTNodeType} from '../node_assert'; import {profiler} from '../profiler'; import {ProfilerEvent} from '../profiler_types'; import {getCurrentDirectiveDef, getCurrentTNode, getLView, getTView} from '../state'; import {getComponentLViewByIndex, getNativeByTNode, unwrapRNode} from '../util/view_utils'; import {markViewDirty} from './mark_view_dirty'; import { getOrCreateLViewCleanup, getOrCreateTViewCleanup, handleError, loadComponentRenderer, } from './shared'; /** * Contains a reference to a function that disables event replay feature * for server-side rendered applications. This function is overridden with * an actual implementation when the event replay feature is enabled via * `withEventReplay()` call. */ let stashEventListener = (el: RElement, eventName: string, listenerFn: (e?: any) => any) => {}; export function setStashFn(fn: typeof stashEventListener) { stashEventListener = fn; } /** * Adds an event listener to the current node. * * If an output exists on one of the node's directives, it also subscribes to the output * and saves the subscription for later cleanup. * * @param eventName Name of the event * @param listenerFn The function to be called when event emits * @param useCapture Whether or not to use capture in event listener - this argument is a reminder * from the Renderer3 infrastructure and should be removed from the instruction arguments * @param eventTargetResolver Function that returns global target information in case this listener * should be attached to a global object like window, document or body * * @codeGenApi */ export function ɵɵlistener( eventName: string, listenerFn: (e?: any) => any, useCapture?: boolean, eventTargetResolver?: GlobalTargetResolver, ): typeof ɵɵlistener { const lView = getLView<{} | null>(); const tView = getTView(); const tNode = getCurrentTNode()!; listenerInternal( tView, lView, lView[RENDERER], tNode, eventName, listenerFn, eventTargetResolver, ); return ɵɵlistener; } /** * Registers a synthetic host listener (e.g. `(@foo.start)`) on a component or directive. * * This instruction is for compatibility purposes and is designed to ensure that a * synthetic host listener (e.g. `@HostListener('@foo.start')`) properly gets rendered * in the component's renderer. Normally all host listeners are evaluated with the * parent component's renderer, but, in the case of animation @triggers, they need * to be evaluated with the sub component's renderer (because that's where the * animation triggers are defined). * * Do not use this instruction as a replacement for `listener`. This instruction * only exists to ensure compatibility with the ViewEngine's host binding behavior. * * @param eventName Name of the event * @param listenerFn The function to be called when event emits * @param useCapture Whether or not to use capture in event listener * @param eventTargetResolver Function that returns global target information in case this listener * should be attached to a global object like window, document or body * * @codeGenApi */ export function ɵɵsyntheticHostListener( eventName: string, listenerFn: (e?: any) => any, ): typeof ɵɵsyntheticHostListener { const tNode = getCurrentTNode()!; const lView = getLView<{} | null>(); const tView = getTView(); const currentDef = getCurrentDirectiveDef(tView.data); const renderer = loadComponentRenderer(currentDef, tNode, lView); listenerInternal(tView, lView, renderer, tNode, eventName, listenerFn); return ɵɵsyntheticHostListener; } /** * A utility function that checks if a given element has already an event handler registered for an * event with a specified name. The TView.cleanup data structure is used to find out which events * are registered for a given element. */ function findExistingListener( tView: TView, lView: LView, eventName: string, tNodeIdx: number, ): ((e?: any) => any) | null { const tCleanup = tView.cleanup; if (tCleanup != null) { for (let i = 0; i < tCleanup.length - 1; i += 2) { const cleanupEventName = tCleanup[i]; if (cleanupEventName === eventName && tCleanup[i + 1] === tNodeIdx) { // We have found a matching event name on the same node but it might not have been // registered yet, so we must explicitly verify entries in the LView cleanup data // structures. const lCleanup = lView[CLEANUP]!; const listenerIdxInLCleanup = tCleanup[i + 2]; return lCleanup.length > listenerIdxInLCleanup ? lCleanup[listenerIdxInLCleanup] : null; } // TView.cleanup can have a mix of 4-elements entries (for event handler cleanups) or // 2-element entries (for directive and queries destroy hooks). As such we can encounter // blocks of 4 or 2 items in the tView.cleanup and this is why we iterate over 2 elements // first and jump another 2 elements if we detect listeners cleanup (4 elements). Also check // documentation of TView.cleanup for more details of this data structure layout. if (typeof cleanupEventName === 'string') { i += 2; } } } return null; } export fun
{ "end_byte": 5955, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/listener.ts" }
angular/packages/core/src/render3/instructions/listener.ts_5957_14481
ion listenerInternal( tView: TView, lView: LView<{} | null>, renderer: Renderer, tNode: TNode, eventName: string, listenerFn: (e?: any) => any, eventTargetResolver?: GlobalTargetResolver, ): void { const isTNodeDirectiveHost = isDirectiveHost(tNode); const firstCreatePass = tView.firstCreatePass; const tCleanup: false | any[] = firstCreatePass && getOrCreateTViewCleanup(tView); const context = lView[CONTEXT]; // When the ɵɵlistener instruction was generated and is executed we know that there is either a // native listener or a directive output on this element. As such we we know that we will have to // register a listener and store its cleanup function on LView. const lCleanup = getOrCreateLViewCleanup(lView); ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode | TNodeType.AnyContainer); let processOutputs = true; // Adding a native event listener is applicable when: // - The corresponding TNode represents a DOM element. // - The event target has a resolver (usually resulting in a global object, // such as `window` or `document`). if (tNode.type & TNodeType.AnyRNode || eventTargetResolver) { const native = getNativeByTNode(tNode, lView) as RElement; const target = eventTargetResolver ? eventTargetResolver(native) : native; const lCleanupIndex = lCleanup.length; const idxOrTargetGetter = eventTargetResolver ? (_lView: LView) => eventTargetResolver(unwrapRNode(_lView[tNode.index])) : tNode.index; // In order to match current behavior, native DOM event listeners must be added for all // events (including outputs). // There might be cases where multiple directives on the same element try to register an event // handler function for the same event. In this situation we want to avoid registration of // several native listeners as each registration would be intercepted by NgZone and // trigger change detection. This would mean that a single user action would result in several // change detections being invoked. To avoid this situation we want to have only one call to // native handler registration (for the same element and same type of event). // // In order to have just one native event handler in presence of multiple handler functions, // we just register a first handler function as a native event listener and then chain // (coalesce) other handler functions on top of the first native handler function. let existingListener = null; // Please note that the coalescing described here doesn't happen for events specifying an // alternative target (ex. (document:click)) - this is to keep backward compatibility with the // view engine. // Also, we don't have to search for existing listeners is there are no directives // matching on a given node as we can't register multiple event handlers for the same event in // a template (this would mean having duplicate attributes). if (!eventTargetResolver && isTNodeDirectiveHost) { existingListener = findExistingListener(tView, lView, eventName, tNode.index); } if (existingListener !== null) { // Attach a new listener to coalesced listeners list, maintaining the order in which // listeners are registered. For performance reasons, we keep a reference to the last // listener in that list (in `__ngLastListenerFn__` field), so we can avoid going through // the entire set each time we need to add a new listener. const lastListenerFn = (<any>existingListener).__ngLastListenerFn__ || existingListener; lastListenerFn.__ngNextListenerFn__ = listenerFn; (<any>existingListener).__ngLastListenerFn__ = listenerFn; processOutputs = false; } else { listenerFn = wrapListener(tNode, lView, context, listenerFn); stashEventListener(native, eventName, listenerFn); const cleanupFn = renderer.listen(target as RElement, eventName, listenerFn); ngDevMode && ngDevMode.rendererAddEventListener++; lCleanup.push(listenerFn, cleanupFn); tCleanup && tCleanup.push(eventName, idxOrTargetGetter, lCleanupIndex, lCleanupIndex + 1); } } else { // Even if there is no native listener to add, we still need to wrap the listener so that OnPush // ancestors are marked dirty when an event occurs. listenerFn = wrapListener(tNode, lView, context, listenerFn); } // subscribe to directive outputs const outputs = tNode.outputs; let props: NodeOutputBindings[keyof NodeOutputBindings] | undefined; if (processOutputs && outputs !== null && (props = outputs[eventName])) { const propsLength = props.length; if (propsLength) { for (let i = 0; i < propsLength; i += 2) { const index = props[i] as number; ngDevMode && assertIndexInRange(lView, index); const minifiedName = props[i + 1]; const directiveInstance = lView[index]; const output = directiveInstance[minifiedName]; if (ngDevMode && !isOutputSubscribable(output)) { throw new Error( `@Output ${minifiedName} not initialized in '${directiveInstance.constructor.name}'.`, ); } const subscription = (output as SubscribableOutput<unknown>).subscribe(listenerFn); const idx = lCleanup.length; lCleanup.push(listenerFn, subscription); tCleanup && tCleanup.push(eventName, tNode.index, idx, -(idx + 1)); } } } } function executeListenerWithErrorHandling( lView: LView, context: {} | null, listenerFn: (e?: any) => any, e: any, ): boolean { const prevConsumer = setActiveConsumer(null); try { profiler(ProfilerEvent.OutputStart, context, listenerFn); // Only explicitly returning false from a listener should preventDefault return listenerFn(e) !== false; } catch (error) { handleError(lView, error); return false; } finally { profiler(ProfilerEvent.OutputEnd, context, listenerFn); setActiveConsumer(prevConsumer); } } /** * Wraps an event listener with a function that marks ancestors dirty and prevents default behavior, * if applicable. * * @param tNode The TNode associated with this listener * @param lView The LView that contains this listener * @param listenerFn The listener function to call * @param wrapWithPreventDefault Whether or not to prevent default behavior * (the procedural renderer does this already, so in those cases, we should skip) */ function wrapListener( tNode: TNode, lView: LView<{} | null>, context: {} | null, listenerFn: (e?: any) => any, ): EventListener { // Note: we are performing most of the work in the listener function itself // to optimize listener registration. return function wrapListenerIn_markDirtyAndPreventDefault(e: any) { // Ivy uses `Function` as a special token that allows us to unwrap the function // so that it can be invoked programmatically by `DebugNode.triggerEventHandler`. if (e === Function) { return listenerFn; } // In order to be backwards compatible with View Engine, events on component host nodes // must also mark the component view itself dirty (i.e. the view that it owns). const startView = tNode.componentOffset > -1 ? getComponentLViewByIndex(tNode.index, lView) : lView; markViewDirty(startView, NotificationSource.Listener); let result = executeListenerWithErrorHandling(lView, context, listenerFn, e); // A just-invoked listener function might have coalesced listeners so we need to check for // their presence and invoke as needed. let nextListenerFn = (<any>wrapListenerIn_markDirtyAndPreventDefault).__ngNextListenerFn__; while (nextListenerFn) { // We should prevent default if any of the listeners explicitly return false result = executeListenerWithErrorHandling(lView, context, nextListenerFn, e) && result; nextListenerFn = (<any>nextListenerFn).__ngNextListenerFn__; } return result; }; } /** Describes a subscribable output field value. */ interface SubscribableOutput<T> { subscribe(listener: (v: T) => void): {unsubscribe: () => void}; } /** * Whether the given value represents a subscribable output. * * For example, an `EventEmitter, a `Subject`, an `Observable` or an * `OutputEmitter`. */ function isOutputSubscribable(value: unknown): value is SubscribableOutput<unknown> { return ( value != null && typeof (value as Partial<SubscribableOutput<unknown>>).subscribe === 'function' ); }
{ "end_byte": 14481, "start_byte": 5957, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/listener.ts" }
angular/packages/core/src/render3/instructions/host_property.ts_0_3477
/** * @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 {bindingUpdated} from '../bindings'; import {SanitizerFn} from '../interfaces/sanitization'; import {RENDERER} from '../interfaces/view'; import { getCurrentDirectiveDef, getLView, getSelectedTNode, getTView, nextBindingIndex, } from '../state'; import {NO_CHANGE} from '../tokens'; import { elementPropertyInternal, loadComponentRenderer, storePropertyBindingMetadata, } from './shared'; /** * Update a property on a host element. Only applies to native node properties, not inputs. * * Operates on the element selected by index via the {@link select} instruction. * * @param propName Name of property. Because it is going to DOM, this is not subject to * renaming as part of minification. * @param value New value to write. * @param sanitizer An optional function used to sanitize the value. * @returns This function returns itself so that it may be chained * (e.g. `property('name', ctx.name)('title', ctx.title)`) * * @codeGenApi */ export function ɵɵhostProperty<T>( propName: string, value: T, sanitizer?: SanitizerFn | null, ): typeof ɵɵhostProperty { const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal(tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, true); ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex); } return ɵɵhostProperty; } /** * Updates a synthetic host binding (e.g. `[@foo]`) on a component or directive. * * This instruction is for compatibility purposes and is designed to ensure that a * synthetic host binding (e.g. `@HostBinding('@foo')`) properly gets rendered in * the component's renderer. Normally all host bindings are evaluated with the parent * component's renderer, but, in the case of animation @triggers, they need to be * evaluated with the sub component's renderer (because that's where the animation * triggers are defined). * * Do not use this instruction as a replacement for `elementProperty`. This instruction * only exists to ensure compatibility with the ViewEngine's host binding behavior. * * @param index The index of the element to update in the data array * @param propName Name of property. Because it is going to DOM, this is not subject to * renaming as part of minification. * @param value New value to write. * @param sanitizer An optional function used to sanitize the value. * * @codeGenApi */ export function ɵɵsyntheticHostProperty<T>( propName: string, value: T | NO_CHANGE, sanitizer?: SanitizerFn | null, ): typeof ɵɵsyntheticHostProperty { const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { const tView = getTView(); const tNode = getSelectedTNode(); const currentDef = getCurrentDirectiveDef(tView.data); const renderer = loadComponentRenderer(currentDef, tNode, lView); elementPropertyInternal(tView, tNode, lView, propName, value, renderer, sanitizer, true); ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex); } return ɵɵsyntheticHostProperty; }
{ "end_byte": 3477, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/host_property.ts" }
angular/packages/core/src/render3/instructions/class_map_interpolation.ts_0_6078
/** * @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 {keyValueArraySet} from '../../util/array_utils'; import {getLView} from '../state'; import { interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV, } from './interpolation'; import {checkStylingMap, classStringParser} from './styling'; /** * * Update an interpolated class on an element with single bound value surrounded by text. * * Used when the value passed to a property has 1 interpolated value in it: * * ```html * <div class="prefix{{v0}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate1('prefix', v0, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate1(prefix: string, v0: any, suffix: string): void { const lView = getLView(); const interpolatedValue = interpolation1(lView, prefix, v0, suffix); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 2 bound values surrounded by text. * * Used when the value passed to a property has 2 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate2('prefix', v0, '-', v1, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate2( prefix: string, v0: any, i0: string, v1: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 3 bound values surrounded by text. * * Used when the value passed to a property has 3 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate3( * 'prefix', v0, '-', v1, '-', v2, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate3( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 4 bound values surrounded by text. * * Used when the value passed to a property has 4 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate4( * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate4( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 5 bound values surrounded by text. * * Used when the value passed to a property has 5 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate5( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate5( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation5( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, ); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update a
{ "end_byte": 6078, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/class_map_interpolation.ts" }
angular/packages/core/src/render3/instructions/class_map_interpolation.ts_6080_12270
interpolated class on an element with 6 bound values surrounded by text. * * Used when the value passed to a property has 6 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate6( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate6( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation6( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, ); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 7 bound values surrounded by text. * * Used when the value passed to a property has 7 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate7( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param i5 Static value used for concatenation only. * @param v6 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate7( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation7( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, ); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * * Update an interpolated class on an element with 8 bound values surrounded by text. * * Used when the value passed to a property has 8 interpolated values in it: * * ```html * <div class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolate8( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix'); * ``` * * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param i5 Static value used for concatenation only. * @param v6 Value checked for change. * @param i6 Static value used for concatenation only. * @param v7 Value checked for change. * @param suffix Static value used for concatenation only. * @codeGenApi */ export function ɵɵclassMapInterpolate8( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any, suffix: string, ): void { const lView = getLView(); const interpolatedValue = interpolation8( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, ); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); } /** * Update an interpolated class on an element with 9 or more bound values surrounded by text. * * Used when the number of interpolated values exceeds 8. * * ```html * <div * class="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div> * ``` * * Its compiled representation is: * * ```ts * ɵɵclassMapInterpolateV( * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9, * 'suffix']); * ``` *. * @param values The collection of values and the strings in-between those values, beginning with * a string prefix and ending with a string suffix. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`) * @codeGenApi */ export function ɵɵclassMapInterpolateV(values: any[]): void { const lView = getLView(); const interpolatedValue = interpolationV(lView, values); checkStylingMap(keyValueArraySet, classStringParser, interpolatedValue, true); }
{ "end_byte": 12270, "start_byte": 6080, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/class_map_interpolation.ts" }
angular/packages/core/src/render3/instructions/two_way.ts_0_2808
/*! * @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 {bindingUpdated} from '../bindings'; import {SanitizerFn} from '../interfaces/sanitization'; import {RENDERER} from '../interfaces/view'; import {isWritableSignal, WritableSignal} from '../reactivity/signal'; import {getCurrentTNode, getLView, getSelectedTNode, getTView, nextBindingIndex} from '../state'; import {listenerInternal} from './listener'; import {elementPropertyInternal, storePropertyBindingMetadata} from './shared'; /** * Update a two-way bound property on a selected element. * * Operates on the element selected by index via the {@link select} instruction. * * @param propName Name of property. * @param value New value to write. * @param sanitizer An optional function used to sanitize the value. * @returns This function returns itself so that it may be chained * (e.g. `twoWayProperty('name', ctx.name)('title', ctx.title)`) * * @codeGenApi */ export function ɵɵtwoWayProperty<T>( propName: string, value: T | WritableSignal<T>, sanitizer?: SanitizerFn | null, ): typeof ɵɵtwoWayProperty { // TODO(crisbeto): perf impact of re-evaluating this on each change detection? if (isWritableSignal(value)) { value = value(); } const lView = getLView(); const bindingIndex = nextBindingIndex(); if (bindingUpdated(lView, bindingIndex, value)) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, value, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata(tView.data, tNode, propName, bindingIndex); } return ɵɵtwoWayProperty; } /** * Function used inside two-way listeners to conditionally set the value of the bound expression. * * @param target Field on which to set the value. * @param value Value to be set to the field. * * @codeGenApi */ export function ɵɵtwoWayBindingSet<T>(target: unknown, value: T): boolean { const canWrite = isWritableSignal(target); canWrite && target.set(value); return canWrite; } /** * Adds an event listener that updates a two-way binding to the current node. * * @param eventName Name of the event. * @param listenerFn The function to be called when event emits. * * @codeGenApi */ export function ɵɵtwoWayListener( eventName: string, listenerFn: (e?: any) => any, ): typeof ɵɵtwoWayListener { const lView = getLView<{} | null>(); const tView = getTView(); const tNode = getCurrentTNode()!; listenerInternal(tView, lView, lView[RENDERER], tNode, eventName, listenerFn); return ɵɵtwoWayListener; }
{ "end_byte": 2808, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/two_way.ts" }
angular/packages/core/src/render3/instructions/next_context.ts_0_808
/** * @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 {nextContextImpl} from '../state'; /** * Retrieves a context at the level specified and saves it as the global, contextViewData. * Will get the next level up if level is not specified. * * This is used to save contexts of parent views so they can be bound in embedded views, or * in conjunction with reference() to bind a ref from a parent view. * * @param level The relative level of the view from which to grab context compared to contextVewData * @returns context * * @codeGenApi */ export function ɵɵnextContext<T = any>(level: number = 1): T { return nextContextImpl(level); }
{ "end_byte": 808, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/next_context.ts" }
angular/packages/core/src/render3/instructions/namespace.ts_0_287
/** * @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 {ɵɵnamespaceHTML, ɵɵnamespaceMathML, ɵɵnamespaceSVG} from '../state';
{ "end_byte": 287, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/namespace.ts" }
angular/packages/core/src/render3/instructions/projection.ts_0_8665
/** * @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 {findMatchingDehydratedView} from '../../hydration/views'; import {newArray} from '../../util/array_utils'; import {assertLContainer, assertTNode} from '../assert'; import {ComponentTemplate} from '../interfaces/definition'; import {TAttributes, TElementNode, TNode, TNodeFlags, TNodeType} from '../interfaces/node'; import {ProjectionSlots} from '../interfaces/projection'; import { DECLARATION_COMPONENT_VIEW, HEADER_OFFSET, HYDRATION, LView, T_HOST, TView, } from '../interfaces/view'; import {applyProjection} from '../node_manipulation'; import { getProjectAsAttrValue, isNodeMatchingSelectorList, isSelectorInSelectorList, } from '../node_selector_matcher'; import {getLView, getTView, isInSkipHydrationBlock, setCurrentTNodeAsNotParent} from '../state'; import { addLViewToLContainer, createAndRenderEmbeddedLView, shouldAddViewToDom, } from '../view_manipulation'; import {getOrCreateTNode} from './shared'; import {declareTemplate} from './template'; /** * Checks a given node against matching projection slots and returns the * determined slot index. Returns "null" if no slot matched the given node. * * This function takes into account the parsed ngProjectAs selector from the * node's attributes. If present, it will check whether the ngProjectAs selector * matches any of the projection slot selectors. */ export function matchingProjectionSlotIndex( tNode: TNode, projectionSlots: ProjectionSlots, ): number | null { let wildcardNgContentIndex = null; const ngProjectAsAttrVal = getProjectAsAttrValue(tNode); for (let i = 0; i < projectionSlots.length; i++) { const slotValue = projectionSlots[i]; // The last wildcard projection slot should match all nodes which aren't matching // any selector. This is necessary to be backwards compatible with view engine. if (slotValue === '*') { wildcardNgContentIndex = i; continue; } // If we ran into an `ngProjectAs` attribute, we should match its parsed selector // to the list of selectors, otherwise we fall back to matching against the node. if ( ngProjectAsAttrVal === null ? isNodeMatchingSelectorList(tNode, slotValue, /* isProjectionMode */ true) : isSelectorInSelectorList(ngProjectAsAttrVal, slotValue) ) { return i; // first matching selector "captures" a given node } } return wildcardNgContentIndex; } /** * Instruction to distribute projectable nodes among <ng-content> occurrences in a given template. * It takes all the selectors from the entire component's template and decides where * each projected node belongs (it re-distributes nodes among "buckets" where each "bucket" is * backed by a selector). * * This function requires CSS selectors to be provided in 2 forms: parsed (by a compiler) and text, * un-parsed form. * * The parsed form is needed for efficient matching of a node against a given CSS selector. * The un-parsed, textual form is needed for support of the ngProjectAs attribute. * * Having a CSS selector in 2 different formats is not ideal, but alternatives have even more * drawbacks: * - having only a textual form would require runtime parsing of CSS selectors; * - we can't have only a parsed as we can't re-construct textual form from it (as entered by a * template author). * * @param projectionSlots? A collection of projection slots. A projection slot can be based * on a parsed CSS selectors or set to the wildcard selector ("*") in order to match * all nodes which do not match any selector. If not specified, a single wildcard * selector projection slot will be defined. * * @codeGenApi */ export function ɵɵprojectionDef(projectionSlots?: ProjectionSlots): void { const componentNode = getLView()[DECLARATION_COMPONENT_VIEW][T_HOST] as TElementNode; if (!componentNode.projection) { // If no explicit projection slots are defined, fall back to a single // projection slot with the wildcard selector. const numProjectionSlots = projectionSlots ? projectionSlots.length : 1; const projectionHeads: (TNode | null)[] = (componentNode.projection = newArray( numProjectionSlots, null! as TNode, )); const tails: (TNode | null)[] = projectionHeads.slice(); let componentChild: TNode | null = componentNode.child; while (componentChild !== null) { // Do not project let declarations so they don't occupy a slot. if (componentChild.type !== TNodeType.LetDeclaration) { const slotIndex = projectionSlots ? matchingProjectionSlotIndex(componentChild, projectionSlots) : 0; if (slotIndex !== null) { if (tails[slotIndex]) { tails[slotIndex]!.projectionNext = componentChild; } else { projectionHeads[slotIndex] = componentChild; } tails[slotIndex] = componentChild; } } componentChild = componentChild.next; } } } /** * Inserts previously re-distributed projected nodes. This instruction must be preceded by a call * to the projectionDef instruction. * * @param nodeIndex Index of the projection node. * @param selectorIndex Index of the slot selector. * - 0 when the selector is `*` (or unspecified as this is the default value), * - 1 based index of the selector from the {@link projectionDef} * @param attrs Static attributes set on the `ng-content` node. * @param fallbackTemplateFn Template function with fallback content. * Will be rendered if the slot is empty at runtime. * @param fallbackDecls Number of declarations in the fallback template. * @param fallbackVars Number of variables in the fallback template. * * @codeGenApi */ export function ɵɵprojection( nodeIndex: number, selectorIndex: number = 0, attrs?: TAttributes, fallbackTemplateFn?: ComponentTemplate<unknown>, fallbackDecls?: number, fallbackVars?: number, ): void { const lView = getLView(); const tView = getTView(); const fallbackIndex = fallbackTemplateFn ? nodeIndex + 1 : null; // Fallback content needs to be declared no matter whether the slot is empty since different // instances of the component may or may not insert it. Also it needs to be declare *before* // the projection node in order to work correctly with hydration. if (fallbackIndex !== null) { declareTemplate( lView, tView, fallbackIndex, fallbackTemplateFn!, fallbackDecls!, fallbackVars!, null, attrs, ); } const tProjectionNode = getOrCreateTNode( tView, HEADER_OFFSET + nodeIndex, TNodeType.Projection, null, attrs || null, ); // We can't use viewData[HOST_NODE] because projection nodes can be nested in embedded views. if (tProjectionNode.projection === null) { tProjectionNode.projection = selectorIndex; } // `<ng-content>` has no content. Even if there's fallback // content, the fallback is shown next to it. setCurrentTNodeAsNotParent(); const hydrationInfo = lView[HYDRATION]; const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock(); const componentHostNode = lView[DECLARATION_COMPONENT_VIEW][T_HOST] as TElementNode; const isEmpty = componentHostNode.projection![tProjectionNode.projection] === null; if (isEmpty && fallbackIndex !== null) { insertFallbackContent(lView, tView, fallbackIndex); } else if ( isNodeCreationMode && (tProjectionNode.flags & TNodeFlags.isDetached) !== TNodeFlags.isDetached ) { // re-distribution of projectable nodes is stored on a component's view level applyProjection(tView, lView, tProjectionNode); } } /** Inserts the fallback content of a projection slot. Assumes there's no projected content. */ function insertFallbackContent(lView: LView, tView: TView, fallbackIndex: number) { const adjustedIndex = HEADER_OFFSET + fallbackIndex; const fallbackTNode = tView.data[adjustedIndex] as TNode; const fallbackLContainer = lView[adjustedIndex]; ngDevMode && assertTNode(fallbackTNode); ngDevMode && assertLContainer(fallbackLContainer); const dehydratedView = findMatchingDehydratedView(fallbackLContainer, fallbackTNode.tView!.ssrId); const fallbackLView = createAndRenderEmbeddedLView(lView, fallbackTNode, undefined, { dehydratedView, }); addLViewToLContainer( fallbackLContainer, fallbackLView, 0, shouldAddViewToDom(fallbackTNode, dehydratedView), ); }
{ "end_byte": 8665, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/projection.ts" }
angular/packages/core/src/render3/instructions/queries.ts_0_2855
/** * @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 {ProviderToken} from '../../di'; import {unwrapElementRef} from '../../linker/element_ref'; import {QueryList} from '../../linker/query_list'; import {QueryFlags} from '../interfaces/query'; import { createContentQuery, createViewQuery, getQueryResults, getTQuery, loadQueryInternal, } from '../query'; import {getCurrentQueryIndex, getLView, getTView, setCurrentQueryIndex} from '../state'; import {isCreationMode} from '../util/view_utils'; /** * Registers a QueryList, associated with a content query, for later refresh (part of a view * refresh). * * @param directiveIndex Current directive index * @param predicate The type for which the query will search * @param flags Flags associated with the query * @param read What to save in the query * @returns QueryList<T> * * @codeGenApi */ export function ɵɵcontentQuery<T>( directiveIndex: number, predicate: ProviderToken<unknown> | string | string[], flags: QueryFlags, read?: any, ): void { createContentQuery<T>(directiveIndex, predicate, flags, read); } /** * Creates a new view query by initializing internal data structures. * * @param predicate The type for which the query will search * @param flags Flags associated with the query * @param read What to save in the query * * @codeGenApi */ export function ɵɵviewQuery<T>( predicate: ProviderToken<unknown> | string | string[], flags: QueryFlags, read?: any, ): void { createViewQuery(predicate, flags, read); } /** * Refreshes a query by combining matches from all active views and removing matches from deleted * views. * * @returns `true` if a query got dirty during change detection or if this is a static query * resolving in creation mode, `false` otherwise. * * @codeGenApi */ export function ɵɵqueryRefresh(queryList: QueryList<any>): boolean { const lView = getLView(); const tView = getTView(); const queryIndex = getCurrentQueryIndex(); setCurrentQueryIndex(queryIndex + 1); const tQuery = getTQuery(tView, queryIndex); if ( queryList.dirty && isCreationMode(lView) === ((tQuery.metadata.flags & QueryFlags.isStatic) === QueryFlags.isStatic) ) { if (tQuery.matches === null) { queryList.reset([]); } else { const result = getQueryResults(lView, queryIndex); queryList.reset(result, unwrapElementRef); queryList.notifyOnChanges(); } return true; } return false; } /** * Loads a QueryList corresponding to the current view or content query. * * @codeGenApi */ export function ɵɵloadQuery<T>(): QueryList<T> { return loadQueryInternal<T>(getLView(), getCurrentQueryIndex()); }
{ "end_byte": 2855, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/queries.ts" }
angular/packages/core/src/render3/instructions/i18n.ts_0_7546
/** * @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 '../../util/ng_i18n_closure_mode'; import {prepareI18nBlockForHydration} from '../../hydration/i18n'; import {assertDefined} from '../../util/assert'; import {bindingUpdated} from '../bindings'; import {applyCreateOpCodes, applyI18n, setMaskBit} from '../i18n/i18n_apply'; import {i18nAttributesFirstPass, i18nStartFirstCreatePass} from '../i18n/i18n_parse'; import {i18nPostprocess} from '../i18n/i18n_postprocess'; import {TI18n} from '../interfaces/i18n'; import {TElementNode, TNodeType} from '../interfaces/node'; import { DECLARATION_COMPONENT_VIEW, FLAGS, HEADER_OFFSET, LViewFlags, T_HOST, TViewType, } from '../interfaces/view'; import {getClosestRElement} from '../node_manipulation'; import { getCurrentParentTNode, getLView, getTView, nextBindingIndex, setInI18nBlock, } from '../state'; import {getConstant} from '../util/view_utils'; /** * Marks a block of text as translatable. * * The instructions `i18nStart` and `i18nEnd` mark the translation block in the template. * The translation `message` is the value which is locale specific. The translation string may * contain placeholders which associate inner elements and sub-templates within the translation. * * The translation `message` placeholders are: * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be * interpolated into. The placeholder `index` points to the expression binding index. An optional * `block` that matches the sub-template in which it was declared. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning * and end of DOM element that were embedded in the original translation block. The placeholder * `index` points to the element index in the template instructions set. An optional `block` that * matches the sub-template in which it was declared. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be * split up and translated separately in each angular template function. The `index` points to the * `template` instruction index. A `block` that matches the sub-template in which it was declared. * * @param index A unique index of the translation in the static block. * @param messageIndex An index of the translation message from the `def.consts` array. * @param subTemplateIndex Optional sub-template index in the `message`. * * @codeGenApi */ export function ɵɵi18nStart( index: number, messageIndex: number, subTemplateIndex: number = -1, ): void { const tView = getTView(); const lView = getLView(); const adjustedIndex = HEADER_OFFSET + index; ngDevMode && assertDefined(tView, `tView should be defined`); const message = getConstant<string>(tView.consts, messageIndex)!; const parentTNode = getCurrentParentTNode() as TElementNode | null; if (tView.firstCreatePass) { i18nStartFirstCreatePass( tView, parentTNode === null ? 0 : parentTNode.index, lView, adjustedIndex, message, subTemplateIndex, ); } // Set a flag that this LView has i18n blocks. // The flag is later used to determine whether this component should // be hydrated (currently hydration is not supported for i18n blocks). if (tView.type === TViewType.Embedded) { // Annotate host component's LView (not embedded view's LView), // since hydration can be skipped on per-component basis only. const componentLView = lView[DECLARATION_COMPONENT_VIEW]; componentLView[FLAGS] |= LViewFlags.HasI18n; } else { lView[FLAGS] |= LViewFlags.HasI18n; } const tI18n = tView.data[adjustedIndex] as TI18n; const sameViewParentTNode = parentTNode === lView[T_HOST] ? null : parentTNode; const parentRNode = getClosestRElement(tView, sameViewParentTNode, lView); // If `parentTNode` is an `ElementContainer` than it has `<!--ng-container--->`. // When we do inserts we have to make sure to insert in front of `<!--ng-container--->`. const insertInFrontOf = parentTNode && parentTNode.type & TNodeType.ElementContainer ? lView[parentTNode.index] : null; prepareI18nBlockForHydration(lView, adjustedIndex, parentTNode, subTemplateIndex); applyCreateOpCodes(lView, tI18n.create, parentRNode, insertInFrontOf); setInI18nBlock(true); } /** * Translates a translation block marked by `i18nStart` and `i18nEnd`. It inserts the text/ICU nodes * into the render tree, moves the placeholder nodes and removes the deleted nodes. * * @codeGenApi */ export function ɵɵi18nEnd(): void { setInI18nBlock(false); } /** * * Use this instruction to create a translation block that doesn't contain any placeholder. * It calls both {@link i18nStart} and {@link i18nEnd} in one instruction. * * The translation `message` is the value which is locale specific. The translation string may * contain placeholders which associate inner elements and sub-templates within the translation. * * The translation `message` placeholders are: * - `�{index}(:{block})�`: *Binding Placeholder*: Marks a location where an expression will be * interpolated into. The placeholder `index` points to the expression binding index. An optional * `block` that matches the sub-template in which it was declared. * - `�#{index}(:{block})�`/`�/#{index}(:{block})�`: *Element Placeholder*: Marks the beginning * and end of DOM element that were embedded in the original translation block. The placeholder * `index` points to the element index in the template instructions set. An optional `block` that * matches the sub-template in which it was declared. * - `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template Placeholder*: Sub-templates must be * split up and translated separately in each angular template function. The `index` points to the * `template` instruction index. A `block` that matches the sub-template in which it was declared. * * @param index A unique index of the translation in the static block. * @param messageIndex An index of the translation message from the `def.consts` array. * @param subTemplateIndex Optional sub-template index in the `message`. * * @codeGenApi */ export function ɵɵi18n(index: number, messageIndex: number, subTemplateIndex?: number): void { ɵɵi18nStart(index, messageIndex, subTemplateIndex); ɵɵi18nEnd(); } /** * Marks a list of attributes as translatable. * * @param index A unique index in the static block * @param values * * @codeGenApi */ export function ɵɵi18nAttributes(index: number, attrsIndex: number): void { const tView = getTView(); ngDevMode && assertDefined(tView, `tView should be defined`); const attrs = getConstant<string[]>(tView.consts, attrsIndex)!; i18nAttributesFirstPass(tView, index + HEADER_OFFSET, attrs); } /** * Stores the values of the bindings during each update cycle in order to determine if we need to * update the translated nodes. * * @param value The binding's value * @returns This function returns itself so that it may be chained * (e.g. `i18nExp(ctx.name)(ctx.title)`) * * @codeGenApi */ export function ɵɵi18nExp<T>(value: T): typeof ɵɵi18nExp { const lView = getLView(); setMaskBit(bindingUpdated(lView, nextBindingIndex(), value)); return ɵɵi18nExp; } /** * Updates a translation block or an i18n attribute
{ "end_byte": 7546, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/i18n.ts" }
angular/packages/core/src/render3/instructions/i18n.ts_7548_9000
en the bindings have changed. * * @param index Index of either {@link i18nStart} (translation block) or {@link i18nAttributes} * (i18n attribute) on which it should update the content. * * @codeGenApi */ export function ɵɵi18nApply(index: number) { applyI18n(getTView(), getLView(), index + HEADER_OFFSET); } /** * Handles message string post-processing for internationalization. * * Handles message string post-processing by transforming it from intermediate * format (that might contain some markers that we need to replace) to the final * form, consumable by i18nStart instruction. Post processing steps include: * * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�]) * 2. Replace all ICU vars (like "VAR_PLURAL") * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER} * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) * in case multiple ICUs have the same placeholder name * * @param message Raw translation string for post processing * @param replacements Set of replacements that should be applied * * @returns Transformed string that can be consumed by i18nStart instruction * * @codeGenApi */ export function ɵɵi18nPostprocess( message: string, replacements: {[key: string]: string | string[]} = {}, ): string { return i18nPostprocess(message, replacements); }
{ "end_byte": 9000, "start_byte": 7548, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/i18n.ts" }
angular/packages/core/src/render3/instructions/template.ts_0_7248
/** * @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 {validateMatchingNode, validateNodeExists} from '../../hydration/error_handling'; import {TEMPLATES} from '../../hydration/interfaces'; import {locateNextRNode, siblingAfter} from '../../hydration/node_lookup_utils'; import { calcSerializedContainerSize, isDisconnectedNode, markRNodeAsClaimedByHydration, setSegmentHead, } from '../../hydration/utils'; import {isDetachedByI18n} from '../../i18n/utils'; import {populateDehydratedViewsInLContainer} from '../../linker/view_container_ref'; import {assertEqual} from '../../util/assert'; import {assertFirstCreatePass} from '../assert'; import {attachPatchData} from '../context_discovery'; import {registerPostOrderHooks} from '../hooks'; import {ComponentTemplate} from '../interfaces/definition'; import {LocalRefExtractor, TAttributes, TContainerNode, TNode, TNodeType} from '../interfaces/node'; import {RComment} from '../interfaces/renderer_dom'; import {isDirectiveHost} from '../interfaces/type_checks'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView, TViewType} from '../interfaces/view'; import {appendChild} from '../node_manipulation'; import { getLView, getTView, isInSkipHydrationBlock, lastNodeWasCreated, setCurrentTNode, wasLastNodeCreated, } from '../state'; import {getConstant} from '../util/view_utils'; import { addToEndOfViewTree, createDirectivesInstances, createLContainer, createTView, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData, } from './shared'; function templateFirstCreatePass( index: number, tView: TView, lView: LView, templateFn: ComponentTemplate<any> | null, decls: number, vars: number, tagName?: string | null, attrs?: TAttributes | null, localRefsIndex?: number | null, ): TContainerNode { ngDevMode && assertFirstCreatePass(tView); ngDevMode && ngDevMode.firstCreatePass++; const tViewConsts = tView.consts; // TODO(pk): refactor getOrCreateTNode to have the "create" only version const tNode = getOrCreateTNode(tView, index, TNodeType.Container, tagName || null, attrs || null); resolveDirectives(tView, lView, tNode, getConstant<string[]>(tViewConsts, localRefsIndex)); registerPostOrderHooks(tView, tNode); const embeddedTView = (tNode.tView = createTView( TViewType.Embedded, tNode, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry, null, tView.schemas, tViewConsts, null /* ssrId */, )); if (tView.queries !== null) { tView.queries.template(tView, tNode); embeddedTView.queries = tView.queries.embeddedTView(tNode); } return tNode; } /** * Creates an LContainer for an embedded view. * * @param declarationLView LView in which the template was declared. * @param declarationTView TView in which the template wa declared. * @param index The index of the container in the data array * @param templateFn Inline template * @param decls The number of nodes, local refs, and pipes for this template * @param vars The number of bindings for this template * @param tagName The name of the container element, if applicable * @param attrsIndex Index of template attributes in the `consts` array. * @param localRefs Index of the local references in the `consts` array. * @param localRefExtractor A function which extracts local-refs values from the template. * Defaults to the current element associated with the local-ref. */ export function declareTemplate( declarationLView: LView, declarationTView: TView, index: number, templateFn: ComponentTemplate<any> | null, decls: number, vars: number, tagName?: string | null, attrs?: TAttributes | null, localRefsIndex?: number | null, localRefExtractor?: LocalRefExtractor, ): TNode { const adjustedIndex = index + HEADER_OFFSET; const tNode = declarationTView.firstCreatePass ? templateFirstCreatePass( adjustedIndex, declarationTView, declarationLView, templateFn, decls, vars, tagName, attrs, localRefsIndex, ) : (declarationTView.data[adjustedIndex] as TContainerNode); setCurrentTNode(tNode, false); const comment = _locateOrCreateContainerAnchor( declarationTView, declarationLView, tNode, index, ) as RComment; if (wasLastNodeCreated()) { appendChild(declarationTView, declarationLView, comment, tNode); } attachPatchData(comment, declarationLView); const lContainer = createLContainer(comment, declarationLView, comment, tNode); declarationLView[adjustedIndex] = lContainer; addToEndOfViewTree(declarationLView, lContainer); // 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, declarationLView); if (isDirectiveHost(tNode)) { createDirectivesInstances(declarationTView, declarationLView, tNode); } if (localRefsIndex != null) { saveResolvedLocalsInData(declarationLView, tNode, localRefExtractor); } return tNode; } /** * Creates an LContainer for an ng-template (dynamically-inserted view), e.g. * * <ng-template #foo> * <div></div> * </ng-template> * * @param index The index of the container in the data array * @param templateFn Inline template * @param decls The number of nodes, local refs, and pipes for this template * @param vars The number of bindings for this template * @param tagName The name of the container element, if applicable * @param attrsIndex Index of template attributes in the `consts` array. * @param localRefs Index of the local references in the `consts` array. * @param localRefExtractor A function which extracts local-refs values from the template. * Defaults to the current element associated with the local-ref. * * @codeGenApi */ export function ɵɵtemplate( index: number, templateFn: ComponentTemplate<any> | null, decls: number, vars: number, tagName?: string | null, attrsIndex?: number | null, localRefsIndex?: number | null, localRefExtractor?: LocalRefExtractor, ): typeof ɵɵtemplate { const lView = getLView(); const tView = getTView(); const attrs = getConstant<TAttributes>(tView.consts, attrsIndex); declareTemplate( lView, tView, index, templateFn, decls, vars, tagName, attrs, localRefsIndex, localRefExtractor, ); return ɵɵtemplate; } let _locateOrCreateContainerAnchor = createContainerAnchorImpl; /** * Regular creation mode for LContainers and their anchor (comment) nodes. */ function createContainerAnchorImpl( tView: TView, lView: LView, tNode: TNode, index: number, ): RComment { lastNodeWasCreated(true); return lView[RENDERER].createComment(ngDevMode ? 'container' : ''); } /** * Enables hydration code path (to lookup existing elements in DOM) * in addition to the regular creation mode for LContainers and their * anchor (comment) nodes. */ funct
{ "end_byte": 7248, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/template.ts" }
angular/packages/core/src/render3/instructions/template.ts_7249_9343
on locateOrCreateContainerAnchorImpl( tView: TView, lView: LView, tNode: TNode, index: number, ): RComment { const hydrationInfo = lView[HYDRATION]; const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock() || isDetachedByI18n(tNode) || isDisconnectedNode(hydrationInfo, index); lastNodeWasCreated(isNodeCreationMode); // Regular creation mode. if (isNodeCreationMode) { return createContainerAnchorImpl(tView, lView, tNode, index); } const ssrId = hydrationInfo.data[TEMPLATES]?.[index] ?? null; // Apply `ssrId` value to the underlying TView if it was not previously set. // // There might be situations when the same component is present in a template // multiple times and some instances are opted-out of using hydration via // `ngSkipHydration` attribute. In this scenario, at the time a TView is created, // the `ssrId` might be `null` (if the first component is opted-out of hydration). // The code below makes sure that the `ssrId` is applied to the TView if it's still // `null` and verifies we never try to override it with a different value. if (ssrId !== null && tNode.tView !== null) { if (tNode.tView.ssrId === null) { tNode.tView.ssrId = ssrId; } else { ngDevMode && assertEqual(tNode.tView.ssrId, ssrId, 'Unexpected value of the `ssrId` for this TView'); } } // Hydration mode, looking up existing elements in DOM. const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode)!; ngDevMode && validateNodeExists(currentRNode, lView, tNode); setSegmentHead(hydrationInfo, index, currentRNode); const viewContainerSize = calcSerializedContainerSize(hydrationInfo, index); const comment = siblingAfter<RComment>(viewContainerSize, currentRNode)!; if (ngDevMode) { validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode); markRNodeAsClaimedByHydration(comment); } return comment; } export function enableLocateOrCreateContainerAnchorImpl() { _locateOrCreateContainerAnchor = locateOrCreateContainerAnchorImpl; }
{ "end_byte": 9343, "start_byte": 7249, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/template.ts" }
angular/packages/core/src/render3/instructions/text_interpolation.ts_0_5901
/** * @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 {getLView, getSelectedIndex} from '../state'; import {NO_CHANGE} from '../tokens'; import { interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV, } from './interpolation'; import {textBindingInternal} from './shared'; /** * * Update text content with a lone bound value * * Used when a text node has 1 interpolated value in it, an no additional text * surrounds that interpolated value: * * ```html * <div>{{v0}}</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate(v0); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate(v0: any): typeof ɵɵtextInterpolate { ɵɵtextInterpolate1('', v0, ''); return ɵɵtextInterpolate; } /** * * Update text content with single bound value surrounded by other text. * * Used when a text node has 1 interpolated value in it: * * ```html * <div>prefix{{v0}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate1('prefix', v0, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate1( prefix: string, v0: any, suffix: string, ): typeof ɵɵtextInterpolate1 { const lView = getLView(); const interpolated = interpolation1(lView, prefix, v0, suffix); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate1; } /** * * Update text content with 2 bound values surrounded by other text. * * Used when a text node has 2 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate2('prefix', v0, '-', v1, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate2( prefix: string, v0: any, i0: string, v1: any, suffix: string, ): typeof ɵɵtextInterpolate2 { const lView = getLView(); const interpolated = interpolation2(lView, prefix, v0, i0, v1, suffix); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate2; } /** * * Update text content with 3 bound values surrounded by other text. * * Used when a text node has 3 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate3( * 'prefix', v0, '-', v1, '-', v2, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate3( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string, ): typeof ɵɵtextInterpolate3 { const lView = getLView(); const interpolated = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate3; } /** * * Update text content with 4 bound values surrounded by other text. * * Used when a text node has 4 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate4( * 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see ɵɵtextInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate4( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, suffix: string, ): typeof ɵɵtextInterpolate4 { const lView = getLView(); const interpolated = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate4; } /** * * Update text content with 5 bound values surrounded by other text. * * Used when a text node has 5 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate5( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate5( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, suffix: string, ): typeof ɵɵtextInterpolate5 { const lView = getLView(); const interpolated = interpolation5(lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate5; } /** * * Update text content with 6 bound values surrounded by other text. * * Used when a text node has 6 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate6( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix'); * ``` * * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate6( prefix: string,
{ "end_byte": 5901, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/text_interpolation.ts" }
angular/packages/core/src/render3/instructions/text_interpolation.ts_5902_9850
v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, suffix: string, ): typeof ɵɵtextInterpolate6 { const lView = getLView(); const interpolated = interpolation6( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, ); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate6; } /** * * Update text content with 7 bound values surrounded by other text. * * Used when a text node has 7 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate7( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate7( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string, ): typeof ɵɵtextInterpolate7 { const lView = getLView(); const interpolated = interpolation7( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, ); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate7; } /** * * Update text content with 8 bound values surrounded by other text. * * Used when a text node has 8 interpolated values in it: * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolate8( * 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix'); * ``` * @returns itself, so that it may be chained. * @see textInterpolateV * @codeGenApi */ export function ɵɵtextInterpolate8( prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any, suffix: string, ): typeof ɵɵtextInterpolate8 { const lView = getLView(); const interpolated = interpolation8( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, ); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolate8; } /** * Update text content with 9 or more bound values other surrounded by text. * * Used when the number of interpolated values exceeds 8. * * ```html * <div>prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix</div> * ``` * * Its compiled representation is: * * ```ts * ɵɵtextInterpolateV( * ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9, * 'suffix']); * ``` *. * @param values The collection of values and the strings in between those values, beginning with * a string prefix and ending with a string suffix. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`) * * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵtextInterpolateV(values: any[]): typeof ɵɵtextInterpolateV { const lView = getLView(); const interpolated = interpolationV(lView, values); if (interpolated !== NO_CHANGE) { textBindingInternal(lView, getSelectedIndex(), interpolated as string); } return ɵɵtextInterpolateV; }
{ "end_byte": 9850, "start_byte": 5902, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/text_interpolation.ts" }
angular/packages/core/src/render3/instructions/text.ts_0_3284
/** * @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 {validateMatchingNode} from '../../hydration/error_handling'; import {locateNextRNode} from '../../hydration/node_lookup_utils'; import {isDisconnectedNode, markRNodeAsClaimedByHydration} from '../../hydration/utils'; import {isDetachedByI18n} from '../../i18n/utils'; import {assertEqual, assertIndexInRange} from '../../util/assert'; import {TElementNode, TNode, TNodeType} from '../interfaces/node'; import {RText} from '../interfaces/renderer_dom'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, T_HOST, TView} from '../interfaces/view'; import {appendChild, createTextNode} from '../node_manipulation'; import { getBindingIndex, getLView, getTView, isInSkipHydrationBlock, lastNodeWasCreated, setCurrentTNode, wasLastNodeCreated, } from '../state'; import {getOrCreateTNode} from './shared'; /** * Create static text node * * @param index Index of the node in the data array * @param value Static string value to write. * * @codeGenApi */ export function ɵɵtext(index: number, value: string = ''): void { const lView = getLView(); const tView = getTView(); const adjustedIndex = index + HEADER_OFFSET; ngDevMode && assertEqual( getBindingIndex(), tView.bindingStartIndex, 'text nodes should be created before any bindings', ); ngDevMode && assertIndexInRange(lView, adjustedIndex); const tNode = tView.firstCreatePass ? getOrCreateTNode(tView, adjustedIndex, TNodeType.Text, value, null) : (tView.data[adjustedIndex] as TElementNode); const textNative = _locateOrCreateTextNode(tView, lView, tNode, value, index); lView[adjustedIndex] = textNative; if (wasLastNodeCreated()) { appendChild(tView, lView, textNative, tNode); } // Text nodes are self closing. setCurrentTNode(tNode, false); } let _locateOrCreateTextNode: typeof locateOrCreateTextNodeImpl = ( tView: TView, lView: LView, tNode: TNode, value: string, index: number, ) => { lastNodeWasCreated(true); return createTextNode(lView[RENDERER], value); }; /** * Enables hydration code path (to lookup existing elements in DOM) * in addition to the regular creation mode of text nodes. */ function locateOrCreateTextNodeImpl( tView: TView, lView: LView, tNode: TNode, value: string, index: number, ): RText { const hydrationInfo = lView[HYDRATION]; const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock() || isDetachedByI18n(tNode) || isDisconnectedNode(hydrationInfo, index); lastNodeWasCreated(isNodeCreationMode); // Regular creation mode. if (isNodeCreationMode) { return createTextNode(lView[RENDERER], value); } // Hydration mode, looking up an existing element in DOM. const textNative = locateNextRNode(hydrationInfo, tView, lView, tNode) as RText; ngDevMode && validateMatchingNode(textNative, Node.TEXT_NODE, null, lView, tNode); ngDevMode && markRNodeAsClaimedByHydration(textNative); return textNative; } export function enableLocateOrCreateTextNodeImpl() { _locateOrCreateTextNode = locateOrCreateTextNodeImpl; }
{ "end_byte": 3284, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/text.ts" }
angular/packages/core/src/render3/instructions/storage.ts_0_1271
/** * @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 {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getContextLView} from '../state'; import {load} from '../util/view_utils'; /** Store a value in the `data` at a given `index`. */ export function store<T>(tView: TView, lView: LView, index: number, value: T): void { // We don't store any static data for local variables, so the first time // we see the template, we should store as null to avoid a sparse array if (index >= tView.data.length) { tView.data[index] = null; tView.blueprint[index] = null; } lView[index] = value; } /** * Retrieves a local reference from the current contextViewData. * * If the reference to retrieve is in a parent view, this instruction is used in conjunction * with a nextContext() call, which walks up the tree and updates the contextViewData instance. * * @param index The index of the local ref in contextViewData. * * @codeGenApi */ export function ɵɵreference<T>(index: number) { const contextLView = getContextLView(); return load<T>(contextLView, HEADER_OFFSET + index); }
{ "end_byte": 1271, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/storage.ts" }
angular/packages/core/src/render3/instructions/advance.ts_0_2795
/** * @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 {assertGreaterThan} from '../../util/assert'; import {assertIndexInDeclRange} from '../assert'; import {executeCheckHooks, executeInitAndCheckHooks} from '../hooks'; import {FLAGS, InitPhaseState, LView, LViewFlags, TVIEW, TView} from '../interfaces/view'; import { getLView, getSelectedIndex, getTView, isInCheckNoChangesMode, setSelectedIndex, } from '../state'; /** * Advances to an element for later binding instructions. * * Used in conjunction with instructions like {@link property} to act on elements with specified * indices, for example those created with {@link element} or {@link elementStart}. * * ```ts * (rf: RenderFlags, ctx: any) => { * if (rf & 1) { * text(0, 'Hello'); * text(1, 'Goodbye') * element(2, 'div'); * } * if (rf & 2) { * advance(2); // Advance twice to the <div>. * property('title', 'test'); * } * } * ``` * @param delta Number of elements to advance forwards by. * * @codeGenApi */ export function ɵɵadvance(delta: number = 1): void { ngDevMode && assertGreaterThan(delta, 0, 'Can only advance forward'); selectIndexInternal( getTView(), getLView(), getSelectedIndex() + delta, !!ngDevMode && isInCheckNoChangesMode(), ); } export function selectIndexInternal( tView: TView, lView: LView, index: number, checkNoChangesMode: boolean, ) { ngDevMode && assertIndexInDeclRange(lView[TVIEW], index); // Flush the initial hooks for elements in the view that have been added up to this point. // PERF WARNING: do NOT extract this to a separate function without running benchmarks if (!checkNoChangesMode) { const hooksInitPhaseCompleted = (lView[FLAGS] & LViewFlags.InitPhaseStateMask) === InitPhaseState.InitPhaseCompleted; if (hooksInitPhaseCompleted) { const preOrderCheckHooks = tView.preOrderCheckHooks; if (preOrderCheckHooks !== null) { executeCheckHooks(lView, preOrderCheckHooks, index); } } else { const preOrderHooks = tView.preOrderHooks; if (preOrderHooks !== null) { executeInitAndCheckHooks(lView, preOrderHooks, InitPhaseState.OnInitHooksToBeRun, index); } } } // We must set the selected index *after* running the hooks, because hooks may have side-effects // that cause other template functions to run, thus updating the selected index, which is global // state. If we run `setSelectedIndex` *before* we run the hooks, in some cases the selected index // will be altered by the time we leave the `ɵɵadvance` instruction. setSelectedIndex(index); }
{ "end_byte": 2795, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/advance.ts" }
angular/packages/core/src/render3/instructions/di_attr.ts_0_511
/** * @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 {injectAttributeImpl} from '../di'; import {getCurrentTNode} from '../state'; /** * Facade for the attribute injection from DI. * * @codeGenApi */ export function ɵɵinjectAttribute(attrNameToInject: string): string | null { return injectAttributeImpl(getCurrentTNode()!, attrNameToInject); }
{ "end_byte": 511, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/di_attr.ts" }
angular/packages/core/src/render3/instructions/shared.ts_0_6122
/** * @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 {Injector} from '../../di/injector'; import {ErrorHandler} from '../../error_handler'; import {RuntimeError, RuntimeErrorCode} from '../../errors'; import {DehydratedView} from '../../hydration/interfaces'; import {hasSkipHydrationAttrOnRElement} from '../../hydration/skip_hydration'; import {PRESERVE_HOST_CONTENT, PRESERVE_HOST_CONTENT_DEFAULT} from '../../hydration/tokens'; import {processTextNodeMarkersBeforeHydration} from '../../hydration/utils'; import {DoCheck, OnChanges, OnInit} from '../../interface/lifecycle_hooks'; import {Writable} from '../../interface/type'; import {SchemaMetadata} from '../../metadata/schema'; import {ViewEncapsulation} from '../../metadata/view'; import { validateAgainstEventAttributes, validateAgainstEventProperties, } from '../../sanitization/sanitization'; import { assertDefined, assertEqual, assertGreaterThan, assertGreaterThanOrEqual, assertIndexInRange, assertNotEqual, assertNotSame, assertSame, assertString, } from '../../util/assert'; import {escapeCommentText} from '../../util/dom'; import {normalizeDebugBindingName, normalizeDebugBindingValue} from '../../util/ng_reflect'; import {stringify} from '../../util/stringify'; import {applyValueToInputField} from '../apply_value_input_field'; import { assertFirstCreatePass, assertFirstUpdatePass, assertLView, assertNoDuplicateDirectives, assertTNodeForLView, assertTNodeForTView, } from '../assert'; import {attachPatchData} from '../context_discovery'; import {getFactoryDef} from '../definition_factory'; import {diPublicInInjector, getNodeInjectable, getOrCreateNodeInjectorForNode} from '../di'; import {throwMultipleComponentError} from '../errors'; import {AttributeMarker} from '../interfaces/attribute_marker'; import {CONTAINER_HEADER_OFFSET, LContainer} from '../interfaces/container'; import { ComponentDef, ComponentTemplate, DirectiveDef, DirectiveDefListOrFactory, HostBindingsFunction, HostDirectiveBindingMap, HostDirectiveDefs, PipeDefListOrFactory, RenderFlags, ViewQueriesFunction, } from '../interfaces/definition'; import {NodeInjectorFactory} from '../interfaces/injector'; import {InputFlags} from '../interfaces/input_flags'; import {getUniqueLViewId} from '../interfaces/lview_tracking'; import { InitialInputData, InitialInputs, LocalRefExtractor, NodeInputBindings, NodeOutputBindings, TAttributes, TConstantsOrFactory, TContainerNode, TDirectiveHostNode, TElementContainerNode, TElementNode, TIcuContainerNode, TLetDeclarationNode, TNode, TNodeFlags, TNodeType, TProjectionNode, } from '../interfaces/node'; import {Renderer} from '../interfaces/renderer'; import {RComment, RElement, RNode, RText} from '../interfaces/renderer_dom'; import {SanitizerFn} from '../interfaces/sanitization'; import {TStylingRange} from '../interfaces/styling'; import {isComponentDef, isComponentHost, isContentQueryHost} from '../interfaces/type_checks'; import { CHILD_HEAD, CHILD_TAIL, CLEANUP, CONTEXT, DECLARATION_COMPONENT_VIEW, DECLARATION_VIEW, EMBEDDED_VIEW_INJECTOR, ENVIRONMENT, FLAGS, HEADER_OFFSET, HOST, HostBindingOpCodes, HYDRATION, ID, INJECTOR, LView, LViewEnvironment, LViewFlags, NEXT, PARENT, RENDERER, T_HOST, TData, TVIEW, TView, TViewType, } from '../interfaces/view'; import {assertPureTNodeType, assertTNodeType} from '../node_assert'; import {clearElementContents, updateTextNode} from '../node_manipulation'; import {isInlineTemplate, isNodeMatchingSelectorList} from '../node_selector_matcher'; import {profiler} from '../profiler'; import {ProfilerEvent} from '../profiler_types'; import { getBindingsEnabled, getCurrentDirectiveIndex, getCurrentParentTNode, getCurrentTNodePlaceholderOk, getSelectedIndex, isCurrentTNodeParent, isInCheckNoChangesMode, isInI18nBlock, isInSkipHydrationBlock, setBindingRootForHostBindings, setCurrentDirectiveIndex, setCurrentQueryIndex, setCurrentTNode, setSelectedIndex, } from '../state'; import {NO_CHANGE} from '../tokens'; import {mergeHostAttrs} from '../util/attrs_utils'; import {INTERPOLATION_DELIMITER} from '../util/misc_utils'; import {renderStringify} from '../util/stringify_utils'; import { getComponentLViewByIndex, getNativeByIndex, getNativeByTNode, resetPreOrderHookFlags, unwrapLView, } from '../util/view_utils'; import {selectIndexInternal} from './advance'; import {ɵɵdirectiveInject} from './di'; import {handleUnknownPropertyError, isPropertyValid, matchingSchemas} from './element_validation'; import {writeToDirectiveInput} from './write_to_directive_input'; /** * Invoke `HostBindingsFunction`s for view. * * This methods executes `TView.hostBindingOpCodes`. It is used to execute the * `HostBindingsFunction`s associated with the current `LView`. * * @param tView Current `TView`. * @param lView Current `LView`. */ export function processHostBindingOpCodes(tView: TView, lView: LView): void { const hostBindingOpCodes = tView.hostBindingOpCodes; if (hostBindingOpCodes === null) return; try { for (let i = 0; i < hostBindingOpCodes.length; i++) { const opCode = hostBindingOpCodes[i] as number; if (opCode < 0) { // Negative numbers are element indexes. setSelectedIndex(~opCode); } else { // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex. const directiveIdx = opCode; const bindingRootIndx = hostBindingOpCodes[++i] as number; const hostBindingFn = hostBindingOpCodes[++i] as HostBindingsFunction<any>; setBindingRootForHostBindings(bindingRootIndx, directiveIdx); const context = lView[directiveIdx]; hostBindingFn(RenderFlags.Update, context); } } } finally { setSelectedIndex(-1); } }
{ "end_byte": 6122, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_6124_13147
port function createLView<T>( parentLView: LView | null, tView: TView, context: T | null, flags: LViewFlags, host: RElement | null, tHostNode: TNode | null, environment: LViewEnvironment | null, renderer: Renderer | null, injector: Injector | null, embeddedViewInjector: Injector | null, hydrationInfo: DehydratedView | null, ): LView<T> { const lView = tView.blueprint.slice() as LView; lView[HOST] = host; lView[FLAGS] = flags | LViewFlags.CreationMode | LViewFlags.Attached | LViewFlags.FirstLViewPass | LViewFlags.Dirty | LViewFlags.RefreshView; if ( embeddedViewInjector !== null || (parentLView && parentLView[FLAGS] & LViewFlags.HasEmbeddedViewInjector) ) { lView[FLAGS] |= LViewFlags.HasEmbeddedViewInjector; } resetPreOrderHookFlags(lView); ngDevMode && tView.declTNode && parentLView && assertTNodeForLView(tView.declTNode, parentLView); lView[PARENT] = lView[DECLARATION_VIEW] = parentLView; lView[CONTEXT] = context; lView[ENVIRONMENT] = (environment || (parentLView && parentLView[ENVIRONMENT]))!; ngDevMode && assertDefined(lView[ENVIRONMENT], 'LViewEnvironment is required'); lView[RENDERER] = (renderer || (parentLView && parentLView[RENDERER]))!; ngDevMode && assertDefined(lView[RENDERER], 'Renderer is required'); lView[INJECTOR as any] = injector || (parentLView && parentLView[INJECTOR]) || null; lView[T_HOST] = tHostNode; lView[ID] = getUniqueLViewId(); lView[HYDRATION] = hydrationInfo; lView[EMBEDDED_VIEW_INJECTOR as any] = embeddedViewInjector; ngDevMode && assertEqual( tView.type == TViewType.Embedded ? parentLView !== null : true, true, 'Embedded views must have parentLView', ); lView[DECLARATION_COMPONENT_VIEW] = tView.type == TViewType.Embedded ? parentLView![DECLARATION_COMPONENT_VIEW] : lView; return lView as LView<T>; } /** * Create and stores the TNode, and hooks it up to the tree. * * @param tView The current `TView`. * @param index The index at which the TNode should be saved (null if view, since they are not * saved). * @param type The type of TNode to create * @param native The native element for this node, if applicable * @param name The tag name of the associated native element, if applicable * @param attrs Any attrs for the native element, if applicable */ export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.Element | TNodeType.Text, name: string | null, attrs: TAttributes | null, ): TElementNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.Container, name: string | null, attrs: TAttributes | null, ): TContainerNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.Projection, name: null, attrs: TAttributes | null, ): TProjectionNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.ElementContainer, name: string | null, attrs: TAttributes | null, ): TElementContainerNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.Icu, name: null, attrs: TAttributes | null, ): TElementContainerNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType.LetDeclaration, name: null, attrs: null, ): TLetDeclarationNode; export function getOrCreateTNode( tView: TView, index: number, type: TNodeType, name: string | null, attrs: TAttributes | null, ): TElementNode & TContainerNode & TElementContainerNode & TProjectionNode & TIcuContainerNode & TLetDeclarationNode { ngDevMode && index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in // `view_engine_compatibility` for additional context. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header."); // Keep this function short, so that the VM will inline it. ngDevMode && assertPureTNodeType(type); let tNode = tView.data[index] as TNode; if (tNode === null) { tNode = createTNodeAtIndex(tView, index, type, name, attrs); if (isInI18nBlock()) { // If we are in i18n block then all elements should be pre declared through `Placeholder` // See `TNodeType.Placeholder` and `LFrame.inI18n` for more context. // If the `TNode` was not pre-declared than it means it was not mentioned which means it was // removed, so we mark it as detached. tNode.flags |= TNodeFlags.isDetached; } } else if (tNode.type & TNodeType.Placeholder) { tNode.type = type; tNode.value = name; tNode.attrs = attrs; const parent = getCurrentParentTNode(); tNode.injectorIndex = parent === null ? -1 : parent.injectorIndex; ngDevMode && assertTNodeForTView(tNode, tView); ngDevMode && assertEqual(index, tNode.index, 'Expecting same index'); } setCurrentTNode(tNode, true); return tNode as TElementNode & TContainerNode & TElementContainerNode & TProjectionNode & TIcuContainerNode; } export function createTNodeAtIndex( tView: TView, index: number, type: TNodeType, name: string | null, attrs: TAttributes | null, ) { const currentTNode = getCurrentTNodePlaceholderOk(); const isParent = isCurrentTNodeParent(); const parent = isParent ? currentTNode : currentTNode && currentTNode.parent; // Parents cannot cross component boundaries because components will be used in multiple places. const tNode = (tView.data[index] = createTNode( tView, parent as TElementNode | TContainerNode, type, index, name, attrs, )); // Assign a pointer to the first child node of a given view. The first node is not always the one // at index 0, in case of i18n, index 0 can be the instruction `i18nStart` and the first node has // the index 1 or more, so we can't just check node index. if (tView.firstChild === null) { tView.firstChild = tNode; } if (currentTNode !== null) { if (isParent) { // FIXME(misko): This logic looks unnecessarily complicated. Could we simplify? if (currentTNode.child == null && tNode.parent !== null) { // We are in the same view, which means we are adding content node to the parent view. currentTNode.child = tNode; } } else { if (currentTNode.next === null) { // In the case of i18n the `currentTNode` may already be linked, in which case we don't want // to break the links which i18n created. currentTNode.next = tNode; tNode.prev = currentTNode; } } } return tNode; } /** * When elements are created dynamically after a view blueprint is created (e.g. through * i18nApply()), we need to adjust the blueprint for future * template passes. * * @param tView `TView` associated with `LView` * @param lView The `LView` containing the blueprint to adjust * @param numSlotsToAlloc The number of slots to alloc in the LView, should be >0 * @param initialValue Initial value to store in blueprint */ e
{ "end_byte": 13147, "start_byte": 6124, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_13148_21004
port function allocExpando( tView: TView, lView: LView, numSlotsToAlloc: number, initialValue: any, ): number { if (numSlotsToAlloc === 0) return -1; if (ngDevMode) { assertFirstCreatePass(tView); assertSame(tView, lView[TVIEW], '`LView` must be associated with `TView`!'); assertEqual(tView.data.length, lView.length, 'Expecting LView to be same size as TView'); assertEqual( tView.data.length, tView.blueprint.length, 'Expecting Blueprint to be same size as TView', ); assertFirstUpdatePass(tView); } const allocIdx = lView.length; for (let i = 0; i < numSlotsToAlloc; i++) { lView.push(initialValue); tView.blueprint.push(initialValue); tView.data.push(null); } return allocIdx; } export function executeTemplate<T>( tView: TView, lView: LView<T>, templateFn: ComponentTemplate<T>, rf: RenderFlags, context: T, ) { const prevSelectedIndex = getSelectedIndex(); const isUpdatePhase = rf & RenderFlags.Update; try { setSelectedIndex(-1); if (isUpdatePhase && lView.length > HEADER_OFFSET) { // When we're updating, inherently select 0 so we don't // have to generate that instruction for most update blocks. selectIndexInternal(tView, lView, HEADER_OFFSET, !!ngDevMode && isInCheckNoChangesMode()); } const preHookType = isUpdatePhase ? ProfilerEvent.TemplateUpdateStart : ProfilerEvent.TemplateCreateStart; profiler(preHookType, context as unknown as {}); templateFn(rf, context); } finally { setSelectedIndex(prevSelectedIndex); const postHookType = isUpdatePhase ? ProfilerEvent.TemplateUpdateEnd : ProfilerEvent.TemplateCreateEnd; profiler(postHookType, context as unknown as {}); } } ////////////////////////// //// Element ////////////////////////// export function executeContentQueries(tView: TView, tNode: TNode, lView: LView) { if (isContentQueryHost(tNode)) { const prevConsumer = setActiveConsumer(null); try { const start = tNode.directiveStart; const end = tNode.directiveEnd; for (let directiveIndex = start; directiveIndex < end; directiveIndex++) { const def = tView.data[directiveIndex] as DirectiveDef<any>; if (def.contentQueries) { const directiveInstance = lView[directiveIndex]; ngDevMode && assertDefined( directiveIndex, 'Incorrect reference to a directive defining a content query', ); def.contentQueries(RenderFlags.Create, directiveInstance, directiveIndex); } } } finally { setActiveConsumer(prevConsumer); } } } /** * Creates directive instances. */ export function createDirectivesInstances(tView: TView, lView: LView, tNode: TDirectiveHostNode) { if (!getBindingsEnabled()) return; instantiateAllDirectives(tView, lView, tNode, getNativeByTNode(tNode, lView)); if ((tNode.flags & TNodeFlags.hasHostBindings) === TNodeFlags.hasHostBindings) { invokeDirectivesHostBindings(tView, lView, tNode); } } /** * Takes a list of local names and indices and pushes the resolved local variable values * to LView in the same order as they are loaded in the template with load(). */ export function saveResolvedLocalsInData( viewData: LView, tNode: TDirectiveHostNode, localRefExtractor: LocalRefExtractor = getNativeByTNode, ): void { const localNames = tNode.localNames; if (localNames !== null) { let localIndex = tNode.index + 1; for (let i = 0; i < localNames.length; i += 2) { const index = localNames[i + 1] as number; const value = index === -1 ? localRefExtractor( tNode as TElementNode | TContainerNode | TElementContainerNode, viewData, ) : viewData[index]; viewData[localIndex++] = value; } } } /** * Gets TView from a template function or creates a new TView * if it doesn't already exist. * * @param def ComponentDef * @returns TView */ export function getOrCreateComponentTView(def: ComponentDef<any>): TView { const tView = def.tView; // Create a TView if there isn't one, or recreate it if the first create pass didn't // complete successfully since we can't know for sure whether it's in a usable shape. if (tView === null || tView.incompleteFirstPass) { // Declaration node here is null since this function is called when we dynamically create a // component and hence there is no declaration. const declTNode = null; return (def.tView = createTView( TViewType.Component, declTNode, def.template, def.decls, def.vars, def.directiveDefs, def.pipeDefs, def.viewQuery, def.schemas, def.consts, def.id, )); } return tView; } /** * Creates a TView instance * * @param type Type of `TView`. * @param declTNode Declaration location of this `TView`. * @param templateFn Template function * @param decls The number of nodes, local refs, and pipes in this template * @param directives Registry of directives for this view * @param pipes Registry of pipes for this view * @param viewQuery View queries for this view * @param schemas Schemas for this view * @param consts Constants for this view */ export function createTView( type: TViewType, declTNode: TNode | null, templateFn: ComponentTemplate<any> | null, decls: number, vars: number, directives: DirectiveDefListOrFactory | null, pipes: PipeDefListOrFactory | null, viewQuery: ViewQueriesFunction<any> | null, schemas: SchemaMetadata[] | null, constsOrFactory: TConstantsOrFactory | null, ssrId: string | null, ): TView { ngDevMode && ngDevMode.tView++; const bindingStartIndex = HEADER_OFFSET + decls; // This length does not yet contain host bindings from child directives because at this point, // we don't know which directives are active on this template. As soon as a directive is matched // that has a host binding, we will update the blueprint with that def's hostVars count. const initialViewLength = bindingStartIndex + vars; const blueprint = createViewBlueprint(bindingStartIndex, initialViewLength); const consts = typeof constsOrFactory === 'function' ? constsOrFactory() : constsOrFactory; const tView = (blueprint[TVIEW as any] = { type: type, blueprint: blueprint, template: templateFn, queries: null, viewQuery: viewQuery, declTNode: declTNode, data: blueprint.slice().fill(null, bindingStartIndex), bindingStartIndex: bindingStartIndex, expandoStartIndex: initialViewLength, hostBindingOpCodes: null, firstCreatePass: true, firstUpdatePass: true, staticViewQueries: false, staticContentQueries: false, preOrderHooks: null, preOrderCheckHooks: null, contentHooks: null, contentCheckHooks: null, viewHooks: null, viewCheckHooks: null, destroyHooks: null, cleanup: null, contentQueries: null, components: null, directiveRegistry: typeof directives === 'function' ? directives() : directives, pipeRegistry: typeof pipes === 'function' ? pipes() : pipes, firstChild: null, schemas: schemas, consts: consts, incompleteFirstPass: false, ssrId, }); if (ngDevMode) { // For performance reasons it is important that the tView retains the same shape during runtime. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to // prevent class transitions. Object.seal(tView); } return tView; } function createViewBlueprint(bindingStartIndex: number, initialViewLength: number): LView { const blueprint = []; for (let i = 0; i < initialViewLength; i++) { blueprint.push(i < bindingStartIndex ? null : NO_CHANGE); } return blueprint as LView; }
{ "end_byte": 21004, "start_byte": 13148, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_21006_29250
* * Locates the host native element, used for bootstrapping existing nodes into rendering pipeline. * * @param renderer the renderer used to locate the element. * @param elementOrSelector Render element or CSS selector to locate the element. * @param encapsulation View Encapsulation defined for component that requests host element. * @param injector Root view injector instance. */ export function locateHostElement( renderer: Renderer, elementOrSelector: RElement | string, encapsulation: ViewEncapsulation, injector: Injector, ): RElement { // Note: we use default value for the `PRESERVE_HOST_CONTENT` here even though it's a // tree-shakable one (providedIn:'root'). This code path can be triggered during dynamic // component creation (after calling ViewContainerRef.createComponent) when an injector // instance can be provided. The injector instance might be disconnected from the main DI // tree, thus the `PRESERVE_HOST_CONTENT` would not be able to instantiate. In this case, the // default value will be used. const preserveHostContent = injector.get(PRESERVE_HOST_CONTENT, PRESERVE_HOST_CONTENT_DEFAULT); // When using native Shadow DOM, do not clear host element to allow native slot // projection. const preserveContent = preserveHostContent || encapsulation === ViewEncapsulation.ShadowDom; const rootElement = renderer.selectRootElement(elementOrSelector, preserveContent); applyRootElementTransform(rootElement as HTMLElement); return rootElement; } /** * Applies any root element transformations that are needed. If hydration is enabled, * this will process corrupted text nodes. * * @param rootElement the app root HTML Element */ export function applyRootElementTransform(rootElement: HTMLElement) { _applyRootElementTransformImpl(rootElement as HTMLElement); } /** * Reference to a function that applies transformations to the root HTML element * of an app. When hydration is enabled, this processes any corrupt text nodes * so they are properly hydratable on the client. * * @param rootElement the app root HTML Element */ let _applyRootElementTransformImpl: typeof applyRootElementTransformImpl = () => null; /** * Processes text node markers before hydration begins. This replaces any special comment * nodes that were added prior to serialization are swapped out to restore proper text * nodes before hydration. * * @param rootElement the app root HTML Element */ export function applyRootElementTransformImpl(rootElement: HTMLElement) { if (hasSkipHydrationAttrOnRElement(rootElement)) { // Handle a situation when the `ngSkipHydration` attribute is applied // to the root node of an application. In this case, we should clear // the contents and render everything from scratch. clearElementContents(rootElement as RElement); } else { processTextNodeMarkersBeforeHydration(rootElement); } } /** * Sets the implementation for the `applyRootElementTransform` function. */ export function enableApplyRootElementTransformImpl() { _applyRootElementTransformImpl = applyRootElementTransformImpl; } /** * Saves context for this cleanup function in LView.cleanupInstances. * * On the first template pass, saves in TView: * - Cleanup function * - Index of context we just saved in LView.cleanupInstances */ export function storeCleanupWithContext( tView: TView, lView: LView, context: any, cleanupFn: Function, ): void { const lCleanup = getOrCreateLViewCleanup(lView); // Historically the `storeCleanupWithContext` was used to register both framework-level and // user-defined cleanup callbacks, but over time those two types of cleanups were separated. // This dev mode checks assures that user-level cleanup callbacks are _not_ stored in data // structures reserved for framework-specific hooks. ngDevMode && assertDefined( context, 'Cleanup context is mandatory when registering framework-level destroy hooks', ); lCleanup.push(context); if (tView.firstCreatePass) { getOrCreateTViewCleanup(tView).push(cleanupFn, lCleanup.length - 1); } else { // Make sure that no new framework-level cleanup functions are registered after the first // template pass is done (and TView data structures are meant to fully constructed). if (ngDevMode) { Object.freeze(getOrCreateTViewCleanup(tView)); } } } /** * Constructs a TNode object from the arguments. * * @param tView `TView` to which this `TNode` belongs * @param tParent Parent `TNode` * @param type The type of the node * @param index The index of the TNode in TView.data, adjusted for HEADER_OFFSET * @param tagName The tag name of the node * @param attrs The attributes defined on this node * @returns the TNode object */ export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.Container, index: number, tagName: string | null, attrs: TAttributes | null, ): TContainerNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.Element | TNodeType.Text, index: number, tagName: string | null, attrs: TAttributes | null, ): TElementNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.ElementContainer, index: number, tagName: string | null, attrs: TAttributes | null, ): TElementContainerNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.Icu, index: number, tagName: string | null, attrs: TAttributes | null, ): TIcuContainerNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.Projection, index: number, tagName: string | null, attrs: TAttributes | null, ): TProjectionNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType.LetDeclaration, index: number, tagName: null, attrs: null, ): TLetDeclarationNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType, index: number, tagName: string | null, attrs: TAttributes | null, ): TNode; export function createTNode( tView: TView, tParent: TElementNode | TContainerNode | null, type: TNodeType, index: number, value: string | null, attrs: TAttributes | null, ): TNode { ngDevMode && index !== 0 && // 0 are bogus nodes and they are OK. See `createContainerRef` in // `view_engine_compatibility` for additional context. assertGreaterThanOrEqual(index, HEADER_OFFSET, "TNodes can't be in the LView header."); ngDevMode && assertNotSame(attrs, undefined, "'undefined' is not valid value for 'attrs'"); ngDevMode && ngDevMode.tNode++; ngDevMode && tParent && assertTNodeForTView(tParent, tView); let injectorIndex = tParent ? tParent.injectorIndex : -1; let flags = 0; if (isInSkipHydrationBlock()) { flags |= TNodeFlags.inSkipHydrationBlock; } const tNode = { type, index, insertBeforeIndex: null, injectorIndex, directiveStart: -1, directiveEnd: -1, directiveStylingLast: -1, componentOffset: -1, propertyBindings: null, flags, providerIndexes: 0, value: value, attrs: attrs, mergedAttrs: null, localNames: null, initialInputs: undefined, inputs: null, outputs: null, tView: null, next: null, prev: null, projectionNext: null, child: null, parent: tParent, projection: null, styles: null, stylesWithoutHost: null, residualStyles: undefined, classes: null, classesWithoutHost: null, residualClasses: undefined, classBindings: 0 as TStylingRange, styleBindings: 0 as TStylingRange, }; if (ngDevMode) { // For performance reasons it is important that the tNode retains the same shape during runtime. // (To make sure that all of the code is monomorphic.) For this reason we seal the object to // prevent class transitions. Object.seal(tNode); } return tNode; } /** Mode for capturing node bindings. */ const enum CaptureNodeBindingMode { Inputs, Outputs, }
{ "end_byte": 29250, "start_byte": 21006, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_29252_36750
* * Captures node input bindings for the given directive based on the inputs metadata. * This will be called multiple times to combine inputs from various directives on a node. * * The host binding alias map is used to alias and filter out properties for host directives. * If the mapping is provided, it'll act as an allowlist, as well as a mapping of what public * name inputs/outputs should be exposed under. */ function captureNodeBindings<T>( mode: CaptureNodeBindingMode.Inputs, inputs: DirectiveDef<T>['inputs'], directiveIndex: number, bindingsResult: NodeInputBindings | null, hostDirectiveAliasMap: HostDirectiveBindingMap | null, ): NodeInputBindings | null; /** * Captures node output bindings for the given directive based on the output metadata. * This will be called multiple times to combine inputs from various directives on a node. * * The host binding alias map is used to alias and filter out properties for host directives. * If the mapping is provided, it'll act as an allowlist, as well as a mapping of what public * name inputs/outputs should be exposed under. */ function captureNodeBindings<T>( mode: CaptureNodeBindingMode.Outputs, outputs: DirectiveDef<T>['outputs'], directiveIndex: number, bindingsResult: NodeOutputBindings | null, hostDirectiveAliasMap: HostDirectiveBindingMap | null, ): NodeOutputBindings | null; function captureNodeBindings<T>( mode: CaptureNodeBindingMode, aliasMap: DirectiveDef<T>['inputs'] | DirectiveDef<T>['outputs'], directiveIndex: number, bindingsResult: NodeInputBindings | NodeOutputBindings | null, hostDirectiveAliasMap: HostDirectiveBindingMap | null, ): NodeInputBindings | NodeOutputBindings | null { for (let publicName in aliasMap) { if (!aliasMap.hasOwnProperty(publicName)) { continue; } const value = aliasMap[publicName]; if (value === undefined) { continue; } bindingsResult ??= {}; let internalName: string; let inputFlags = InputFlags.None; // For inputs, the value might be an array capturing additional // input flags. if (Array.isArray(value)) { internalName = value[0]; inputFlags = value[1]; } else { internalName = value; } // If there are no host directive mappings, we want to remap using the alias map from the // definition itself. If there is an alias map, it has two functions: // 1. It serves as an allowlist of bindings that are exposed by the host directives. Only the // ones inside the host directive map will be exposed on the host. // 2. The public name of the property is aliased using the host directive alias map, rather // than the alias map from the definition. let finalPublicName: string = publicName; if (hostDirectiveAliasMap !== null) { // If there is no mapping, it's not part of the allowlist and this input/output // is not captured and should be ignored. if (!hostDirectiveAliasMap.hasOwnProperty(publicName)) { continue; } finalPublicName = hostDirectiveAliasMap[publicName]; } if (mode === CaptureNodeBindingMode.Inputs) { addPropertyBinding( bindingsResult as NodeInputBindings, directiveIndex, finalPublicName, internalName, inputFlags, ); } else { addPropertyBinding( bindingsResult as NodeOutputBindings, directiveIndex, finalPublicName, internalName, ); } } return bindingsResult; } function addPropertyBinding( bindings: NodeInputBindings, directiveIndex: number, publicName: string, internalName: string, inputFlags: InputFlags, ): void; function addPropertyBinding( bindings: NodeOutputBindings, directiveIndex: number, publicName: string, internalName: string, ): void; function addPropertyBinding( bindings: NodeInputBindings | NodeOutputBindings, directiveIndex: number, publicName: string, internalName: string, inputFlags?: InputFlags, ) { let values: (typeof bindings)[typeof publicName]; if (bindings.hasOwnProperty(publicName)) { (values = bindings[publicName]).push(directiveIndex, internalName); } else { values = bindings[publicName] = [directiveIndex, internalName]; } if (inputFlags !== undefined) { (values as NodeInputBindings[typeof publicName]).push(inputFlags); } } /** * Initializes data structures required to work with directive inputs and outputs. * Initialization is done for all directives matched on a given TNode. */ function initializeInputAndOutputAliases( tView: TView, tNode: TNode, hostDirectiveDefinitionMap: HostDirectiveDefs | null, ): void { ngDevMode && assertFirstCreatePass(tView); const start = tNode.directiveStart; const end = tNode.directiveEnd; const tViewData = tView.data; const tNodeAttrs = tNode.attrs; const inputsFromAttrs: InitialInputData = []; let inputsStore: NodeInputBindings | null = null; let outputsStore: NodeOutputBindings | null = null; for (let directiveIndex = start; directiveIndex < end; directiveIndex++) { const directiveDef = tViewData[directiveIndex] as DirectiveDef<any>; const aliasData = hostDirectiveDefinitionMap ? hostDirectiveDefinitionMap.get(directiveDef) : null; const aliasedInputs = aliasData ? aliasData.inputs : null; const aliasedOutputs = aliasData ? aliasData.outputs : null; inputsStore = captureNodeBindings( CaptureNodeBindingMode.Inputs, directiveDef.inputs, directiveIndex, inputsStore, aliasedInputs, ); outputsStore = captureNodeBindings( CaptureNodeBindingMode.Outputs, directiveDef.outputs, directiveIndex, outputsStore, aliasedOutputs, ); // Do not use unbound attributes as inputs to structural directives, since structural // directive inputs can only be set using microsyntax (e.g. `<div *dir="exp">`). // TODO(FW-1930): microsyntax expressions may also contain unbound/static attributes, which // should be set for inline templates. const initialInputs = inputsStore !== null && tNodeAttrs !== null && !isInlineTemplate(tNode) ? generateInitialInputs(inputsStore, directiveIndex, tNodeAttrs) : null; inputsFromAttrs.push(initialInputs); } if (inputsStore !== null) { if (inputsStore.hasOwnProperty('class')) { tNode.flags |= TNodeFlags.hasClassInput; } if (inputsStore.hasOwnProperty('style')) { tNode.flags |= TNodeFlags.hasStyleInput; } } tNode.initialInputs = inputsFromAttrs; tNode.inputs = inputsStore; tNode.outputs = outputsStore; } /** * Mapping between attributes names that don't correspond to their element property names. * * Performance note: this function is written as a series of if checks (instead of, say, a property * object lookup) for performance reasons - the series of `if` checks seems to be the fastest way of * mapping property names. Do NOT change without benchmarking. * * Note: this mapping has to be kept in sync with the equally named mapping in the template * type-checking machinery of ngtsc. */ function mapPropName(name: string): string { if (name === 'class') return 'className'; if (name === 'for') return 'htmlFor'; if (name === 'formaction') return 'formAction'; if (name === 'innerHtml') return 'innerHTML'; if (name === 'readonly') return 'readOnly'; if (name === 'tabindex') return 'tabIndex'; return name; }
{ "end_byte": 36750, "start_byte": 29252, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_36752_41603
port function elementPropertyInternal<T>( tView: TView, tNode: TNode, lView: LView, propName: string, value: T, renderer: Renderer, sanitizer: SanitizerFn | null | undefined, nativeOnly: boolean, ): void { ngDevMode && assertNotSame(value, NO_CHANGE as any, 'Incoming value should never be NO_CHANGE.'); const element = getNativeByTNode(tNode, lView) as RElement | RComment; let inputData = tNode.inputs; let dataValue: NodeInputBindings[typeof propName] | undefined; if (!nativeOnly && inputData != null && (dataValue = inputData[propName])) { setInputsForProperty(tView, lView, dataValue, propName, value); if (isComponentHost(tNode)) markDirtyIfOnPush(lView, tNode.index); if (ngDevMode) { setNgReflectProperties(lView, element, tNode.type, dataValue, value); } } else if (tNode.type & TNodeType.AnyRNode) { propName = mapPropName(propName); if (ngDevMode) { validateAgainstEventProperties(propName); if (!isPropertyValid(element, propName, tNode.value, tView.schemas)) { handleUnknownPropertyError(propName, tNode.value, tNode.type, lView); } ngDevMode.rendererSetProperty++; } // It is assumed that the sanitizer is only added when the compiler determines that the // property is risky, so sanitization can be done without further checks. value = sanitizer != null ? (sanitizer(value, tNode.value || '', propName) as any) : value; renderer.setProperty(element as RElement, propName, value); } else if (tNode.type & TNodeType.AnyContainer) { // If the node is a container and the property didn't // match any of the inputs or schemas we should throw. if (ngDevMode && !matchingSchemas(tView.schemas, tNode.value)) { handleUnknownPropertyError(propName, tNode.value, tNode.type, lView); } } } /** If node is an OnPush component, marks its LView dirty. */ export function markDirtyIfOnPush(lView: LView, viewIndex: number): void { ngDevMode && assertLView(lView); const childComponentLView = getComponentLViewByIndex(viewIndex, lView); if (!(childComponentLView[FLAGS] & LViewFlags.CheckAlways)) { childComponentLView[FLAGS] |= LViewFlags.Dirty; } } function setNgReflectProperty( lView: LView, element: RElement | RComment, type: TNodeType, attrName: string, value: any, ) { const renderer = lView[RENDERER]; attrName = normalizeDebugBindingName(attrName); const debugValue = normalizeDebugBindingValue(value); if (type & TNodeType.AnyRNode) { if (value == null) { renderer.removeAttribute(element as RElement, attrName); } else { renderer.setAttribute(element as RElement, attrName, debugValue); } } else { const textContent = escapeCommentText( `bindings=${JSON.stringify({[attrName]: debugValue}, null, 2)}`, ); renderer.setValue(element as RComment, textContent); } } export function setNgReflectProperties( lView: LView, element: RElement | RComment, type: TNodeType, dataValue: NodeInputBindings[string], value: any, ) { if (type & (TNodeType.AnyRNode | TNodeType.Container)) { /** * dataValue is an array containing runtime input or output names for the directives: * i+0: directive instance index * i+1: privateName * * e.g. [0, 'change', 'change-minified'] * we want to set the reflected property with the privateName: dataValue[i+1] */ for (let i = 0; i < dataValue.length; i += 3) { setNgReflectProperty(lView, element, type, dataValue[i + 1] as string, value); } } } /** * Resolve the matched directives on a node. */ export function resolveDirectives( tView: TView, lView: LView, tNode: TElementNode | TContainerNode | TElementContainerNode, localRefs: string[] | null, ): void { // Please make sure to have explicit type for `exportsMap`. Inferred type triggers bug in // tsickle. ngDevMode && assertFirstCreatePass(tView); if (getBindingsEnabled()) { const exportsMap: {[key: string]: number} | null = localRefs === null ? null : {'': -1}; const matchResult = findDirectiveDefMatches(tView, tNode); let directiveDefs: DirectiveDef<unknown>[] | null; let hostDirectiveDefs: HostDirectiveDefs | null; if (matchResult === null) { directiveDefs = hostDirectiveDefs = null; } else { [directiveDefs, hostDirectiveDefs] = matchResult; } if (directiveDefs !== null) { initializeDirectives(tView, lView, tNode, directiveDefs, exportsMap, hostDirectiveDefs); } if (exportsMap) cacheMatchingLocalNames(tNode, localRefs, exportsMap); } // Merge the template attrs last so that they have the highest priority. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, tNode.attrs); } /** Initializes the data structures necessary for a list of directives to be instantiated. */ e
{ "end_byte": 41603, "start_byte": 36752, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_41604_49343
port function initializeDirectives( tView: TView, lView: LView<unknown>, tNode: TElementNode | TContainerNode | TElementContainerNode, directives: DirectiveDef<unknown>[], exportsMap: {[key: string]: number} | null, hostDirectiveDefs: HostDirectiveDefs | null, ) { ngDevMode && assertFirstCreatePass(tView); // Publishes the directive types to DI so they can be injected. Needs to // happen in a separate pass before the TNode flags have been initialized. for (let i = 0; i < directives.length; i++) { diPublicInInjector(getOrCreateNodeInjectorForNode(tNode, lView), tView, directives[i].type); } initTNodeFlags(tNode, tView.data.length, directives.length); // When the same token is provided by several directives on the same node, some rules apply in // the viewEngine: // - viewProviders have priority over providers // - the last directive in NgModule.declarations has priority over the previous one // So to match these rules, the order in which providers are added in the arrays is very // important. for (let i = 0; i < directives.length; i++) { const def = directives[i]; if (def.providersResolver) def.providersResolver(def); } let preOrderHooksFound = false; let preOrderCheckHooksFound = false; let directiveIdx = allocExpando(tView, lView, directives.length, null); ngDevMode && assertSame( directiveIdx, tNode.directiveStart, 'TNode.directiveStart should point to just allocated space', ); for (let i = 0; i < directives.length; i++) { const def = directives[i]; // Merge the attrs in the order of matches. This assumes that the first directive is the // component itself, so that the component has the least priority. tNode.mergedAttrs = mergeHostAttrs(tNode.mergedAttrs, def.hostAttrs); configureViewWithDirective(tView, tNode, lView, directiveIdx, def); saveNameToExportMap(directiveIdx, def, exportsMap); if (def.contentQueries !== null) tNode.flags |= TNodeFlags.hasContentQuery; if (def.hostBindings !== null || def.hostAttrs !== null || def.hostVars !== 0) tNode.flags |= TNodeFlags.hasHostBindings; const lifeCycleHooks: Partial<OnChanges & OnInit & DoCheck> = def.type.prototype; // Only push a node index into the preOrderHooks array if this is the first // pre-order hook found on this node. if ( !preOrderHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngOnInit || lifeCycleHooks.ngDoCheck) ) { // We will push the actual hook function into this array later during dir instantiation. // We cannot do it now because we must ensure hooks are registered in the same // order that directives are created (i.e. injection order). (tView.preOrderHooks ??= []).push(tNode.index); preOrderHooksFound = true; } if (!preOrderCheckHooksFound && (lifeCycleHooks.ngOnChanges || lifeCycleHooks.ngDoCheck)) { (tView.preOrderCheckHooks ??= []).push(tNode.index); preOrderCheckHooksFound = true; } directiveIdx++; } initializeInputAndOutputAliases(tView, tNode, hostDirectiveDefs); } /** * Add `hostBindings` to the `TView.hostBindingOpCodes`. * * @param tView `TView` to which the `hostBindings` should be added. * @param tNode `TNode` the element which contains the directive * @param directiveIdx Directive index in view. * @param directiveVarsIdx Where will the directive's vars be stored * @param def `ComponentDef`/`DirectiveDef`, which contains the `hostVars`/`hostBindings` to add. */ export function registerHostBindingOpCodes( tView: TView, tNode: TNode, directiveIdx: number, directiveVarsIdx: number, def: ComponentDef<any> | DirectiveDef<any>, ): void { ngDevMode && assertFirstCreatePass(tView); const hostBindings = def.hostBindings; if (hostBindings) { let hostBindingOpCodes = tView.hostBindingOpCodes; if (hostBindingOpCodes === null) { hostBindingOpCodes = tView.hostBindingOpCodes = [] as any as HostBindingOpCodes; } const elementIndx = ~tNode.index; if (lastSelectedElementIdx(hostBindingOpCodes) != elementIndx) { // Conditionally add select element so that we are more efficient in execution. // NOTE: this is strictly not necessary and it trades code size for runtime perf. // (We could just always add it.) hostBindingOpCodes.push(elementIndx); } hostBindingOpCodes.push(directiveIdx, directiveVarsIdx, hostBindings); } } /** * Returns the last selected element index in the `HostBindingOpCodes` * * For perf reasons we don't need to update the selected element index in `HostBindingOpCodes` only * if it changes. This method returns the last index (or '0' if not found.) * * Selected element index are only the ones which are negative. */ function lastSelectedElementIdx(hostBindingOpCodes: HostBindingOpCodes): number { let i = hostBindingOpCodes.length; while (i > 0) { const value = hostBindingOpCodes[--i]; if (typeof value === 'number' && value < 0) { return value; } } return 0; } /** * Instantiate all the directives that were previously resolved on the current node. */ function instantiateAllDirectives( tView: TView, lView: LView, tNode: TDirectiveHostNode, native: RNode, ) { const start = tNode.directiveStart; const end = tNode.directiveEnd; // The component view needs to be created before creating the node injector // since it is used to inject some special symbols like `ChangeDetectorRef`. if (isComponentHost(tNode)) { ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode); addComponentLogic( lView, tNode as TElementNode, tView.data[start + tNode.componentOffset] as ComponentDef<unknown>, ); } if (!tView.firstCreatePass) { getOrCreateNodeInjectorForNode(tNode, lView); } attachPatchData(native, lView); const initialInputs = tNode.initialInputs; for (let i = start; i < end; i++) { const def = tView.data[i] as DirectiveDef<any>; const directive = getNodeInjectable(lView, tView, i, tNode); attachPatchData(directive, lView); if (initialInputs !== null) { setInputsFromAttrs(lView, i - start, directive, def, tNode, initialInputs!); } if (isComponentDef(def)) { const componentView = getComponentLViewByIndex(tNode.index, lView); componentView[CONTEXT] = getNodeInjectable(lView, tView, i, tNode); } } } export function invokeDirectivesHostBindings(tView: TView, lView: LView, tNode: TNode) { const start = tNode.directiveStart; const end = tNode.directiveEnd; const elementIndex = tNode.index; const currentDirectiveIndex = getCurrentDirectiveIndex(); try { setSelectedIndex(elementIndex); for (let dirIndex = start; dirIndex < end; dirIndex++) { const def = tView.data[dirIndex] as DirectiveDef<unknown>; const directive = lView[dirIndex]; setCurrentDirectiveIndex(dirIndex); if (def.hostBindings !== null || def.hostVars !== 0 || def.hostAttrs !== null) { invokeHostBindingsInCreationMode(def, directive); } } } finally { setSelectedIndex(-1); setCurrentDirectiveIndex(currentDirectiveIndex); } } /** * Invoke the host bindings in creation mode. * * @param def `DirectiveDef` which may contain the `hostBindings` function. * @param directive Instance of directive. */ export function invokeHostBindingsInCreationMode(def: DirectiveDef<any>, directive: any) { if (def.hostBindings !== null) { def.hostBindings!(RenderFlags.Create, directive); } } /** * Matches the current node against all available selectors. * If a component is matched (at most one), it is returned in first position in the array. */ f
{ "end_byte": 49343, "start_byte": 41604, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_49344_57368
nction findDirectiveDefMatches( tView: TView, tNode: TElementNode | TContainerNode | TElementContainerNode, ): [matches: DirectiveDef<unknown>[], hostDirectiveDefs: HostDirectiveDefs | null] | null { ngDevMode && assertFirstCreatePass(tView); ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode | TNodeType.AnyContainer); const registry = tView.directiveRegistry; let matches: DirectiveDef<unknown>[] | null = null; let hostDirectiveDefs: HostDirectiveDefs | null = null; if (registry) { for (let i = 0; i < registry.length; i++) { const def = registry[i] as ComponentDef<any> | DirectiveDef<any>; if (isNodeMatchingSelectorList(tNode, def.selectors!, /* isProjectionMode */ false)) { matches || (matches = []); if (isComponentDef(def)) { if (ngDevMode) { assertTNodeType( tNode, TNodeType.Element, `"${tNode.value}" tags cannot be used as component hosts. ` + `Please use a different tag to activate the ${stringify(def.type)} component.`, ); if (isComponentHost(tNode)) { throwMultipleComponentError(tNode, matches.find(isComponentDef)!.type, def.type); } } // Components are inserted at the front of the matches array so that their lifecycle // hooks run before any directive lifecycle hooks. This appears to be for ViewEngine // compatibility. This logic doesn't make sense with host directives, because it // would allow the host directives to undo any overrides the host may have made. // To handle this case, the host directives of components are inserted at the beginning // of the array, followed by the component. As such, the insertion order is as follows: // 1. Host directives belonging to the selector-matched component. // 2. Selector-matched component. // 3. Host directives belonging to selector-matched directives. // 4. Selector-matched directives. if (def.findHostDirectiveDefs !== null) { const hostDirectiveMatches: DirectiveDef<unknown>[] = []; hostDirectiveDefs = hostDirectiveDefs || new Map(); def.findHostDirectiveDefs(def, hostDirectiveMatches, hostDirectiveDefs); // Add all host directives declared on this component, followed by the component itself. // Host directives should execute first so the host has a chance to override changes // to the DOM made by them. matches.unshift(...hostDirectiveMatches, def); // Component is offset starting from the beginning of the host directives array. const componentOffset = hostDirectiveMatches.length; markAsComponentHost(tView, tNode, componentOffset); } else { // No host directives on this component, just add the // component def to the beginning of the matches. matches.unshift(def); markAsComponentHost(tView, tNode, 0); } } else { // Append any host directives to the matches first. hostDirectiveDefs = hostDirectiveDefs || new Map(); def.findHostDirectiveDefs?.(def, matches, hostDirectiveDefs); matches.push(def); } } } } ngDevMode && matches !== null && assertNoDuplicateDirectives(matches); return matches === null ? null : [matches, hostDirectiveDefs]; } /** * Marks a given TNode as a component's host. This consists of: * - setting the component offset on the TNode. * - storing index of component's host element so it will be queued for view refresh during CD. */ export function markAsComponentHost(tView: TView, hostTNode: TNode, componentOffset: number): void { ngDevMode && assertFirstCreatePass(tView); ngDevMode && assertGreaterThan(componentOffset, -1, 'componentOffset must be great than -1'); hostTNode.componentOffset = componentOffset; (tView.components ??= []).push(hostTNode.index); } /** Caches local names and their matching directive indices for query and template lookups. */ function cacheMatchingLocalNames( tNode: TNode, localRefs: string[] | null, exportsMap: {[key: string]: number}, ): void { if (localRefs) { const localNames: (string | number)[] = (tNode.localNames = []); // Local names must be stored in tNode in the same order that localRefs are defined // in the template to ensure the data is loaded in the same slots as their refs // in the template (for template queries). for (let i = 0; i < localRefs.length; i += 2) { const index = exportsMap[localRefs[i + 1]]; if (index == null) throw new RuntimeError( RuntimeErrorCode.EXPORT_NOT_FOUND, ngDevMode && `Export of name '${localRefs[i + 1]}' not found!`, ); localNames.push(localRefs[i], index); } } } /** * Builds up an export map as directives are created, so local refs can be quickly mapped * to their directive instances. */ function saveNameToExportMap( directiveIdx: number, def: DirectiveDef<any> | ComponentDef<any>, exportsMap: {[key: string]: number} | null, ) { if (exportsMap) { if (def.exportAs) { for (let i = 0; i < def.exportAs.length; i++) { exportsMap[def.exportAs[i]] = directiveIdx; } } if (isComponentDef(def)) exportsMap[''] = directiveIdx; } } /** * Initializes the flags on the current node, setting all indices to the initial index, * the directive count to 0, and adding the isComponent flag. * @param index the initial index */ export function initTNodeFlags(tNode: TNode, index: number, numberOfDirectives: number) { ngDevMode && assertNotEqual( numberOfDirectives, tNode.directiveEnd - tNode.directiveStart, 'Reached the max number of directives', ); tNode.flags |= TNodeFlags.isDirectiveHost; // When the first directive is created on a node, save the index tNode.directiveStart = index; tNode.directiveEnd = index + numberOfDirectives; tNode.providerIndexes = index; } /** * Setup directive for instantiation. * * We need to create a `NodeInjectorFactory` which is then inserted in both the `Blueprint` as well * as `LView`. `TView` gets the `DirectiveDef`. * * @param tView `TView` * @param tNode `TNode` * @param lView `LView` * @param directiveIndex Index where the directive will be stored in the Expando. * @param def `DirectiveDef` */ export function configureViewWithDirective<T>( tView: TView, tNode: TNode, lView: LView, directiveIndex: number, def: DirectiveDef<T>, ): void { ngDevMode && assertGreaterThanOrEqual(directiveIndex, HEADER_OFFSET, 'Must be in Expando section'); tView.data[directiveIndex] = def; const directiveFactory = def.factory || ((def as Writable<DirectiveDef<T>>).factory = getFactoryDef(def.type, true)); // Even though `directiveFactory` will already be using `ɵɵdirectiveInject` in its generated code, // we also want to support `inject()` directly from the directive constructor context so we set // `ɵɵdirectiveInject` as the inject implementation here too. const nodeInjectorFactory = new NodeInjectorFactory( directiveFactory, isComponentDef(def), ɵɵdirectiveInject, ); tView.blueprint[directiveIndex] = nodeInjectorFactory; lView[directiveIndex] = nodeInjectorFactory; registerHostBindingOpCodes( tView, tNode, directiveIndex, allocExpando(tView, lView, def.hostVars, NO_CHANGE), def, ); } /** * Gets the initial set of LView flags based on the component definition that the LView represents. * @param def Component definition from which to determine the flags. */ export function getInitialLViewFlagsFromDef(def: ComponentDef<unknown>): LViewFlags { let flags = LViewFlags.CheckAlways; if (def.signals) { flags = LViewFlags.SignalView; } else if (def.onPush) { flags = LViewFlags.Dirty; } return flags; } functi
{ "end_byte": 57368, "start_byte": 49344, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_57370_65438
addComponentLogic<T>(lView: LView, hostTNode: TElementNode, def: ComponentDef<T>): void { const native = getNativeByTNode(hostTNode, lView) as RElement; const tView = getOrCreateComponentTView(def); // Only component views should be added to the view tree directly. Embedded views are // accessed through their containers because they may be removed / re-added later. const rendererFactory = lView[ENVIRONMENT].rendererFactory; const componentView = addToEndOfViewTree( lView, createLView( lView, tView, null, getInitialLViewFlagsFromDef(def), native, hostTNode as TElementNode, null, rendererFactory.createRenderer(native, def), null, null, null, ), ); // Component view will always be created before any injected LContainers, // so this is a regular element, wrap it with the component view lView[hostTNode.index] = componentView; } export function elementAttributeInternal( tNode: TNode, lView: LView, name: string, value: any, sanitizer: SanitizerFn | null | undefined, namespace: string | null | undefined, ) { if (ngDevMode) { assertNotSame(value, NO_CHANGE as any, 'Incoming value should never be NO_CHANGE.'); validateAgainstEventAttributes(name); assertTNodeType( tNode, TNodeType.Element, `Attempted to set attribute \`${name}\` on a container node. ` + `Host bindings are not valid on ng-container or ng-template.`, ); } const element = getNativeByTNode(tNode, lView) as RElement; setElementAttribute(lView[RENDERER], element, namespace, tNode.value, name, value, sanitizer); } export function setElementAttribute( renderer: Renderer, element: RElement, namespace: string | null | undefined, tagName: string | null, name: string, value: any, sanitizer: SanitizerFn | null | undefined, ) { if (value == null) { ngDevMode && ngDevMode.rendererRemoveAttribute++; renderer.removeAttribute(element, name, namespace); } else { ngDevMode && ngDevMode.rendererSetAttribute++; const strValue = sanitizer == null ? renderStringify(value) : sanitizer(value, tagName || '', name); renderer.setAttribute(element, name, strValue as string, namespace); } } /** * Sets initial input properties on directive instances from attribute data * * @param lView Current LView that is being processed. * @param directiveIndex Index of the directive in directives array * @param instance Instance of the directive on which to set the initial inputs * @param def The directive def that contains the list of inputs * @param tNode The static data for this node */ function setInputsFromAttrs<T>( lView: LView, directiveIndex: number, instance: T, def: DirectiveDef<T>, tNode: TNode, initialInputData: InitialInputData, ): void { const initialInputs: InitialInputs | null = initialInputData![directiveIndex]; if (initialInputs !== null) { for (let i = 0; i < initialInputs.length; ) { const publicName = initialInputs[i++] as string; const privateName = initialInputs[i++] as string; const flags = initialInputs[i++] as InputFlags; const value = initialInputs[i++] as string; writeToDirectiveInput<T>(def, instance, publicName, privateName, flags, value); if (ngDevMode) { const nativeElement = getNativeByTNode(tNode, lView) as RElement; setNgReflectProperty(lView, nativeElement, tNode.type, privateName, value); } } } } /** * Generates initialInputData for a node and stores it in the template's static storage * so subsequent template invocations don't have to recalculate it. * * initialInputData is an array containing values that need to be set as input properties * for directives on this node, but only once on creation. We need this array to support * the case where you set an @Input property of a directive using attribute-like syntax. * e.g. if you have a `name` @Input, you can set it once like this: * * <my-component name="Bess"></my-component> * * @param inputs Input alias map that was generated from the directive def inputs. * @param directiveIndex Index of the directive that is currently being processed. * @param attrs Static attrs on this node. */ function generateInitialInputs( inputs: NodeInputBindings, directiveIndex: number, attrs: TAttributes, ): InitialInputs | null { let inputsToStore: InitialInputs | null = null; let i = 0; while (i < attrs.length) { const attrName = attrs[i]; if (attrName === AttributeMarker.NamespaceURI) { // We do not allow inputs on namespaced attributes. i += 4; continue; } else if (attrName === AttributeMarker.ProjectAs) { // Skip over the `ngProjectAs` value. i += 2; continue; } // If we hit any other attribute markers, we're done anyway. None of those are valid inputs. if (typeof attrName === 'number') break; if (inputs.hasOwnProperty(attrName as string)) { if (inputsToStore === null) inputsToStore = []; // Find the input's public name from the input store. Note that we can be found easier // through the directive def, but we want to do it using the inputs store so that it can // account for host directive aliases. const inputConfig = inputs[attrName as string]; for (let j = 0; j < inputConfig.length; j += 3) { if (inputConfig[j] === directiveIndex) { inputsToStore.push( attrName as string, inputConfig[j + 1] as string, inputConfig[j + 2] as InputFlags, attrs[i + 1] as string, ); // A directive can't have multiple inputs with the same name so we can break here. break; } } } i += 2; } return inputsToStore; } ////////////////////////// //// ViewContainer & View ////////////////////////// /** * Creates a LContainer, either from a container instruction, or for a ViewContainerRef. * * @param hostNative The host element for the LContainer * @param hostTNode The host TNode for the LContainer * @param currentView The parent view of the LContainer * @param native The native comment element * @param isForViewContainerRef Optional a flag indicating the ViewContainerRef case * @returns LContainer */ export function createLContainer( hostNative: RElement | RComment | LView, currentView: LView, native: RComment, tNode: TNode, ): LContainer { ngDevMode && assertLView(currentView); const lContainer: LContainer = [ hostNative, // host native true, // Boolean `true` in this position signifies that this is an `LContainer` 0, // flags currentView, // parent null, // next tNode, // t_host null, // dehydrated views native, // native, null, // view refs null, // moved views ]; ngDevMode && assertEqual( lContainer.length, CONTAINER_HEADER_OFFSET, 'Should allocate correct number of slots for LContainer header.', ); return lContainer; } /** Refreshes all content queries declared by directives in a given view */ export function refreshContentQueries(tView: TView, lView: LView): void { const contentQueries = tView.contentQueries; if (contentQueries !== null) { const prevConsumer = setActiveConsumer(null); try { for (let i = 0; i < contentQueries.length; i += 2) { const queryStartIdx = contentQueries[i]; const directiveDefIdx = contentQueries[i + 1]; if (directiveDefIdx !== -1) { const directiveDef = tView.data[directiveDefIdx] as DirectiveDef<any>; ngDevMode && assertDefined(directiveDef, 'DirectiveDef not found.'); ngDevMode && assertDefined(directiveDef.contentQueries, 'contentQueries function should be defined'); setCurrentQueryIndex(queryStartIdx); directiveDef.contentQueries!(RenderFlags.Update, lView[directiveDefIdx], directiveDefIdx); } } } finally { setActiveConsumer(prevConsumer); } } } /** *
{ "end_byte": 65438, "start_byte": 57370, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/shared.ts_65440_72102
dds LView or LContainer to the end of the current view tree. * * This structure will be used to traverse through nested views to remove listeners * and call onDestroy callbacks. * * @param lView The view where LView or LContainer should be added * @param adjustedHostIndex Index of the view's host node in LView[], adjusted for header * @param lViewOrLContainer The LView or LContainer to add to the view tree * @returns The state passed in */ export function addToEndOfViewTree<T extends LView | LContainer>( lView: LView, lViewOrLContainer: T, ): T { // TODO(benlesh/misko): This implementation is incorrect, because it always adds the LContainer // to the end of the queue, which means if the developer retrieves the LContainers from RNodes out // of order, the change detection will run out of order, as the act of retrieving the the // LContainer from the RNode is what adds it to the queue. if (lView[CHILD_HEAD]) { lView[CHILD_TAIL]![NEXT] = lViewOrLContainer; } else { lView[CHILD_HEAD] = lViewOrLContainer; } lView[CHILD_TAIL] = lViewOrLContainer; return lViewOrLContainer; } /////////////////////////////// //// Change detection /////////////////////////////// export function executeViewQueryFn<T>( flags: RenderFlags, viewQueryFn: ViewQueriesFunction<T>, component: T, ): void { ngDevMode && assertDefined(viewQueryFn, 'View queries function to execute must be defined.'); setCurrentQueryIndex(0); const prevConsumer = setActiveConsumer(null); try { viewQueryFn(flags, component); } finally { setActiveConsumer(prevConsumer); } } /////////////////////////////// //// Bindings & interpolations /////////////////////////////// /** * Stores meta-data for a property binding to be used by TestBed's `DebugElement.properties`. * * In order to support TestBed's `DebugElement.properties` we need to save, for each binding: * - a bound property name; * - a static parts of interpolated strings; * * A given property metadata is saved at the binding's index in the `TView.data` (in other words, a * property binding metadata will be stored in `TView.data` at the same index as a bound value in * `LView`). Metadata are represented as `INTERPOLATION_DELIMITER`-delimited string with the * following format: * - `propertyName` for bound properties; * - `propertyName�prefix�interpolation_static_part1�..interpolation_static_partN�suffix` for * interpolated properties. * * @param tData `TData` where meta-data will be saved; * @param tNode `TNode` that is a target of the binding; * @param propertyName bound property name; * @param bindingIndex binding index in `LView` * @param interpolationParts static interpolation parts (for property interpolations) */ export function storePropertyBindingMetadata( tData: TData, tNode: TNode, propertyName: string, bindingIndex: number, ...interpolationParts: string[] ) { // Binding meta-data are stored only the first time a given property instruction is processed. // Since we don't have a concept of the "first update pass" we need to check for presence of the // binding meta-data to decide if one should be stored (or if was stored already). if (tData[bindingIndex] === null) { if (tNode.inputs == null || !tNode.inputs[propertyName]) { const propBindingIdxs = tNode.propertyBindings || (tNode.propertyBindings = []); propBindingIdxs.push(bindingIndex); let bindingMetadata = propertyName; if (interpolationParts.length > 0) { bindingMetadata += INTERPOLATION_DELIMITER + interpolationParts.join(INTERPOLATION_DELIMITER); } tData[bindingIndex] = bindingMetadata; } } } export function getOrCreateLViewCleanup(view: LView): any[] { // top level variables should not be exported for performance reasons (PERF_NOTES.md) return (view[CLEANUP] ??= []); } export function getOrCreateTViewCleanup(tView: TView): any[] { return (tView.cleanup ??= []); } /** * There are cases where the sub component's renderer needs to be included * instead of the current renderer (see the componentSyntheticHost* instructions). */ export function loadComponentRenderer( currentDef: DirectiveDef<any> | null, tNode: TNode, lView: LView, ): Renderer { // TODO(FW-2043): the `currentDef` is null when host bindings are invoked while creating root // component (see packages/core/src/render3/component.ts). This is not consistent with the process // of creating inner components, when current directive index is available in the state. In order // to avoid relying on current def being `null` (thus special-casing root component creation), the // process of creating root component should be unified with the process of creating inner // components. if (currentDef === null || isComponentDef(currentDef)) { lView = unwrapLView(lView[tNode.index])!; } return lView[RENDERER]; } /** Handles an error thrown in an LView. */ export function handleError(lView: LView, error: any): void { const injector = lView[INJECTOR]; const errorHandler = injector ? injector.get(ErrorHandler, null) : null; errorHandler && errorHandler.handleError(error); } /** * Set the inputs of directives at the current node to corresponding value. * * @param tView The current TView * @param lView the `LView` which contains the directives. * @param inputs mapping between the public "input" name and privately-known, * possibly minified, property names to write to. * @param value Value to set. */ export function setInputsForProperty( tView: TView, lView: LView, inputs: NodeInputBindings[typeof publicName], publicName: string, value: unknown, ): void { for (let i = 0; i < inputs.length; ) { const index = inputs[i++] as number; const privateName = inputs[i++] as string; const flags = inputs[i++] as InputFlags; const instance = lView[index]; ngDevMode && assertIndexInRange(lView, index); const def = tView.data[index] as DirectiveDef<any>; writeToDirectiveInput(def, instance, publicName, privateName, flags, value); } } /** * Updates a text binding at a given index in a given LView. */ export function textBindingInternal(lView: LView, index: number, value: string): void { ngDevMode && assertString(value, 'Value should be a string'); ngDevMode && assertNotSame(value, NO_CHANGE as any, 'value should not be NO_CHANGE'); ngDevMode && assertIndexInRange(lView, index); const element = getNativeByIndex(index, lView) as any as RText; ngDevMode && assertDefined(element, 'native element should exist'); updateTextNode(lView[RENDERER], element, value); }
{ "end_byte": 72102, "start_byte": 65440, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/shared.ts" }
angular/packages/core/src/render3/instructions/element.ts_0_7597
/** * @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 { invalidSkipHydrationHost, validateMatchingNode, validateNodeExists, } from '../../hydration/error_handling'; import {locateNextRNode} from '../../hydration/node_lookup_utils'; import { hasSkipHydrationAttrOnRElement, hasSkipHydrationAttrOnTNode, } from '../../hydration/skip_hydration'; import { getSerializedContainerViews, isDisconnectedNode, markRNodeAsClaimedByHydration, markRNodeAsSkippedByHydration, setSegmentHead, } from '../../hydration/utils'; import {isDetachedByI18n} from '../../i18n/utils'; import {assertDefined, assertEqual, assertIndexInRange} from '../../util/assert'; import {assertFirstCreatePass, assertHasParent} from '../assert'; import {attachPatchData} from '../context_discovery'; import {registerPostOrderHooks} from '../hooks'; import { hasClassInput, hasStyleInput, TAttributes, TElementNode, TNode, TNodeFlags, TNodeType, } from '../interfaces/node'; import {Renderer} from '../interfaces/renderer'; import {RElement} from '../interfaces/renderer_dom'; import {isComponentHost, isContentQueryHost, isDirectiveHost} from '../interfaces/type_checks'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view'; import {assertTNodeType} from '../node_assert'; import { appendChild, clearElementContents, createElementNode, setupStaticAttributes, } from '../node_manipulation'; import { decreaseElementDepthCount, enterSkipHydrationBlock, getBindingIndex, getCurrentTNode, getElementDepthCount, getLView, getNamespace, getTView, increaseElementDepthCount, isCurrentTNodeParent, isInSkipHydrationBlock, isSkipHydrationRootTNode, lastNodeWasCreated, leaveSkipHydrationBlock, setCurrentTNode, setCurrentTNodeAsNotParent, wasLastNodeCreated, } from '../state'; import {computeStaticStyling} from '../styling/static_styling'; import {getConstant} from '../util/view_utils'; import {validateElementIsKnown} from './element_validation'; import {setDirectiveInputsWhichShadowsStyling} from './property'; import { createDirectivesInstances, executeContentQueries, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData, } from './shared'; function elementStartFirstCreatePass( index: number, tView: TView, lView: LView, name: string, attrsIndex?: number | null, localRefsIndex?: number, ): TElementNode { ngDevMode && assertFirstCreatePass(tView); ngDevMode && ngDevMode.firstCreatePass++; const tViewConsts = tView.consts; const attrs = getConstant<TAttributes>(tViewConsts, attrsIndex); const tNode = getOrCreateTNode(tView, index, TNodeType.Element, name, attrs); resolveDirectives(tView, lView, tNode, getConstant<string[]>(tViewConsts, localRefsIndex)); if (tNode.attrs !== null) { computeStaticStyling(tNode, tNode.attrs, false); } if (tNode.mergedAttrs !== null) { computeStaticStyling(tNode, tNode.mergedAttrs, true); } if (tView.queries !== null) { tView.queries.elementStart(tView, tNode); } return tNode; } /** * Create DOM element. The instruction must later be followed by `elementEnd()` call. * * @param index Index of the element in the LView array * @param name Name of the DOM Node * @param attrsIndex Index of the element's attributes in the `consts` array. * @param localRefsIndex Index of the element's local references in the `consts` array. * @returns This function returns itself so that it may be chained. * * Attributes and localRefs are passed as an array of strings where elements with an even index * hold an attribute name and elements with an odd index hold an attribute value, ex.: * ['id', 'warning5', 'class', 'alert'] * * @codeGenApi */ export function ɵɵelementStart( index: number, name: string, attrsIndex?: number | null, localRefsIndex?: number, ): typeof ɵɵelementStart { const lView = getLView(); const tView = getTView(); const adjustedIndex = HEADER_OFFSET + index; ngDevMode && assertEqual( getBindingIndex(), tView.bindingStartIndex, 'elements should be created before any bindings', ); ngDevMode && assertIndexInRange(lView, adjustedIndex); const renderer = lView[RENDERER]; const tNode = tView.firstCreatePass ? elementStartFirstCreatePass(adjustedIndex, tView, lView, name, attrsIndex, localRefsIndex) : (tView.data[adjustedIndex] as TElementNode); const native = _locateOrCreateElementNode(tView, lView, tNode, renderer, name, index); lView[adjustedIndex] = native; const hasDirectives = isDirectiveHost(tNode); if (ngDevMode && tView.firstCreatePass) { validateElementIsKnown(native, lView, tNode.value, tView.schemas, hasDirectives); } setCurrentTNode(tNode, true); setupStaticAttributes(renderer, native, tNode); if (!isDetachedByI18n(tNode) && wasLastNodeCreated()) { // In the i18n case, the translation may have removed this element, so only add it if it is not // detached. See `TNodeType.Placeholder` and `LFrame.inI18n` for more context. appendChild(tView, lView, native, tNode); } // any immediate children of a component or template container must be pre-emptively // monkey-patched with the component view data so that the element can be inspected // later on using any element discovery utility methods (see `element_discovery.ts`) if (getElementDepthCount() === 0) { attachPatchData(native, lView); } increaseElementDepthCount(); if (hasDirectives) { createDirectivesInstances(tView, lView, tNode); executeContentQueries(tView, tNode, lView); } if (localRefsIndex !== null) { saveResolvedLocalsInData(lView, tNode); } return ɵɵelementStart; } /** * Mark the end of the element. * @returns This function returns itself so that it may be chained. * * @codeGenApi */ export function ɵɵelementEnd(): typeof ɵɵelementEnd { let currentTNode = getCurrentTNode()!; ngDevMode && assertDefined(currentTNode, 'No parent node to close.'); if (isCurrentTNodeParent()) { setCurrentTNodeAsNotParent(); } else { ngDevMode && assertHasParent(getCurrentTNode()); currentTNode = currentTNode.parent!; setCurrentTNode(currentTNode, false); } const tNode = currentTNode; ngDevMode && assertTNodeType(tNode, TNodeType.AnyRNode); if (isSkipHydrationRootTNode(tNode)) { leaveSkipHydrationBlock(); } decreaseElementDepthCount(); const tView = getTView(); if (tView.firstCreatePass) { registerPostOrderHooks(tView, currentTNode); if (isContentQueryHost(currentTNode)) { tView.queries!.elementEnd(currentTNode); } } if (tNode.classesWithoutHost != null && hasClassInput(tNode)) { setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.classesWithoutHost, true); } if (tNode.stylesWithoutHost != null && hasStyleInput(tNode)) { setDirectiveInputsWhichShadowsStyling(tView, tNode, getLView(), tNode.stylesWithoutHost, false); } return ɵɵelementEnd; } /** * Creates an empty element using {@link elementStart} and {@link elementEnd} * * @param index Index of the element in the data array * @param name Name of the DOM Node * @param attrsIndex Index of the element's attributes in the `consts` array. * @param localRefsIndex Index of the element's local references in the `consts` array. * @returns This function returns itself so that it may be chained. * * @codeGenApi */ export func
{ "end_byte": 7597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/element.ts" }
angular/packages/core/src/render3/instructions/element.ts_7598_10852
ion ɵɵelement( index: number, name: string, attrsIndex?: number | null, localRefsIndex?: number, ): typeof ɵɵelement { ɵɵelementStart(index, name, attrsIndex, localRefsIndex); ɵɵelementEnd(); return ɵɵelement; } let _locateOrCreateElementNode: typeof locateOrCreateElementNodeImpl = ( tView: TView, lView: LView, tNode: TNode, renderer: Renderer, name: string, index: number, ) => { lastNodeWasCreated(true); return createElementNode(renderer, name, getNamespace()); }; /** * Enables hydration code path (to lookup existing elements in DOM) * in addition to the regular creation mode of element nodes. */ function locateOrCreateElementNodeImpl( tView: TView, lView: LView, tNode: TNode, renderer: Renderer, name: string, index: number, ): RElement { const hydrationInfo = lView[HYDRATION]; const isNodeCreationMode = !hydrationInfo || isInSkipHydrationBlock() || isDetachedByI18n(tNode) || isDisconnectedNode(hydrationInfo, index); lastNodeWasCreated(isNodeCreationMode); // Regular creation mode. if (isNodeCreationMode) { return createElementNode(renderer, name, getNamespace()); } // Hydration mode, looking up an existing element in DOM. const native = locateNextRNode<RElement>(hydrationInfo, tView, lView, tNode)!; ngDevMode && validateMatchingNode(native, Node.ELEMENT_NODE, name, lView, tNode); ngDevMode && markRNodeAsClaimedByHydration(native); // This element might also be an anchor of a view container. if (getSerializedContainerViews(hydrationInfo, index)) { // Important note: this element acts as an anchor, but it's **not** a part // of the embedded view, so we start the segment **after** this element, taking // a reference to the next sibling. For example, the following template: // `<div #vcrTarget>` is represented in the DOM as `<div></div>...<!--container-->`, // so while processing a `<div>` instruction, point to the next sibling as a // start of a segment. ngDevMode && validateNodeExists(native.nextSibling, lView, tNode); setSegmentHead(hydrationInfo, index, native.nextSibling); } // Checks if the skip hydration attribute is present during hydration so we know to // skip attempting to hydrate this block. We check both TNode and RElement for an // attribute: the RElement case is needed for i18n cases, when we add it to host // elements during the annotation phase (after all internal data structures are setup). if ( hydrationInfo && (hasSkipHydrationAttrOnTNode(tNode) || hasSkipHydrationAttrOnRElement(native)) ) { if (isComponentHost(tNode)) { enterSkipHydrationBlock(tNode); // Since this isn't hydratable, we need to empty the node // so there's no duplicate content after render clearElementContents(native); ngDevMode && markRNodeAsSkippedByHydration(native); } else if (ngDevMode) { // If this is not a component host, throw an error. // Hydration can be skipped on per-component basis only. throw invalidSkipHydrationHost(native); } } return native; } export function enableLocateOrCreateElementNodeImpl() { _locateOrCreateElementNode = locateOrCreateElementNodeImpl; }
{ "end_byte": 10852, "start_byte": 7598, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/element.ts" }
angular/packages/core/src/render3/instructions/component_instance.ts_0_892
/*! * @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 {assertDefined} from '../../util/assert'; import {CONTEXT, DECLARATION_COMPONENT_VIEW} from '../interfaces/view'; import {getLView} from '../state'; /** * Instruction that returns the component instance in which the current instruction is executing. * This is a constant-time version of `nextContent` for the case where we know that we need the * component instance specifically, rather than the context of a particular template. * * @codeGenApi */ export function ɵɵcomponentInstance(): unknown { const instance = getLView()[DECLARATION_COMPONENT_VIEW][CONTEXT]; ngDevMode && assertDefined(instance, 'Expected component instance to be defined'); return instance; }
{ "end_byte": 892, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/component_instance.ts" }
angular/packages/core/src/render3/instructions/all.ts_0_2243
/** * @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 */ /* * This file re-exports all symbols contained in this directory. * * Why is this file not `index.ts`? * * There seems to be an inconsistent path resolution of an `index.ts` file * when only the parent directory is referenced. This could be due to the * node module resolution configuration differing from rollup and/or typescript. * * With commit * https://github.com/angular/angular/commit/d5e3f2c64bd13ce83e7c70788b7fc514ca4a9918 * the `instructions.ts` file was moved to `instructions/instructions.ts` and an * `index.ts` file was used to re-export everything. Having had file names that were * importing from `instructions' directly (not the from the sub file or the `index.ts` * file) caused strange CI issues. `index.ts` had to be renamed to `all.ts` for this * to work. * * Jira Issue = FW-1184 */ export * from '../../defer/instructions'; export * from './advance'; export * from './attribute'; export * from './attribute_interpolation'; export * from './change_detection'; export * from './class_map_interpolation'; export * from './component_instance'; export * from './control_flow'; export * from './di'; export * from './di_attr'; export * from './element'; export * from './element_container'; export { ɵgetUnknownElementStrictMode, ɵgetUnknownPropertyStrictMode, ɵsetUnknownElementStrictMode, ɵsetUnknownPropertyStrictMode, } from './element_validation'; export * from './get_current_view'; export * from './host_property'; export * from './i18n'; export * from './listener'; export * from './namespace'; export * from './next_context'; export * from './projection'; export * from './property'; export * from './property_interpolation'; export * from './queries'; export * from './queries_signals'; export * from './storage'; export * from './style_map_interpolation'; export * from './style_prop_interpolation'; export * from './styling'; export * from './template'; export * from './text'; export * from './text_interpolation'; export * from './two_way'; export * from './let_declaration';
{ "end_byte": 2243, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/all.ts" }
angular/packages/core/src/render3/instructions/property_interpolation.ts_0_7615
/** * @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 {SanitizerFn} from '../interfaces/sanitization'; import {RENDERER} from '../interfaces/view'; import {getBindingIndex, getLView, getSelectedTNode, getTView} from '../state'; import {NO_CHANGE} from '../tokens'; import { interpolation1, interpolation2, interpolation3, interpolation4, interpolation5, interpolation6, interpolation7, interpolation8, interpolationV, } from './interpolation'; import {elementPropertyInternal, storePropertyBindingMetadata} from './shared'; /** * * Update an interpolated property on an element with a lone bound value * * Used when the value passed to a property has 1 interpolated value in it, an no additional text * surrounds that interpolated value: * * ```html * <div title="{{v0}}"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate('title', v0); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate( propName: string, v0: any, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate { ɵɵpropertyInterpolate1(propName, '', v0, '', sanitizer); return ɵɵpropertyInterpolate; } /** * * Update an interpolated property on an element with single bound value surrounded by text. * * Used when the value passed to a property has 1 interpolated value in it: * * ```html * <div title="prefix{{v0}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate1('title', 'prefix', v0, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate1( propName: string, prefix: string, v0: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate1 { const lView = getLView(); const interpolatedValue = interpolation1(lView, prefix, v0, suffix); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 1, prefix, suffix, ); } return ɵɵpropertyInterpolate1; } /** * * Update an interpolated property on an element with 2 bound values surrounded by text. * * Used when the value passed to a property has 2 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate2('title', 'prefix', v0, '-', v1, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate2( propName: string, prefix: string, v0: any, i0: string, v1: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate2 { const lView = getLView(); const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 2, prefix, i0, suffix, ); } return ɵɵpropertyInterpolate2; } /** * * Update an interpolated property on an element with 3 bound values surrounded by text. * * Used when the value passed to a property has 3 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate3( * 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate3( propName: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate3 { const lView = getLView(); const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 3, prefix, i0, i1, suffix, ); } return ɵɵpropertyInterpolate3; } /** * * Update an interpolated
{ "end_byte": 7615, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/property_interpolation.ts" }
angular/packages/core/src/render3/instructions/property_interpolation.ts_7617_13778
roperty on an element with 4 bound values surrounded by text. * * Used when the value passed to a property has 4 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate4( * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate4( propName: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate4 { const lView = getLView(); const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 4, prefix, i0, i1, i2, suffix, ); } return ɵɵpropertyInterpolate4; } /** * * Update an interpolated property on an element with 5 bound values surrounded by text. * * Used when the value passed to a property has 5 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate5( * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate5( propName: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate5 { const lView = getLView(); const interpolatedValue = interpolation5( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, suffix, ); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 5, prefix, i0, i1, i2, i3, suffix, ); } return ɵɵpropertyInterpolate5; } /** * * Update an interpolated property on an element with 6 bound values surrounded by text. * * Used when the value passed to a property has 6 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate6( * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate6( propName:
{ "end_byte": 13778, "start_byte": 7617, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/property_interpolation.ts" }
angular/packages/core/src/render3/instructions/property_interpolation.ts_13779_20492
string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate6 { const lView = getLView(); const interpolatedValue = interpolation6( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, suffix, ); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 6, prefix, i0, i1, i2, i3, i4, suffix, ); } return ɵɵpropertyInterpolate6; } /** * * Update an interpolated property on an element with 7 bound values surrounded by text. * * Used when the value passed to a property has 7 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate7( * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param i5 Static value used for concatenation only. * @param v6 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate7( propName: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate7 { const lView = getLView(); const interpolatedValue = interpolation7( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, suffix, ); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 7, prefix, i0, i1, i2, i3, i4, i5, suffix, ); } return ɵɵpropertyInterpolate7; } /** * * Update an interpolated property on an element with 8 bound values surrounded by text. * * Used when the value passed to a property has 8 interpolated values in it: * * ```html * <div title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolate8( * 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix'); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update * @param prefix Static value used for concatenation only. * @param v0 Value checked for change. * @param i0 Static value used for concatenation only. * @param v1 Value checked for change. * @param i1 Static value used for concatenation only. * @param v2 Value checked for change. * @param i2 Static value used for concatenation only. * @param v3 Value checked for change. * @param i3 Static value used for concatenation only. * @param v4 Value checked for change. * @param i4 Static value used for concatenation only. * @param v5 Value checked for change. * @param i5 Static value used for concatenation only. * @param v6 Value checked for change. * @param i6 Static value used for concatenation only. * @param v7 Value checked for change. * @param suffix Static value used for concatenation only. * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolate8( propName: string, prefix: string, v0: any, i0: string, v1: any, i1: string, v2: any, i2: string, v3: any, i3: string, v4: any, i4: string, v5: any, i5: string, v6: any, i6: string, v7: any, suffix: string, sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolate8 { const lView = getLView(); const interpolatedValue = interpolation8( lView, prefix, v0, i0, v1, i1, v2, i2, v3, i3, v4, i4, v5, i5, v6, i6, v7, suffix, ); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); ngDevMode && storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - 8, prefix, i0, i1, i2, i3, i4, i5, i6, suffix, ); } return ɵɵpropertyInterpolate8; } /** * Update an interpolated property on an element with 9 or more boun
{ "end_byte": 20492, "start_byte": 13779, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/property_interpolation.ts" }
angular/packages/core/src/render3/instructions/property_interpolation.ts_20494_22616
values surrounded by text. * * Used when the number of interpolated values exceeds 8. * * ```html * <div * title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix"></div> * ``` * * Its compiled representation is:: * * ```ts * ɵɵpropertyInterpolateV( * 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9, * 'suffix']); * ``` * * If the property name also exists as an input property on one of the element's directives, * the component property will be set instead of the element property. This check must * be conducted at runtime so child components that add new `@Inputs` don't have to be re-compiled. * * @param propName The name of the property to update. * @param values The collection of values and the strings in between those values, beginning with a * string prefix and ending with a string suffix. * (e.g. `['prefix', value0, '-', value1, '-', value2, ..., value99, 'suffix']`) * @param sanitizer An optional sanitizer function * @returns itself, so that it may be chained. * @codeGenApi */ export function ɵɵpropertyInterpolateV( propName: string, values: any[], sanitizer?: SanitizerFn, ): typeof ɵɵpropertyInterpolateV { const lView = getLView(); const interpolatedValue = interpolationV(lView, values); if (interpolatedValue !== NO_CHANGE) { const tView = getTView(); const tNode = getSelectedTNode(); elementPropertyInternal( tView, tNode, lView, propName, interpolatedValue, lView[RENDERER], sanitizer, false, ); if (ngDevMode) { const interpolationInBetween = [values[0]]; // prefix for (let i = 2; i < values.length; i += 2) { interpolationInBetween.push(values[i]); } storePropertyBindingMetadata( tView.data, tNode, propName, getBindingIndex() - interpolationInBetween.length + 1, ...interpolationInBetween, ); } } return ɵɵpropertyInterpolateV; }
{ "end_byte": 22616, "start_byte": 20494, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/property_interpolation.ts" }
angular/packages/core/src/render3/instructions/styling.ts_0_7940
/** * @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 {SafeValue, unwrapSafeValue} from '../../sanitization/bypass'; import {KeyValueArray, keyValueArrayGet, keyValueArraySet} from '../../util/array_utils'; import { assertDefined, assertEqual, assertLessThan, assertNotEqual, throwError, } from '../../util/assert'; import {EMPTY_ARRAY} from '../../util/empty'; import {concatStringsWithSpace, stringify} from '../../util/stringify'; import {assertFirstUpdatePass} from '../assert'; import {bindingUpdated} from '../bindings'; import {AttributeMarker} from '../interfaces/attribute_marker'; import {DirectiveDef} from '../interfaces/definition'; import {TAttributes, TNode, TNodeFlags, TNodeType} from '../interfaces/node'; import {Renderer} from '../interfaces/renderer'; import {RElement} from '../interfaces/renderer_dom'; import { getTStylingRangeNext, getTStylingRangeNextDuplicate, getTStylingRangePrev, getTStylingRangePrevDuplicate, TStylingKey, TStylingRange, } from '../interfaces/styling'; import {LView, RENDERER, TData, TView} from '../interfaces/view'; import {applyStyling} from '../node_manipulation'; import { getCurrentDirectiveDef, getLView, getSelectedIndex, getTView, incrementBindingIndex, } from '../state'; import {insertTStylingBinding} from '../styling/style_binding_list'; import { getLastParsedKey, getLastParsedValue, parseClassName, parseClassNameNext, parseStyle, parseStyleNext, } from '../styling/styling_parser'; import {NO_CHANGE} from '../tokens'; import {getNativeByIndex} from '../util/view_utils'; import {setDirectiveInputsWhichShadowsStyling} from './property'; /** * Update a style binding on an element with the provided value. * * If the style value is falsy then it will be removed from the element * (or assigned a different value depending if there are any styles placed * on the element with `styleMap` or any static styles that are * present from when the element was created with `styling`). * * Note that the styling element is updated as part of `stylingApply`. * * @param prop A valid CSS property. * @param value New value to write (`null` or an empty string to remove). * @param suffix Optional suffix. Used with scalar values to add unit such as `px`. * * Note that this will apply the provided style value to the host element if this function is called * within a host binding function. * * @codeGenApi */ export function ɵɵstyleProp( prop: string, value: string | number | SafeValue | undefined | null, suffix?: string | null, ): typeof ɵɵstyleProp { checkStylingProperty(prop, value, suffix, false); return ɵɵstyleProp; } /** * Update a class binding on an element with the provided value. * * This instruction is meant to handle the `[class.foo]="exp"` case and, * therefore, the class binding itself must already be allocated using * `styling` within the creation block. * * @param prop A valid CSS class (only one). * @param value A true/false value which will turn the class on or off. * * Note that this will apply the provided class value to the host element if this function * is called within a host binding function. * * @codeGenApi */ export function ɵɵclassProp( className: string, value: boolean | undefined | null, ): typeof ɵɵclassProp { checkStylingProperty(className, value, null, true); return ɵɵclassProp; } /** * Update style bindings using an object literal on an element. * * This instruction is meant to apply styling via the `[style]="exp"` template bindings. * When styles are applied to the element they will then be updated with respect to * any styles/classes set via `styleProp`. If any styles are set to falsy * then they will be removed from the element. * * Note that the styling instruction will not be applied until `stylingApply` is called. * * @param styles A key/value style map of the styles that will be applied to the given element. * Any missing styles (that have already been applied to the element beforehand) will be * removed (unset) from the element's styling. * * Note that this will apply the provided styleMap value to the host element if this function * is called within a host binding. * * @codeGenApi */ export function ɵɵstyleMap(styles: {[styleName: string]: any} | string | undefined | null): void { checkStylingMap(styleKeyValueArraySet, styleStringParser, styles, false); } /** * Parse text as style and add values to KeyValueArray. * * This code is pulled out to a separate function so that it can be tree shaken away if it is not * needed. It is only referenced from `ɵɵstyleMap`. * * @param keyValueArray KeyValueArray to add parsed values to. * @param text text to parse. */ export function styleStringParser(keyValueArray: KeyValueArray<any>, text: string): void { for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i)) { styleKeyValueArraySet(keyValueArray, getLastParsedKey(text), getLastParsedValue(text)); } } /** * Update class bindings using an object literal or class-string on an element. * * This instruction is meant to apply styling via the `[class]="exp"` template bindings. * When classes are applied to the element they will then be updated with * respect to any styles/classes set via `classProp`. If any * classes are set to falsy then they will be removed from the element. * * Note that the styling instruction will not be applied until `stylingApply` is called. * Note that this will the provided classMap value to the host element if this function is called * within a host binding. * * @param classes A key/value map or string of CSS classes that will be added to the * given element. Any missing classes (that have already been applied to the element * beforehand) will be removed (unset) from the element's list of CSS classes. * * @codeGenApi */ export function ɵɵclassMap( classes: {[className: string]: boolean | undefined | null} | string | undefined | null, ): void { checkStylingMap(classKeyValueArraySet, classStringParser, classes, true); } /** * Parse text as class and add values to KeyValueArray. * * This code is pulled out to a separate function so that it can be tree shaken away if it is not * needed. It is only referenced from `ɵɵclassMap`. * * @param keyValueArray KeyValueArray to add parsed values to. * @param text text to parse. */ export function classStringParser(keyValueArray: KeyValueArray<any>, text: string): void { for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) { keyValueArraySet(keyValueArray, getLastParsedKey(text), true); } } /** * Common code between `ɵɵclassProp` and `ɵɵstyleProp`. * * @param prop property name. * @param value binding value. * @param suffix suffix for the property (e.g. `em` or `px`) * @param isClassBased `true` if `class` change (`false` if `style`) */ export function checkStylingProperty( prop: string, value: any | NO_CHANGE, suffix: string | undefined | null, isClassBased: boolean, ): void { const lView = getLView(); const tView = getTView(); // Styling instructions use 2 slots per binding. // 1. one for the value / TStylingKey // 2. one for the intermittent-value / TStylingRange const bindingIndex = incrementBindingIndex(2); if (tView.firstUpdatePass) { stylingFirstUpdatePass(tView, prop, bindingIndex, isClassBased); } if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) { const tNode = tView.data[getSelectedIndex()] as TNode; updateStyling( tView, tNode, lView, lView[RENDERER], prop, (lView[bindingIndex + 1] = normalizeSuffix(value, suffix)), isClassBased, bindingIndex, ); } } /** * Common code bet
{ "end_byte": 7940, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts" }
angular/packages/core/src/render3/instructions/styling.ts_7942_14220
en `ɵɵclassMap` and `ɵɵstyleMap`. * * @param keyValueArraySet (See `keyValueArraySet` in "util/array_utils") Gets passed in as a * function so that `style` can be processed. This is done for tree shaking purposes. * @param stringParser Parser used to parse `value` if `string`. (Passed in as `style` and `class` * have different parsers.) * @param value bound value from application * @param isClassBased `true` if `class` change (`false` if `style`) */ export function checkStylingMap( keyValueArraySet: (keyValueArray: KeyValueArray<any>, key: string, value: any) => void, stringParser: (styleKeyValueArray: KeyValueArray<any>, text: string) => void, value: any | NO_CHANGE, isClassBased: boolean, ): void { const tView = getTView(); const bindingIndex = incrementBindingIndex(2); if (tView.firstUpdatePass) { stylingFirstUpdatePass(tView, null, bindingIndex, isClassBased); } const lView = getLView(); if (value !== NO_CHANGE && bindingUpdated(lView, bindingIndex, value)) { // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the // if so as not to read unnecessarily. const tNode = tView.data[getSelectedIndex()] as TNode; if (hasStylingInputShadow(tNode, isClassBased) && !isInHostBindings(tView, bindingIndex)) { if (ngDevMode) { // verify that if we are shadowing then `TData` is appropriately marked so that we skip // processing this binding in styling resolution. const tStylingKey = tView.data[bindingIndex]; assertEqual( Array.isArray(tStylingKey) ? tStylingKey[1] : tStylingKey, false, "Styling linked list shadow input should be marked as 'false'", ); } // VE does not concatenate the static portion like we are doing here. // Instead VE just ignores the static completely if dynamic binding is present. // Because of locality we have already set the static portion because we don't know if there // is a dynamic portion until later. If we would ignore the static portion it would look like // the binding has removed it. This would confuse `[ngStyle]`/`[ngClass]` to do the wrong // thing as it would think that the static portion was removed. For this reason we // concatenate it so that `[ngStyle]`/`[ngClass]` can continue to work on changed. let staticPrefix = isClassBased ? tNode.classesWithoutHost : tNode.stylesWithoutHost; ngDevMode && isClassBased === false && staticPrefix !== null && assertEqual(staticPrefix.endsWith(';'), true, "Expecting static portion to end with ';'"); if (staticPrefix !== null) { // We want to make sure that falsy values of `value` become empty strings. value = concatStringsWithSpace(staticPrefix, value ? value : ''); } // Given `<div [style] my-dir>` such that `my-dir` has `@Input('style')`. // This takes over the `[style]` binding. (Same for `[class]`) setDirectiveInputsWhichShadowsStyling(tView, tNode, lView, value, isClassBased); } else { updateStylingMap( tView, tNode, lView, lView[RENDERER], lView[bindingIndex + 1], (lView[bindingIndex + 1] = toStylingKeyValueArray(keyValueArraySet, stringParser, value)), isClassBased, bindingIndex, ); } } } /** * Determines when the binding is in `hostBindings` section * * @param tView Current `TView` * @param bindingIndex index of binding which we would like if it is in `hostBindings` */ function isInHostBindings(tView: TView, bindingIndex: number): boolean { // All host bindings are placed after the expando section. return bindingIndex >= tView.expandoStartIndex; } /** * Collects the necessary information to insert the binding into a linked list of style bindings * using `insertTStylingBinding`. * * @param tView `TView` where the binding linked list will be stored. * @param tStylingKey Property/key of the binding. * @param bindingIndex Index of binding associated with the `prop` * @param isClassBased `true` if `class` change (`false` if `style`) */ function stylingFirstUpdatePass( tView: TView, tStylingKey: TStylingKey, bindingIndex: number, isClassBased: boolean, ): void { ngDevMode && assertFirstUpdatePass(tView); const tData = tView.data; if (tData[bindingIndex + 1] === null) { // The above check is necessary because we don't clear first update pass until first successful // (no exception) template execution. This prevents the styling instruction from double adding // itself to the list. // `getSelectedIndex()` should be here (rather than in instruction) so that it is guarded by the // if so as not to read unnecessarily. const tNode = tData[getSelectedIndex()] as TNode; ngDevMode && assertDefined(tNode, 'TNode expected'); const isHostBindings = isInHostBindings(tView, bindingIndex); if (hasStylingInputShadow(tNode, isClassBased) && tStylingKey === null && !isHostBindings) { // `tStylingKey === null` implies that we are either `[style]` or `[class]` binding. // If there is a directive which uses `@Input('style')` or `@Input('class')` than // we need to neutralize this binding since that directive is shadowing it. // We turn this into a noop by setting the key to `false` tStylingKey = false; } tStylingKey = wrapInStaticStylingKey(tData, tNode, tStylingKey, isClassBased); insertTStylingBinding(tData, tNode, tStylingKey, bindingIndex, isHostBindings, isClassBased); } } /** * Adds static styling information to the binding if applicable. * * The linked list of styles not only stores the list and keys, but also stores static styling * information on some of the keys. This function determines if the key should contain the styling * information and computes it. * * See `TStylingStatic` for more details. * * @param tData `TData` where the linked list is stored. * @param tNode `TNode` for which the styling is being computed. * @param stylingKey `TStylingKeyPrimitive` which may need to be wrapped into `TStylingKey` * @param isClassBased `true` if `class` (`false` if `style`) */ export function wrapInStati
{ "end_byte": 14220, "start_byte": 7942, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts" }