_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/src/render3/instructions/styling.ts_14221_21905 | StylingKey(
tData: TData,
tNode: TNode,
stylingKey: TStylingKey,
isClassBased: boolean,
): TStylingKey {
const hostDirectiveDef = getCurrentDirectiveDef(tData);
let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
if (hostDirectiveDef === null) {
// We are in template node.
// If template node already had styling instruction then it has already collected the static
// styling and there is no need to collect them again. We know that we are the first styling
// instruction because the `TNode.*Bindings` points to 0 (nothing has been inserted yet).
const isFirstStylingInstructionInTemplate =
((isClassBased ? tNode.classBindings : tNode.styleBindings) as any as number) === 0;
if (isFirstStylingInstructionInTemplate) {
// It would be nice to be able to get the statics from `mergeAttrs`, however, at this point
// they are already merged and it would not be possible to figure which property belongs where
// in the priority.
stylingKey = collectStylingFromDirectives(null, tData, tNode, stylingKey, isClassBased);
stylingKey = collectStylingFromTAttrs(stylingKey, tNode.attrs, isClassBased);
// We know that if we have styling binding in template we can't have residual.
residual = null;
}
} else {
// We are in host binding node and there was no binding instruction in template node.
// This means that we need to compute the residual.
const directiveStylingLast = tNode.directiveStylingLast;
const isFirstStylingInstructionInHostBinding =
directiveStylingLast === -1 || tData[directiveStylingLast] !== hostDirectiveDef;
if (isFirstStylingInstructionInHostBinding) {
stylingKey = collectStylingFromDirectives(
hostDirectiveDef,
tData,
tNode,
stylingKey,
isClassBased,
);
if (residual === null) {
// - If `null` than either:
// - Template styling instruction already ran and it has consumed the static
// styling into its `TStylingKey` and so there is no need to update residual. Instead
// we need to update the `TStylingKey` associated with the first template node
// instruction. OR
// - Some other styling instruction ran and determined that there are no residuals
let templateStylingKey = getTemplateHeadTStylingKey(tData, tNode, isClassBased);
if (templateStylingKey !== undefined && Array.isArray(templateStylingKey)) {
// Only recompute if `templateStylingKey` had static values. (If no static value found
// then there is nothing to do since this operation can only produce less static keys, not
// more.)
templateStylingKey = collectStylingFromDirectives(
null,
tData,
tNode,
templateStylingKey[1] /* unwrap previous statics */,
isClassBased,
);
templateStylingKey = collectStylingFromTAttrs(
templateStylingKey,
tNode.attrs,
isClassBased,
);
setTemplateHeadTStylingKey(tData, tNode, isClassBased, templateStylingKey);
}
} else {
// We only need to recompute residual if it is not `null`.
// - If existing residual (implies there was no template styling). This means that some of
// the statics may have moved from the residual to the `stylingKey` and so we have to
// recompute.
// - If `undefined` this is the first time we are running.
residual = collectResidual(tData, tNode, isClassBased);
}
}
}
if (residual !== undefined) {
isClassBased ? (tNode.residualClasses = residual) : (tNode.residualStyles = residual);
}
return stylingKey;
}
/**
* Retrieve the `TStylingKey` for the template styling instruction.
*
* This is needed since `hostBinding` styling instructions are inserted after the template
* instruction. While the template instruction needs to update the residual in `TNode` the
* `hostBinding` instructions need to update the `TStylingKey` of the template instruction because
* the template instruction is downstream from the `hostBindings` instructions.
*
* @param tData `TData` where the linked list is stored.
* @param tNode `TNode` for which the styling is being computed.
* @param isClassBased `true` if `class` (`false` if `style`)
* @return `TStylingKey` if found or `undefined` if not found.
*/
function getTemplateHeadTStylingKey(
tData: TData,
tNode: TNode,
isClassBased: boolean,
): TStylingKey | undefined {
const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
if (getTStylingRangeNext(bindings) === 0) {
// There does not seem to be a styling instruction in the `template`.
return undefined;
}
return tData[getTStylingRangePrev(bindings)] as TStylingKey;
}
/**
* Update the `TStylingKey` of the first template instruction in `TNode`.
*
* Logically `hostBindings` styling instructions are of lower priority than that of the template.
* However, they execute after the template styling instructions. This means that they get inserted
* in front of the template styling instructions.
*
* If we have a template styling instruction and a new `hostBindings` styling instruction is
* executed it means that it may need to steal static fields from the template instruction. This
* method allows us to update the first template instruction `TStylingKey` with a new value.
*
* Assume:
* ```
* <div my-dir style="color: red" [style.color]="tmplExp"></div>
*
* @Directive({
* host: {
* 'style': 'width: 100px',
* '[style.color]': 'dirExp',
* }
* })
* class MyDir {}
* ```
*
* when `[style.color]="tmplExp"` executes it creates this data structure.
* ```
* ['', 'color', 'color', 'red', 'width', '100px'],
* ```
*
* The reason for this is that the template instruction does not know if there are styling
* instructions and must assume that there are none and must collect all of the static styling.
* (both
* `color' and 'width`)
*
* When `'[style.color]': 'dirExp',` executes we need to insert a new data into the linked list.
* ```
* ['', 'color', 'width', '100px'], // newly inserted
* ['', 'color', 'color', 'red', 'width', '100px'], // this is wrong
* ```
*
* Notice that the template statics is now wrong as it incorrectly contains `width` so we need to
* update it like so:
* ```
* ['', 'color', 'width', '100px'],
* ['', 'color', 'color', 'red'], // UPDATE
* ```
*
* @param tData `TData` where the linked list is stored.
* @param tNode `TNode` for which the styling is being computed.
* @param isClassBased `true` if `class` (`false` if `style`)
* @param tStylingKey New `TStylingKey` which is replacing the old one.
*/
function setTemplateHeadTStylingKey(
tData: TData,
tNode: TNode,
isClassBased: boolean,
tStylingKey: TStylingKey,
): void {
const bindings = isClassBased ? tNode.classBindings : tNode.styleBindings;
ngDevMode &&
assertNotEqual(
getTStylingRangeNext(bindings),
0,
'Expecting to have at least one template styling binding.',
);
tData[getTStylingRangePrev(bindings)] = tStylingKey;
}
/**
* Collect all static values after the current `TNode.directiveStylingLast` index.
*
* Collect the remaining styling information which has not yet been collected by an existing
* styling instruction.
*
* @param tData `TData` where the `DirectiveDefs` are stored.
* @param tNode `TNode` which contains the directive range.
* @param isClassBased `true` if `class` (`false` if `style`)
*/
function collectResidual(
| {
"end_byte": 21905,
"start_byte": 14221,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts"
} |
angular/packages/core/src/render3/instructions/styling.ts_21906_29899 | tData: TData,
tNode: TNode,
isClassBased: boolean,
): KeyValueArray<any> | null {
let residual: KeyValueArray<any> | null | undefined = undefined;
const directiveEnd = tNode.directiveEnd;
ngDevMode &&
assertNotEqual(
tNode.directiveStylingLast,
-1,
'By the time this function gets called at least one hostBindings-node styling instruction must have executed.',
);
// We add `1 + tNode.directiveStart` because we need to skip the current directive (as we are
// collecting things after the last `hostBindings` directive which had a styling instruction.)
for (let i = 1 + tNode.directiveStylingLast; i < directiveEnd; i++) {
const attrs = (tData[i] as DirectiveDef<any>).hostAttrs;
residual = collectStylingFromTAttrs(residual, attrs, isClassBased) as KeyValueArray<any> | null;
}
return collectStylingFromTAttrs(residual, tNode.attrs, isClassBased) as KeyValueArray<any> | null;
}
/**
* Collect the static styling information with lower priority than `hostDirectiveDef`.
*
* (This is opposite of residual styling.)
*
* @param hostDirectiveDef `DirectiveDef` for which we want to collect lower priority static
* styling. (Or `null` if template styling)
* @param tData `TData` where the linked list is stored.
* @param tNode `TNode` for which the styling is being computed.
* @param stylingKey Existing `TStylingKey` to update or wrap.
* @param isClassBased `true` if `class` (`false` if `style`)
*/
function collectStylingFromDirectives(
hostDirectiveDef: DirectiveDef<any> | null,
tData: TData,
tNode: TNode,
stylingKey: TStylingKey,
isClassBased: boolean,
): TStylingKey {
// We need to loop because there can be directives which have `hostAttrs` but don't have
// `hostBindings` so this loop catches up to the current directive..
let currentDirective: DirectiveDef<any> | null = null;
const directiveEnd = tNode.directiveEnd;
let directiveStylingLast = tNode.directiveStylingLast;
if (directiveStylingLast === -1) {
directiveStylingLast = tNode.directiveStart;
} else {
directiveStylingLast++;
}
while (directiveStylingLast < directiveEnd) {
currentDirective = tData[directiveStylingLast] as DirectiveDef<any>;
ngDevMode && assertDefined(currentDirective, 'expected to be defined');
stylingKey = collectStylingFromTAttrs(stylingKey, currentDirective.hostAttrs, isClassBased);
if (currentDirective === hostDirectiveDef) break;
directiveStylingLast++;
}
if (hostDirectiveDef !== null) {
// we only advance the styling cursor if we are collecting data from host bindings.
// Template executes before host bindings and so if we would update the index,
// host bindings would not get their statics.
tNode.directiveStylingLast = directiveStylingLast;
}
return stylingKey;
}
/**
* Convert `TAttrs` into `TStylingStatic`.
*
* @param stylingKey existing `TStylingKey` to update or wrap.
* @param attrs `TAttributes` to process.
* @param isClassBased `true` if `class` (`false` if `style`)
*/
function collectStylingFromTAttrs(
stylingKey: TStylingKey | undefined,
attrs: TAttributes | null,
isClassBased: boolean,
): TStylingKey {
const desiredMarker = isClassBased ? AttributeMarker.Classes : AttributeMarker.Styles;
let currentMarker = AttributeMarker.ImplicitAttributes;
if (attrs !== null) {
for (let i = 0; i < attrs.length; i++) {
const item = attrs[i] as number | string;
if (typeof item === 'number') {
currentMarker = item;
} else {
if (currentMarker === desiredMarker) {
if (!Array.isArray(stylingKey)) {
stylingKey = stylingKey === undefined ? [] : (['', stylingKey] as any);
}
keyValueArraySet(
stylingKey as KeyValueArray<any>,
item,
isClassBased ? true : attrs[++i],
);
}
}
}
}
return stylingKey === undefined ? null : stylingKey;
}
/**
* Convert user input to `KeyValueArray`.
*
* This function takes user input which could be `string`, Object literal, or iterable and converts
* it into a consistent representation. The output of this is `KeyValueArray` (which is an array
* where
* even indexes contain keys and odd indexes contain values for those keys).
*
* The advantage of converting to `KeyValueArray` is that we can perform diff in an input
* independent
* way.
* (ie we can compare `foo bar` to `['bar', 'baz'] and determine a set of changes which need to be
* applied)
*
* The fact that `KeyValueArray` is sorted is very important because it allows us to compute the
* difference in linear fashion without the need to allocate any additional data.
*
* For example if we kept this as a `Map` we would have to iterate over previous `Map` to determine
* which values need to be deleted, over the new `Map` to determine additions, and we would have to
* keep additional `Map` to keep track of duplicates or items which have not yet been visited.
*
* @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 The parser is passed in so that it will be tree shakable. See
* `styleStringParser` and `classStringParser`
* @param value The value to parse/convert to `KeyValueArray`
*/
export function toStylingKeyValueArray(
keyValueArraySet: (keyValueArray: KeyValueArray<any>, key: string, value: any) => void,
stringParser: (styleKeyValueArray: KeyValueArray<any>, text: string) => void,
value: string | string[] | {[key: string]: any} | SafeValue | null | undefined,
): KeyValueArray<any> {
if (value == null /*|| value === undefined */ || value === '') return EMPTY_ARRAY as any;
const styleKeyValueArray: KeyValueArray<any> = [] as any;
const unwrappedValue = unwrapSafeValue(value) as string | string[] | {[key: string]: any};
if (Array.isArray(unwrappedValue)) {
for (let i = 0; i < unwrappedValue.length; i++) {
keyValueArraySet(styleKeyValueArray, unwrappedValue[i], true);
}
} else if (typeof unwrappedValue === 'object') {
for (const key in unwrappedValue) {
if (unwrappedValue.hasOwnProperty(key)) {
keyValueArraySet(styleKeyValueArray, key, unwrappedValue[key]);
}
}
} else if (typeof unwrappedValue === 'string') {
stringParser(styleKeyValueArray, unwrappedValue);
} else {
ngDevMode &&
throwError('Unsupported styling type ' + typeof unwrappedValue + ': ' + unwrappedValue);
}
return styleKeyValueArray;
}
/**
* Set a `value` for a `key`.
*
* See: `keyValueArraySet` for details
*
* @param keyValueArray KeyValueArray to add to.
* @param key Style key to add.
* @param value The value to set.
*/
export function styleKeyValueArraySet(keyValueArray: KeyValueArray<any>, key: string, value: any) {
keyValueArraySet(keyValueArray, key, unwrapSafeValue(value));
}
/**
* Class-binding-specific function for setting the `value` for a `key`.
*
* See: `keyValueArraySet` for details
*
* @param keyValueArray KeyValueArray to add to.
* @param key Style key to add.
* @param value The value to set.
*/
export function classKeyValueArraySet(keyValueArray: KeyValueArray<any>, key: unknown, value: any) {
// We use `classList.add` to eventually add the CSS classes to the DOM node. Any value passed into
// `add` is stringified and added to the `class` attribute, e.g. even null, undefined or numbers
// will be added. Stringify the key here so that our internal data structure matches the value in
// the DOM. The only exceptions are empty strings and strings that contain spaces for which
// the browser throws an error. We ignore such values, because the error is somewhat cryptic.
const stringKey = String(key);
if (stringKey !== '' && !stringKey.includes(' ')) {
keyValueArraySet(keyValueArray, stringKey, value);
}
}
/**
* Update map based st | {
"end_byte": 29899,
"start_byte": 21906,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts"
} |
angular/packages/core/src/render3/instructions/styling.ts_29901_37516 | ing.
*
* Map based styling could be anything which contains more than one binding. For example `string`,
* or object literal. Dealing with all of these types would complicate the logic so
* instead this function expects that the complex input is first converted into normalized
* `KeyValueArray`. The advantage of normalization is that we get the values sorted, which makes it
* very cheap to compute deltas between the previous and current value.
*
* @param tView Associated `TView.data` contains the linked list of binding priorities.
* @param tNode `TNode` where the binding is located.
* @param lView `LView` contains the values associated with other styling binding at this `TNode`.
* @param renderer Renderer to use if any updates.
* @param oldKeyValueArray Previous value represented as `KeyValueArray`
* @param newKeyValueArray Current value represented as `KeyValueArray`
* @param isClassBased `true` if `class` (`false` if `style`)
* @param bindingIndex Binding index of the binding.
*/
function updateStylingMap(
tView: TView,
tNode: TNode,
lView: LView,
renderer: Renderer,
oldKeyValueArray: KeyValueArray<any>,
newKeyValueArray: KeyValueArray<any>,
isClassBased: boolean,
bindingIndex: number,
) {
if ((oldKeyValueArray as KeyValueArray<any> | NO_CHANGE) === NO_CHANGE) {
// On first execution the oldKeyValueArray is NO_CHANGE => treat it as empty KeyValueArray.
oldKeyValueArray = EMPTY_ARRAY as any;
}
let oldIndex = 0;
let newIndex = 0;
let oldKey: string | null = 0 < oldKeyValueArray.length ? oldKeyValueArray[0] : null;
let newKey: string | null = 0 < newKeyValueArray.length ? newKeyValueArray[0] : null;
while (oldKey !== null || newKey !== null) {
ngDevMode && assertLessThan(oldIndex, 999, 'Are we stuck in infinite loop?');
ngDevMode && assertLessThan(newIndex, 999, 'Are we stuck in infinite loop?');
const oldValue =
oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex + 1] : undefined;
const newValue =
newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex + 1] : undefined;
let setKey: string | null = null;
let setValue: any = undefined;
if (oldKey === newKey) {
// UPDATE: Keys are equal => new value is overwriting old value.
oldIndex += 2;
newIndex += 2;
if (oldValue !== newValue) {
setKey = newKey;
setValue = newValue;
}
} else if (newKey === null || (oldKey !== null && oldKey < newKey!)) {
// DELETE: oldKey key is missing or we did not find the oldKey in the newValue
// (because the keyValueArray is sorted and `newKey` is found later alphabetically).
// `"background" < "color"` so we need to delete `"background"` because it is not found in the
// new array.
oldIndex += 2;
setKey = oldKey;
} else {
// CREATE: newKey's is earlier alphabetically than oldKey's (or no oldKey) => we have new key.
// `"color" > "background"` so we need to add `color` because it is in new array but not in
// old array.
ngDevMode && assertDefined(newKey, 'Expecting to have a valid key');
newIndex += 2;
setKey = newKey;
setValue = newValue;
}
if (setKey !== null) {
updateStyling(tView, tNode, lView, renderer, setKey, setValue, isClassBased, bindingIndex);
}
oldKey = oldIndex < oldKeyValueArray.length ? oldKeyValueArray[oldIndex] : null;
newKey = newIndex < newKeyValueArray.length ? newKeyValueArray[newIndex] : null;
}
}
/**
* Update a simple (property name) styling.
*
* This function takes `prop` and updates the DOM to that value. The function takes the binding
* value as well as binding priority into consideration to determine which value should be written
* to DOM. (For example it may be determined that there is a higher priority overwrite which blocks
* the DOM write, or if the value goes to `undefined` a lower priority overwrite may be consulted.)
*
* @param tView Associated `TView.data` contains the linked list of binding priorities.
* @param tNode `TNode` where the binding is located.
* @param lView `LView` contains the values associated with other styling binding at this `TNode`.
* @param renderer Renderer to use if any updates.
* @param prop Either style property name or a class name.
* @param value Either style value for `prop` or `true`/`false` if `prop` is class.
* @param isClassBased `true` if `class` (`false` if `style`)
* @param bindingIndex Binding index of the binding.
*/
function updateStyling(
tView: TView,
tNode: TNode,
lView: LView,
renderer: Renderer,
prop: string,
value: string | undefined | null | boolean,
isClassBased: boolean,
bindingIndex: number,
) {
if (!(tNode.type & TNodeType.AnyRNode)) {
// It is possible to have styling on non-elements (such as ng-container).
// This is rare, but it does happen. In such a case, just ignore the binding.
return;
}
const tData = tView.data;
const tRange = tData[bindingIndex + 1] as TStylingRange;
const higherPriorityValue = getTStylingRangeNextDuplicate(tRange)
? findStylingValue(tData, tNode, lView, prop, getTStylingRangeNext(tRange), isClassBased)
: undefined;
if (!isStylingValuePresent(higherPriorityValue)) {
// We don't have a next duplicate, or we did not find a duplicate value.
if (!isStylingValuePresent(value)) {
// We should delete current value or restore to lower priority value.
if (getTStylingRangePrevDuplicate(tRange)) {
// We have a possible prev duplicate, let's retrieve it.
value = findStylingValue(tData, null, lView, prop, bindingIndex, isClassBased);
}
}
const rNode = getNativeByIndex(getSelectedIndex(), lView) as RElement;
applyStyling(renderer, isClassBased, rNode, prop, value);
}
}
/**
* Search for styling value with higher priority which is overwriting current value, or a
* value of lower priority to which we should fall back if the value is `undefined`.
*
* When value is being applied at a location, related values need to be consulted.
* - If there is a higher priority binding, we should be using that one instead.
* For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp1`
* requires that we check `exp2` to see if it is set to value other than `undefined`.
* - If there is a lower priority binding and we are changing to `undefined`
* For example `<div [style]="{color:exp1}" [style.color]="exp2">` change to `exp2` to
* `undefined` requires that we check `exp1` (and static values) and use that as new value.
*
* NOTE: The styling stores two values.
* 1. The raw value which came from the application is stored at `index + 0` location. (This value
* is used for dirty checking).
* 2. The normalized value is stored at `index + 1`.
*
* @param tData `TData` used for traversing the priority.
* @param tNode `TNode` to use for resolving static styling. Also controls search direction.
* - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
* If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
* - `null` search prev and go all the way to end. Return last value where
* `isStylingValuePresent(value)` is true.
* @param lView `LView` used for retrieving the actual values.
* @param prop Property which we are interested in.
* @param index Starting index in the linked list of styling bindings where the search should start.
* @param isClassBased `true` if `class` (`false` if `style`)
*/
function findStylingValue(
| {
"end_byte": 37516,
"start_byte": 29901,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts"
} |
angular/packages/core/src/render3/instructions/styling.ts_37517_41868 | tData: TData,
tNode: TNode | null,
lView: LView,
prop: string,
index: number,
isClassBased: boolean,
): any {
// `TNode` to use for resolving static styling. Also controls search direction.
// - `TNode` search next and quit as soon as `isStylingValuePresent(value)` is true.
// If no value found consult `tNode.residualStyle`/`tNode.residualClass` for default value.
// - `null` search prev and go all the way to end. Return last value where
// `isStylingValuePresent(value)` is true.
const isPrevDirection = tNode === null;
let value: any = undefined;
while (index > 0) {
const rawKey = tData[index] as TStylingKey;
const containsStatics = Array.isArray(rawKey);
// Unwrap the key if we contain static values.
const key = containsStatics ? (rawKey as string[])[1] : rawKey;
const isStylingMap = key === null;
let valueAtLViewIndex = lView[index + 1];
if (valueAtLViewIndex === NO_CHANGE) {
// In firstUpdatePass the styling instructions create a linked list of styling.
// On subsequent passes it is possible for a styling instruction to try to read a binding
// which
// has not yet executed. In that case we will find `NO_CHANGE` and we should assume that
// we have `undefined` (or empty array in case of styling-map instruction) instead. This
// allows the resolution to apply the value (which may later be overwritten when the
// binding actually executes.)
valueAtLViewIndex = isStylingMap ? EMPTY_ARRAY : undefined;
}
let currentValue = isStylingMap
? keyValueArrayGet(valueAtLViewIndex, prop)
: key === prop
? valueAtLViewIndex
: undefined;
if (containsStatics && !isStylingValuePresent(currentValue)) {
currentValue = keyValueArrayGet(rawKey as KeyValueArray<any>, prop);
}
if (isStylingValuePresent(currentValue)) {
value = currentValue;
if (isPrevDirection) {
return value;
}
}
const tRange = tData[index + 1] as TStylingRange;
index = isPrevDirection ? getTStylingRangePrev(tRange) : getTStylingRangeNext(tRange);
}
if (tNode !== null) {
// in case where we are going in next direction AND we did not find anything, we need to
// consult residual styling
let residual = isClassBased ? tNode.residualClasses : tNode.residualStyles;
if (residual != null /** OR residual !=== undefined */) {
value = keyValueArrayGet(residual!, prop);
}
}
return value;
}
/**
* Determines if the binding value should be used (or if the value is 'undefined' and hence priority
* resolution should be used.)
*
* @param value Binding style value.
*/
function isStylingValuePresent(value: any): boolean {
// Currently only `undefined` value is considered non-binding. That is `undefined` says I don't
// have an opinion as to what this binding should be and you should consult other bindings by
// priority to determine the valid value.
// This is extracted into a single function so that we have a single place to control this.
return value !== undefined;
}
/**
* Normalizes and/or adds a suffix to the value.
*
* If value is `null`/`undefined` no suffix is added
* @param value
* @param suffix
*/
function normalizeSuffix(
value: any,
suffix: string | undefined | null,
): string | null | undefined | boolean {
if (value == null || value === '') {
// do nothing
// Do not add the suffix if the value is going to be empty.
// As it produce invalid CSS, which the browsers will automatically omit but Domino will not.
// Example: `"left": "px;"` instead of `"left": ""`.
} else if (typeof suffix === 'string') {
value = value + suffix;
} else if (typeof value === 'object') {
value = stringify(unwrapSafeValue(value));
}
return value;
}
/**
* Tests if the `TNode` has input shadow.
*
* An input shadow is when a directive steals (shadows) the input by using `@Input('style')` or
* `@Input('class')` as input.
*
* @param tNode `TNode` which we would like to see if it has shadow.
* @param isClassBased `true` if `class` (`false` if `style`)
*/
export function hasStylingInputShadow(tNode: TNode, isClassBased: boolean) {
return (tNode.flags & (isClassBased ? TNodeFlags.hasClassInput : TNodeFlags.hasStyleInput)) !== 0;
}
| {
"end_byte": 41868,
"start_byte": 37517,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/styling.ts"
} |
angular/packages/core/src/render3/instructions/di.ts_0_2957 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectFlags, resolveForwardRef} from '../../di';
import {assertInjectImplementationNotEqual} from '../../di/inject_switch';
import {ɵɵinject} from '../../di/injector_compatibility';
import {ProviderToken} from '../../di/provider_token';
import {Type} from '../../interface/type';
import {emitInjectEvent} from '../debug/injector_profiler';
import {getOrCreateInjectable} from '../di';
import {TDirectiveHostNode} from '../interfaces/node';
import {getCurrentTNode, getLView} from '../state';
/**
* Returns the value associated to the given token from the injectors.
*
* `directiveInject` is intended to be used for directive, component and pipe factories.
* All other injection use `inject` which does not walk the node injector tree.
*
* Usage example (in factory function):
*
* ```ts
* class SomeDirective {
* constructor(directive: DirectiveA) {}
*
* static ɵdir = ɵɵdefineDirective({
* type: SomeDirective,
* factory: () => new SomeDirective(ɵɵdirectiveInject(DirectiveA))
* });
* }
* ```
* @param token the type or token to inject
* @param flags Injection flags
* @returns the value from the injector or `null` when not found
*
* @codeGenApi
*/
export function ɵɵdirectiveInject<T>(token: ProviderToken<T>): T;
export function ɵɵdirectiveInject<T>(token: ProviderToken<T>, flags: InjectFlags): T;
export function ɵɵdirectiveInject<T>(
token: ProviderToken<T>,
flags = InjectFlags.Default,
): T | null {
const lView = getLView();
// Fall back to inject() if view hasn't been created. This situation can happen in tests
// if inject utilities are used before bootstrapping.
if (lView === null) {
// Verify that we will not get into infinite loop.
ngDevMode && assertInjectImplementationNotEqual(ɵɵdirectiveInject);
return ɵɵinject(token, flags);
}
const tNode = getCurrentTNode();
const value = getOrCreateInjectable<T>(
tNode as TDirectiveHostNode,
lView,
resolveForwardRef(token),
flags,
);
ngDevMode && emitInjectEvent(token as Type<unknown>, value, flags);
return value;
}
/**
* Throws an error indicating that a factory function could not be generated by the compiler for a
* particular class.
*
* This instruction allows the actual error message to be optimized away when ngDevMode is turned
* off, saving bytes of generated code while still providing a good experience in dev mode.
*
* The name of the class is not mentioned here, but will be in the generated factory function name
* and thus in the stack trace.
*
* @codeGenApi
*/
export function ɵɵinvalidFactory(): never {
const msg = ngDevMode
? `This constructor was not compatible with Dependency Injection.`
: 'invalid';
throw new Error(msg);
}
| {
"end_byte": 2957,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/di.ts"
} |
angular/packages/core/src/render3/instructions/control_flow.ts_0_7050 | /**
* @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 {TrackByFunction} from '../../change_detection';
import {formatRuntimeError, RuntimeErrorCode} from '../../errors';
import {DehydratedContainerView} from '../../hydration/interfaces';
import {findMatchingDehydratedView} from '../../hydration/views';
import {assertDefined, assertFunction} from '../../util/assert';
import {performanceMarkFeature} from '../../util/performance';
import {assertLContainer, assertLView, assertTNode} from '../assert';
import {bindingUpdated} from '../bindings';
import {CONTAINER_HEADER_OFFSET, LContainer} from '../interfaces/container';
import {ComponentTemplate} from '../interfaces/definition';
import {TNode} from '../interfaces/node';
import {
CONTEXT,
DECLARATION_COMPONENT_VIEW,
HEADER_OFFSET,
HYDRATION,
LView,
TVIEW,
TView,
} from '../interfaces/view';
import {LiveCollection, reconcile} from '../list_reconciliation';
import {destroyLView, detachView} from '../node_manipulation';
import {getLView, getSelectedIndex, getTView, nextBindingIndex} from '../state';
import {NO_CHANGE} from '../tokens';
import {getConstant, getTNode} from '../util/view_utils';
import {
addLViewToLContainer,
createAndRenderEmbeddedLView,
getLViewFromLContainer,
removeLViewFromLContainer,
shouldAddViewToDom,
} from '../view_manipulation';
import {declareTemplate} from './template';
/**
* The conditional instruction represents the basic building block on the runtime side to support
* built-in "if" and "switch". On the high level this instruction is responsible for adding and
* removing views selected by a conditional expression.
*
* @param matchingTemplateIndex Index of a template TNode representing a conditional view to be
* inserted; -1 represents a special case when there is no view to insert.
* @param contextValue Value that should be exposed as the context of the conditional.
* @codeGenApi
*/
export function ɵɵconditional<T>(matchingTemplateIndex: number, contextValue?: T) {
performanceMarkFeature('NgControlFlow');
const hostLView = getLView();
const bindingIndex = nextBindingIndex();
const prevMatchingTemplateIndex: number =
hostLView[bindingIndex] !== NO_CHANGE ? hostLView[bindingIndex] : -1;
const prevContainer =
prevMatchingTemplateIndex !== -1
? getLContainer(hostLView, HEADER_OFFSET + prevMatchingTemplateIndex)
: undefined;
const viewInContainerIdx = 0;
if (bindingUpdated(hostLView, bindingIndex, matchingTemplateIndex)) {
const prevConsumer = setActiveConsumer(null);
try {
// The index of the view to show changed - remove the previously displayed one
// (it is a noop if there are no active views in a container).
if (prevContainer !== undefined) {
removeLViewFromLContainer(prevContainer, viewInContainerIdx);
}
// Index -1 is a special case where none of the conditions evaluates to
// a truthy value and as the consequence we've got no view to show.
if (matchingTemplateIndex !== -1) {
const nextLContainerIndex = HEADER_OFFSET + matchingTemplateIndex;
const nextContainer = getLContainer(hostLView, nextLContainerIndex);
const templateTNode = getExistingTNode(hostLView[TVIEW], nextLContainerIndex);
const dehydratedView = findMatchingDehydratedView(
nextContainer,
templateTNode.tView!.ssrId,
);
const embeddedLView = createAndRenderEmbeddedLView(hostLView, templateTNode, contextValue, {
dehydratedView,
});
addLViewToLContainer(
nextContainer,
embeddedLView,
viewInContainerIdx,
shouldAddViewToDom(templateTNode, dehydratedView),
);
}
} finally {
setActiveConsumer(prevConsumer);
}
} else if (prevContainer !== undefined) {
// We might keep displaying the same template but the actual value of the expression could have
// changed - re-bind in context.
const lView = getLViewFromLContainer<T | undefined>(prevContainer, viewInContainerIdx);
if (lView !== undefined) {
lView[CONTEXT] = contextValue;
}
}
}
export class RepeaterContext<T> {
constructor(
private lContainer: LContainer,
public $implicit: T,
public $index: number,
) {}
get $count(): number {
return this.lContainer.length - CONTAINER_HEADER_OFFSET;
}
}
/**
* A built-in trackBy function used for situations where users specified collection index as a
* tracking expression. Having this function body in the runtime avoids unnecessary code generation.
*
* @param index
* @returns
*/
export function ɵɵrepeaterTrackByIndex(index: number) {
return index;
}
/**
* A built-in trackBy function used for situations where users specified collection item reference
* as a tracking expression. Having this function body in the runtime avoids unnecessary code
* generation.
*
* @param index
* @returns
*/
export function ɵɵrepeaterTrackByIdentity<T>(_: number, value: T) {
return value;
}
class RepeaterMetadata {
constructor(
public hasEmptyBlock: boolean,
public trackByFn: TrackByFunction<unknown>,
public liveCollection?: LiveCollectionLContainerImpl,
) {}
}
/**
* The repeaterCreate instruction runs in the creation part of the template pass and initializes
* internal data structures required by the update pass of the built-in repeater logic. Repeater
* metadata are allocated in the data part of LView with the following layout:
* - LView[HEADER_OFFSET + index] - metadata
* - LView[HEADER_OFFSET + index + 1] - reference to a template function rendering an item
* - LView[HEADER_OFFSET + index + 2] - optional reference to a template function rendering an empty
* block
*
* @param index Index at which to store the metadata of the repeater.
* @param templateFn Reference to the template of the main repeater block.
* @param decls The number of nodes, local refs, and pipes for the main block.
* @param vars The number of bindings for the main block.
* @param tagName The name of the container element, if applicable
* @param attrsIndex Index of template attributes in the `consts` array.
* @param trackByFn Reference to the tracking function.
* @param trackByUsesComponentInstance Whether the tracking function has any references to the
* component instance. If it doesn't, we can avoid rebinding it.
* @param emptyTemplateFn Reference to the template function of the empty block.
* @param emptyDecls The number of nodes, local refs, and pipes for the empty block.
* @param emptyVars The number of bindings for the empty block.
* @param emptyTagName The name of the empty block container element, if applicable
* @param emptyAttrsIndex Index of the empty block template attributes in the `consts` array.
*
* @codeGenApi
*/
expor | {
"end_byte": 7050,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/control_flow.ts"
} |
angular/packages/core/src/render3/instructions/control_flow.ts_7051_12602 | function ɵɵrepeaterCreate(
index: number,
templateFn: ComponentTemplate<unknown>,
decls: number,
vars: number,
tagName: string | null,
attrsIndex: number | null,
trackByFn: TrackByFunction<unknown>,
trackByUsesComponentInstance?: boolean,
emptyTemplateFn?: ComponentTemplate<unknown>,
emptyDecls?: number,
emptyVars?: number,
emptyTagName?: string | null,
emptyAttrsIndex?: number | null,
): void {
performanceMarkFeature('NgControlFlow');
ngDevMode &&
assertFunction(
trackByFn,
`A track expression must be a function, was ${typeof trackByFn} instead.`,
);
const lView = getLView();
const tView = getTView();
const hasEmptyBlock = emptyTemplateFn !== undefined;
const hostLView = getLView();
const boundTrackBy = trackByUsesComponentInstance
? // We only want to bind when necessary, because it produces a
// new function. For pure functions it's not necessary.
trackByFn.bind(hostLView[DECLARATION_COMPONENT_VIEW][CONTEXT])
: trackByFn;
const metadata = new RepeaterMetadata(hasEmptyBlock, boundTrackBy);
hostLView[HEADER_OFFSET + index] = metadata;
declareTemplate(
lView,
tView,
index + 1,
templateFn,
decls,
vars,
tagName,
getConstant(tView.consts, attrsIndex),
);
if (hasEmptyBlock) {
ngDevMode &&
assertDefined(emptyDecls, 'Missing number of declarations for the empty repeater block.');
ngDevMode &&
assertDefined(emptyVars, 'Missing number of bindings for the empty repeater block.');
declareTemplate(
lView,
tView,
index + 2,
emptyTemplateFn,
emptyDecls!,
emptyVars!,
emptyTagName,
getConstant(tView.consts, emptyAttrsIndex),
);
}
}
function isViewExpensiveToRecreate(lView: LView): boolean {
// assumption: anything more than a text node with a binding is considered "expensive"
return lView.length - HEADER_OFFSET > 2;
}
class OperationsCounter {
created = 0;
destroyed = 0;
reset() {
this.created = 0;
this.destroyed = 0;
}
recordCreate() {
this.created++;
}
recordDestroy() {
this.destroyed++;
}
/**
* A method indicating if the entire collection was re-created as part of the reconciliation pass.
* Used to warn developers about the usage of a tracking function that might result in excessive
* amount of view creation / destroy operations.
*
* @returns boolean value indicating if a live collection was re-created
*/
wasReCreated(collectionLen: number): boolean {
return collectionLen > 0 && this.created === this.destroyed && this.created === collectionLen;
}
}
class LiveCollectionLContainerImpl extends LiveCollection<
LView<RepeaterContext<unknown>>,
unknown
> {
operationsCounter = ngDevMode ? new OperationsCounter() : undefined;
/**
Property indicating if indexes in the repeater context need to be updated following the live
collection changes. Index updates are necessary if and only if views are inserted / removed in
the middle of LContainer. Adds and removals at the end don't require index updates.
*/
private needsIndexUpdate = false;
constructor(
private lContainer: LContainer,
private hostLView: LView,
private templateTNode: TNode,
) {
super();
}
override get length(): number {
return this.lContainer.length - CONTAINER_HEADER_OFFSET;
}
override at(index: number): unknown {
return this.getLView(index)[CONTEXT].$implicit;
}
override attach(index: number, lView: LView<RepeaterContext<unknown>>): void {
const dehydratedView = lView[HYDRATION] as DehydratedContainerView;
this.needsIndexUpdate ||= index !== this.length;
addLViewToLContainer(
this.lContainer,
lView,
index,
shouldAddViewToDom(this.templateTNode, dehydratedView),
);
}
override detach(index: number): LView<RepeaterContext<unknown>> {
this.needsIndexUpdate ||= index !== this.length - 1;
return detachExistingView<RepeaterContext<unknown>>(this.lContainer, index);
}
override create(index: number, value: unknown): LView<RepeaterContext<unknown>> {
const dehydratedView = findMatchingDehydratedView(
this.lContainer,
this.templateTNode.tView!.ssrId,
);
const embeddedLView = createAndRenderEmbeddedLView(
this.hostLView,
this.templateTNode,
new RepeaterContext(this.lContainer, value, index),
{dehydratedView},
);
this.operationsCounter?.recordCreate();
return embeddedLView;
}
override destroy(lView: LView<RepeaterContext<unknown>>): void {
destroyLView(lView[TVIEW], lView);
this.operationsCounter?.recordDestroy();
}
override updateValue(index: number, value: unknown): void {
this.getLView(index)[CONTEXT].$implicit = value;
}
reset(): void {
this.needsIndexUpdate = false;
this.operationsCounter?.reset();
}
updateIndexes(): void {
if (this.needsIndexUpdate) {
for (let i = 0; i < this.length; i++) {
this.getLView(i)[CONTEXT].$index = i;
}
}
}
private getLView(index: number): LView<RepeaterContext<unknown>> {
return getExistingLViewFromLContainer(this.lContainer, index);
}
}
/**
* The repeater instruction does update-time diffing of a provided collection (against the
* collection seen previously) and maps changes in the collection to views structure (by adding,
* removing or moving views as needed).
* @param collection - the collection instance to be checked for changes
* @codeGenApi
*/
export | {
"end_byte": 12602,
"start_byte": 7051,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/control_flow.ts"
} |
angular/packages/core/src/render3/instructions/control_flow.ts_12603_16698 | unction ɵɵrepeater(collection: Iterable<unknown> | undefined | null): void {
const prevConsumer = setActiveConsumer(null);
const metadataSlotIdx = getSelectedIndex();
try {
const hostLView = getLView();
const hostTView = hostLView[TVIEW];
const metadata = hostLView[metadataSlotIdx] as RepeaterMetadata;
const containerIndex = metadataSlotIdx + 1;
const lContainer = getLContainer(hostLView, containerIndex);
if (metadata.liveCollection === undefined) {
const itemTemplateTNode = getExistingTNode(hostTView, containerIndex);
metadata.liveCollection = new LiveCollectionLContainerImpl(
lContainer,
hostLView,
itemTemplateTNode,
);
} else {
metadata.liveCollection.reset();
}
const liveCollection = metadata.liveCollection;
reconcile(liveCollection, collection, metadata.trackByFn);
// Warn developers about situations where the entire collection was re-created as part of the
// reconciliation pass. Note that this warning might be "overreacting" and report cases where
// the collection re-creation is the intended behavior. Still, the assumption is that most of
// the time it is undesired.
if (
ngDevMode &&
metadata.trackByFn === ɵɵrepeaterTrackByIdentity &&
liveCollection.operationsCounter?.wasReCreated(liveCollection.length) &&
isViewExpensiveToRecreate(getExistingLViewFromLContainer(lContainer, 0))
) {
const message = formatRuntimeError(
RuntimeErrorCode.LOOP_TRACK_RECREATE,
`The configured tracking expression (track by identity) caused re-creation of the entire collection of size ${liveCollection.length}. ` +
'This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc. ' +
'Please review the "track expression" and make sure that it uniquely identifies items in a collection.',
);
console.warn(message);
}
// moves in the container might caused context's index to get out of order, re-adjust if needed
liveCollection.updateIndexes();
// handle empty blocks
if (metadata.hasEmptyBlock) {
const bindingIndex = nextBindingIndex();
const isCollectionEmpty = liveCollection.length === 0;
if (bindingUpdated(hostLView, bindingIndex, isCollectionEmpty)) {
const emptyTemplateIndex = metadataSlotIdx + 2;
const lContainerForEmpty = getLContainer(hostLView, emptyTemplateIndex);
if (isCollectionEmpty) {
const emptyTemplateTNode = getExistingTNode(hostTView, emptyTemplateIndex);
const dehydratedView = findMatchingDehydratedView(
lContainerForEmpty,
emptyTemplateTNode.tView!.ssrId,
);
const embeddedLView = createAndRenderEmbeddedLView(
hostLView,
emptyTemplateTNode,
undefined,
{dehydratedView},
);
addLViewToLContainer(
lContainerForEmpty,
embeddedLView,
0,
shouldAddViewToDom(emptyTemplateTNode, dehydratedView),
);
} else {
removeLViewFromLContainer(lContainerForEmpty, 0);
}
}
}
} finally {
setActiveConsumer(prevConsumer);
}
}
function getLContainer(lView: LView, index: number): LContainer {
const lContainer = lView[index];
ngDevMode && assertLContainer(lContainer);
return lContainer;
}
function detachExistingView<T>(lContainer: LContainer, index: number): LView<T> {
const existingLView = detachView(lContainer, index);
ngDevMode && assertLView(existingLView);
return existingLView as LView<T>;
}
function getExistingLViewFromLContainer<T>(lContainer: LContainer, index: number): LView<T> {
const existingLView = getLViewFromLContainer<T>(lContainer, index);
ngDevMode && assertLView(existingLView);
return existingLView!;
}
function getExistingTNode(tView: TView, index: number): TNode {
const tNode = getTNode(tView, index);
ngDevMode && assertTNode(tNode);
return tNode;
}
| {
"end_byte": 16698,
"start_byte": 12603,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/control_flow.ts"
} |
angular/packages/core/src/render3/instructions/let_declaration.ts_0_2283 | /*!
* @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 {performanceMarkFeature} from '../../util/performance';
import {TNodeType} from '../interfaces/node';
import {HEADER_OFFSET} from '../interfaces/view';
import {getContextLView, getLView, getSelectedIndex, getTView, setCurrentTNode} from '../state';
import {load} from '../util/view_utils';
import {getOrCreateTNode} from './shared';
import {store} from './storage';
/** Object that indicates the value of a `@let` declaration that hasn't been initialized yet. */
const UNINITIALIZED_LET = {};
/**
* Declares an `@let` at a specific data slot. Returns itself to allow chaining.
*
* @param index Index at which to declare the `@let`.
*
* @codeGenApi
*/
export function ɵɵdeclareLet(index: number): typeof ɵɵdeclareLet {
const tView = getTView();
const lView = getLView();
const adjustedIndex = index + HEADER_OFFSET;
const tNode = getOrCreateTNode(tView, adjustedIndex, TNodeType.LetDeclaration, null, null);
setCurrentTNode(tNode, false);
store(tView, lView, adjustedIndex, UNINITIALIZED_LET);
return ɵɵdeclareLet;
}
/**
* Instruction that stores the value of a `@let` declaration on the current view.
* Returns the value to allow usage inside variable initializers.
*
* @codeGenApi
*/
export function ɵɵstoreLet<T>(value: T): T {
performanceMarkFeature('NgLet');
const tView = getTView();
const lView = getLView();
const index = getSelectedIndex();
store(tView, lView, index, value);
return value;
}
/**
* Retrieves the value of a `@let` declaration defined in a parent view.
*
* @param index Index of the declaration within the view.
*
* @codeGenApi
*/
export function ɵɵreadContextLet<T>(index: number): T {
const contextLView = getContextLView();
const value = load<T>(contextLView, HEADER_OFFSET + index);
if (value === UNINITIALIZED_LET) {
throw new RuntimeError(
RuntimeErrorCode.UNINITIALIZED_LET_ACCESS,
ngDevMode && 'Attempting to access a @let declaration whose value is not available yet',
);
}
return value;
}
| {
"end_byte": 2283,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/let_declaration.ts"
} |
angular/packages/core/src/render3/instructions/style_prop_interpolation.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 {getLView} from '../state';
import {
interpolation1,
interpolation2,
interpolation3,
interpolation4,
interpolation5,
interpolation6,
interpolation7,
interpolation8,
interpolationV,
} from './interpolation';
import {checkStylingProperty} from './styling';
/**
*
* Update an interpolated style 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 style.color="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate1(0, 'prefix', v0, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @param prefix Static value used for concatenation only.
* @param v0 Value checked for change.
* @param suffix Static value used for concatenation only.
* @param valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate1(
prop: string,
prefix: string,
v0: any,
suffix: string,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate1 {
const lView = getLView();
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate1;
}
/**
*
* Update an interpolated style 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 style.color="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate2(0, 'prefix', v0, '-', v1, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate2(
prop: string,
prefix: string,
v0: any,
i0: string,
v1: any,
suffix: string,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate2 {
const lView = getLView();
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate2;
}
/**
*
* Update an interpolated style 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 style.color="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate3(0, 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate3(
prop: string,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
suffix: string,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate3 {
const lView = getLView();
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate3;
}
/**
*
* Update an interpolated style property 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 style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate4(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate4(
prop: string,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
i2: string,
v3: any,
suffix: string,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate4 {
const lView = getLView();
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate4;
}
/**
*
* Update an interpolat | {
"end_byte": 6300,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_prop_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/style_prop_interpolation.ts_6302_12352 | style 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 style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate5(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate5(
prop: string,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
i2: string,
v3: any,
i3: string,
v4: any,
suffix: string,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate5 {
const lView = getLView();
const interpolatedValue = interpolation5(
lView,
prefix,
v0,
i0,
v1,
i1,
v2,
i2,
v3,
i3,
v4,
suffix,
);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate5;
}
/**
*
* Update an interpolated style 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 style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate6(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate6(
prop: 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,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate6 {
const lView = getLView();
const interpolatedValue = interpolation6(
lView,
prefix,
v0,
i0,
v1,
i1,
v2,
i2,
v3,
i3,
v4,
i4,
v5,
suffix,
);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate6;
}
/**
*
* Update an interpolated style 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 style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate7(
* 0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate7(
prop: 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,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate7 {
const lView = getLView();
const interpolatedValue = interpolation7(
lView,
prefix,
v0,
i0,
v1,
i1,
v2,
i2,
v3,
i3,
v4,
i4,
v5,
i5,
v6,
suffix,
);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate7;
}
/**
*
* Update an interpolated style property on an | {
"end_byte": 12352,
"start_byte": 6302,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_prop_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/style_prop_interpolation.ts_12354_16087 | ement with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolate8(0, 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6,
* '-', v7, 'suffix');
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`.
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolate8(
prop: 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,
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolate8 {
const lView = getLView();
const interpolatedValue = interpolation8(
lView,
prefix,
v0,
i0,
v1,
i1,
v2,
i2,
v3,
i3,
v4,
i4,
v5,
i5,
v6,
i6,
v7,
suffix,
);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolate8;
}
/**
* Update an interpolated style property on an element with 9 or more bound values surrounded by
* text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* style.color="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}-{{v8}}-{{v9}}suffix">
* </div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstylePropInterpolateV(
* 0, ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
*
* @param styleIndex Index of style to update. This index value refers to the
* index of the style in the style bindings array that was passed into
* `styling`..
* @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 valueSuffix Optional suffix. Used with scalar values to add unit such as `px`.
* @returns itself, so that it may be chained.
* @codeGenApi
*/
export function ɵɵstylePropInterpolateV(
prop: string,
values: any[],
valueSuffix?: string | null,
): typeof ɵɵstylePropInterpolateV {
const lView = getLView();
const interpolatedValue = interpolationV(lView, values);
checkStylingProperty(prop, interpolatedValue, valueSuffix, false);
return ɵɵstylePropInterpolateV;
}
| {
"end_byte": 16087,
"start_byte": 12354,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_prop_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/element_container.ts_0_7882 | /**
* @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 {locateNextRNode, siblingAfter} from '../../hydration/node_lookup_utils';
import {
getNgContainerSize,
isDisconnectedNode,
markRNodeAsClaimedByHydration,
setSegmentHead,
} from '../../hydration/utils';
import {isDetachedByI18n} from '../../i18n/utils';
import {assertEqual, assertIndexInRange, assertNumber} from '../../util/assert';
import {assertHasParent} from '../assert';
import {attachPatchData} from '../context_discovery';
import {registerPostOrderHooks} from '../hooks';
import {TAttributes, TElementContainerNode, TNode, TNodeType} from '../interfaces/node';
import {RComment} from '../interfaces/renderer_dom';
import {isContentQueryHost, isDirectiveHost} from '../interfaces/type_checks';
import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view';
import {assertTNodeType} from '../node_assert';
import {appendChild, createCommentNode} from '../node_manipulation';
import {
getBindingIndex,
getCurrentTNode,
getLView,
getTView,
isCurrentTNodeParent,
isInSkipHydrationBlock,
lastNodeWasCreated,
setCurrentTNode,
setCurrentTNodeAsNotParent,
wasLastNodeCreated,
} from '../state';
import {computeStaticStyling} from '../styling/static_styling';
import {getConstant} from '../util/view_utils';
import {
createDirectivesInstances,
executeContentQueries,
getOrCreateTNode,
resolveDirectives,
saveResolvedLocalsInData,
} from './shared';
function elementContainerStartFirstCreatePass(
index: number,
tView: TView,
lView: LView,
attrsIndex?: number | null,
localRefsIndex?: number,
): TElementContainerNode {
ngDevMode && ngDevMode.firstCreatePass++;
const tViewConsts = tView.consts;
const attrs = getConstant<TAttributes>(tViewConsts, attrsIndex);
const tNode = getOrCreateTNode(tView, index, TNodeType.ElementContainer, 'ng-container', attrs);
// While ng-container doesn't necessarily support styling, we use the style context to identify
// and execute directives on the ng-container.
if (attrs !== null) {
computeStaticStyling(tNode, attrs, true);
}
const localRefs = getConstant<string[]>(tViewConsts, localRefsIndex);
resolveDirectives(tView, lView, tNode, localRefs);
if (tView.queries !== null) {
tView.queries.elementStart(tView, tNode);
}
return tNode;
}
/**
* Creates a logical container for other nodes (<ng-container>) backed by a comment node in the DOM.
* The instruction must later be followed by `elementContainerEnd()` call.
*
* @param index Index of the element in the LView array
* @param attrsIndex Index of the container attributes in the `consts` array.
* @param localRefsIndex Index of the container's local references in the `consts` array.
* @returns This function returns itself so that it may be chained.
*
* Even if this instruction accepts a set of attributes no actual attribute values are propagated to
* the DOM (as a comment node can't have attributes). Attributes are here only for directive
* matching purposes and setting initial inputs of directives.
*
* @codeGenApi
*/
export function ɵɵelementContainerStart(
index: number,
attrsIndex?: number | null,
localRefsIndex?: number,
): typeof ɵɵelementContainerStart {
const lView = getLView();
const tView = getTView();
const adjustedIndex = index + HEADER_OFFSET;
ngDevMode && assertIndexInRange(lView, adjustedIndex);
ngDevMode &&
assertEqual(
getBindingIndex(),
tView.bindingStartIndex,
'element containers should be created before any bindings',
);
const tNode = tView.firstCreatePass
? elementContainerStartFirstCreatePass(adjustedIndex, tView, lView, attrsIndex, localRefsIndex)
: (tView.data[adjustedIndex] as TElementContainerNode);
setCurrentTNode(tNode, true);
const comment = _locateOrCreateElementContainerNode(tView, lView, tNode, index);
lView[adjustedIndex] = comment;
if (wasLastNodeCreated()) {
appendChild(tView, lView, comment, tNode);
}
attachPatchData(comment, lView);
if (isDirectiveHost(tNode)) {
createDirectivesInstances(tView, lView, tNode);
executeContentQueries(tView, tNode, lView);
}
if (localRefsIndex != null) {
saveResolvedLocalsInData(lView, tNode);
}
return ɵɵelementContainerStart;
}
/**
* Mark the end of the <ng-container>.
* @returns This function returns itself so that it may be chained.
*
* @codeGenApi
*/
export function ɵɵelementContainerEnd(): typeof ɵɵelementContainerEnd {
let currentTNode = getCurrentTNode()!;
const tView = getTView();
if (isCurrentTNodeParent()) {
setCurrentTNodeAsNotParent();
} else {
ngDevMode && assertHasParent(currentTNode);
currentTNode = currentTNode.parent!;
setCurrentTNode(currentTNode, false);
}
ngDevMode && assertTNodeType(currentTNode, TNodeType.ElementContainer);
if (tView.firstCreatePass) {
registerPostOrderHooks(tView, currentTNode);
if (isContentQueryHost(currentTNode)) {
tView.queries!.elementEnd(currentTNode);
}
}
return ɵɵelementContainerEnd;
}
/**
* Creates an empty logical container using {@link elementContainerStart}
* and {@link elementContainerEnd}
*
* @param index Index of the element in the LView array
* @param attrsIndex Index of the container attributes in the `consts` array.
* @param localRefsIndex Index of the container's local references in the `consts` array.
* @returns This function returns itself so that it may be chained.
*
* @codeGenApi
*/
export function ɵɵelementContainer(
index: number,
attrsIndex?: number | null,
localRefsIndex?: number,
): typeof ɵɵelementContainer {
ɵɵelementContainerStart(index, attrsIndex, localRefsIndex);
ɵɵelementContainerEnd();
return ɵɵelementContainer;
}
let _locateOrCreateElementContainerNode: typeof locateOrCreateElementContainerNode = (
tView: TView,
lView: LView,
tNode: TNode,
index: number,
) => {
lastNodeWasCreated(true);
return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
};
/**
* Enables hydration code path (to lookup existing elements in DOM)
* in addition to the regular creation mode of comment nodes that
* represent <ng-container>'s anchor.
*/
function locateOrCreateElementContainerNode(
tView: TView,
lView: LView,
tNode: TNode,
index: number,
): RComment {
let comment: RComment;
const hydrationInfo = lView[HYDRATION];
const isNodeCreationMode =
!hydrationInfo ||
isInSkipHydrationBlock() ||
isDisconnectedNode(hydrationInfo, index) ||
isDetachedByI18n(tNode);
lastNodeWasCreated(isNodeCreationMode);
// Regular creation mode.
if (isNodeCreationMode) {
return createCommentNode(lView[RENDERER], ngDevMode ? 'ng-container' : '');
}
// Hydration mode, looking up existing elements in DOM.
const currentRNode = locateNextRNode(hydrationInfo, tView, lView, tNode)!;
ngDevMode && validateNodeExists(currentRNode, lView, tNode);
const ngContainerSize = getNgContainerSize(hydrationInfo, index) as number;
ngDevMode &&
assertNumber(
ngContainerSize,
'Unexpected state: hydrating an <ng-container>, ' + 'but no hydration info is available.',
);
setSegmentHead(hydrationInfo, index, currentRNode);
comment = siblingAfter<RComment>(ngContainerSize, currentRNode)!;
if (ngDevMode) {
validateMatchingNode(comment, Node.COMMENT_NODE, null, lView, tNode);
markRNodeAsClaimedByHydration(comment);
}
return comment;
}
export function enableLocateOrCreateElementContainerNodeImpl() {
_locateOrCreateElementContainerNode = locateOrCreateElementContainerNode;
}
| {
"end_byte": 7882,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/element_container.ts"
} |
angular/packages/core/src/render3/instructions/change_detection.ts_0_5683 | /**
* @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 {
consumerAfterComputation,
consumerBeforeComputation,
consumerDestroy,
consumerPollProducersForChange,
getActiveConsumer,
ReactiveNode,
} from '@angular/core/primitives/signals';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {assertDefined, assertEqual} from '../../util/assert';
import {executeCheckHooks, executeInitAndCheckHooks, incrementInitPhaseFlags} from '../hooks';
import {CONTAINER_HEADER_OFFSET, LContainerFlags, MOVED_VIEWS} from '../interfaces/container';
import {ComponentTemplate, RenderFlags} from '../interfaces/definition';
import {
CONTEXT,
EFFECTS_TO_SCHEDULE,
ENVIRONMENT,
FLAGS,
InitPhaseState,
LView,
LViewFlags,
REACTIVE_TEMPLATE_CONSUMER,
TVIEW,
TView,
} from '../interfaces/view';
import {
getOrCreateTemporaryConsumer,
getOrBorrowReactiveLViewConsumer,
maybeReturnReactiveLViewConsumer,
ReactiveLViewConsumer,
viewShouldHaveReactiveConsumer,
} from '../reactive_lview_consumer';
import {
CheckNoChangesMode,
enterView,
isExhaustiveCheckNoChanges,
isInCheckNoChangesMode,
isRefreshingViews,
leaveView,
setBindingIndex,
setIsInCheckNoChangesMode,
setIsRefreshingViews,
} from '../state';
import {getFirstLContainer, getNextLContainer} from '../util/view_traversal_utils';
import {
getComponentLViewByIndex,
isCreationMode,
markAncestorsForTraversal,
markViewForRefresh,
requiresRefreshOrTraversal,
resetPreOrderHookFlags,
viewAttachedToChangeDetector,
} from '../util/view_utils';
import {
executeTemplate,
executeViewQueryFn,
handleError,
processHostBindingOpCodes,
refreshContentQueries,
} from './shared';
import {runEffectsInView} from '../reactivity/view_effect_runner';
/**
* The maximum number of times the change detection traversal will rerun before throwing an error.
*/
export const MAXIMUM_REFRESH_RERUNS = 100;
export function detectChangesInternal(
lView: LView,
notifyErrorHandler = true,
mode = ChangeDetectionMode.Global,
) {
const environment = lView[ENVIRONMENT];
const rendererFactory = environment.rendererFactory;
// Check no changes mode is a dev only mode used to verify that bindings have not changed
// since they were assigned. We do not want to invoke renderer factory functions in that mode
// to avoid any possible side-effects.
const checkNoChangesMode = !!ngDevMode && isInCheckNoChangesMode();
if (!checkNoChangesMode) {
rendererFactory.begin?.();
}
try {
detectChangesInViewWhileDirty(lView, mode);
} catch (error) {
if (notifyErrorHandler) {
handleError(lView, error);
}
throw error;
} finally {
if (!checkNoChangesMode) {
rendererFactory.end?.();
}
}
}
function detectChangesInViewWhileDirty(lView: LView, mode: ChangeDetectionMode) {
const lastIsRefreshingViewsValue = isRefreshingViews();
try {
setIsRefreshingViews(true);
detectChangesInView(lView, mode);
// We don't need or want to do any looping when in exhaustive checkNoChanges because we
// already traverse all the views and nothing should change so we shouldn't have to do
// another pass to pick up new changes.
if (ngDevMode && isExhaustiveCheckNoChanges()) {
return;
}
let retries = 0;
// If after running change detection, this view still needs to be refreshed or there are
// descendants views that need to be refreshed due to re-dirtying during the change detection
// run, detect changes on the view again. We run change detection in `Targeted` mode to only
// refresh views with the `RefreshView` flag.
while (requiresRefreshOrTraversal(lView)) {
if (retries === MAXIMUM_REFRESH_RERUNS) {
throw new RuntimeError(
RuntimeErrorCode.INFINITE_CHANGE_DETECTION,
ngDevMode &&
'Infinite change detection while trying to refresh views. ' +
'There may be components which each cause the other to require a refresh, ' +
'causing an infinite loop.',
);
}
retries++;
// Even if this view is detached, we still detect changes in targeted mode because this was
// the root of the change detection run.
detectChangesInView(lView, ChangeDetectionMode.Targeted);
}
} finally {
// restore state to what it was before entering this change detection loop
setIsRefreshingViews(lastIsRefreshingViewsValue);
}
}
export function checkNoChangesInternal(
lView: LView,
mode: CheckNoChangesMode,
notifyErrorHandler = true,
) {
setIsInCheckNoChangesMode(mode);
try {
detectChangesInternal(lView, notifyErrorHandler);
} finally {
setIsInCheckNoChangesMode(CheckNoChangesMode.Off);
}
}
/**
* Different modes of traversing the logical view tree during change detection.
*
*
* The change detection traversal algorithm switches between these modes based on various
* conditions.
*/
export const enum ChangeDetectionMode {
/**
* In `Global` mode, `Dirty` and `CheckAlways` views are refreshed as well as views with the
* `RefreshView` flag.
*/
Global,
/**
* In `Targeted` mode, only views with the `RefreshView` flag or updated signals are refreshed.
*/
Targeted,
}
/**
* Processes a view in update mode. This includes a number of steps in a specific order:
* - executing a template function in update mode;
* - executing hooks;
* - refreshing queries;
* - setting host bindings;
* - refreshing child (embedded and component) views.
*/ | {
"end_byte": 5683,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/change_detection.ts"
} |
angular/packages/core/src/render3/instructions/change_detection.ts_5685_14221 | export function refreshView<T>(
tView: TView,
lView: LView,
templateFn: ComponentTemplate<{}> | null,
context: T,
) {
ngDevMode && assertEqual(isCreationMode(lView), false, 'Should be run in update mode');
const flags = lView[FLAGS];
if ((flags & LViewFlags.Destroyed) === LViewFlags.Destroyed) return;
// Check no changes mode is a dev only mode used to verify that bindings have not changed
// since they were assigned. We do not want to execute lifecycle hooks in that mode.
const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
const isInExhaustiveCheckNoChangesPass = ngDevMode && isExhaustiveCheckNoChanges();
// Start component reactive context
// - We might already be in a reactive context if this is an embedded view of the host.
// - We might be descending into a view that needs a consumer.
enterView(lView);
let returnConsumerToPool = true;
let prevConsumer: ReactiveNode | null = null;
let currentConsumer: ReactiveLViewConsumer | null = null;
if (!isInCheckNoChangesPass) {
if (viewShouldHaveReactiveConsumer(tView)) {
currentConsumer = getOrBorrowReactiveLViewConsumer(lView);
prevConsumer = consumerBeforeComputation(currentConsumer);
} else if (getActiveConsumer() === null) {
// If the current view should not have a reactive consumer but we don't have an active consumer,
// we still need to create a temporary consumer to track any signal reads in this template.
// This is a rare case that can happen with `viewContainerRef.createEmbeddedView(...).detectChanges()`.
// This temporary consumer marks the first parent that _should_ have a consumer for refresh.
// Once that refresh happens, the signals will be tracked in the parent consumer and we can destroy
// the temporary one.
returnConsumerToPool = false;
currentConsumer = getOrCreateTemporaryConsumer(lView);
prevConsumer = consumerBeforeComputation(currentConsumer);
} else if (lView[REACTIVE_TEMPLATE_CONSUMER]) {
consumerDestroy(lView[REACTIVE_TEMPLATE_CONSUMER]);
lView[REACTIVE_TEMPLATE_CONSUMER] = null;
}
}
try {
resetPreOrderHookFlags(lView);
setBindingIndex(tView.bindingStartIndex);
if (templateFn !== null) {
executeTemplate(tView, lView, templateFn, RenderFlags.Update, context);
}
const hooksInitPhaseCompleted =
(flags & LViewFlags.InitPhaseStateMask) === InitPhaseState.InitPhaseCompleted;
// execute pre-order hooks (OnInit, OnChanges, DoCheck)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!isInCheckNoChangesPass) {
if (hooksInitPhaseCompleted) {
const preOrderCheckHooks = tView.preOrderCheckHooks;
if (preOrderCheckHooks !== null) {
executeCheckHooks(lView, preOrderCheckHooks, null);
}
} else {
const preOrderHooks = tView.preOrderHooks;
if (preOrderHooks !== null) {
executeInitAndCheckHooks(lView, preOrderHooks, InitPhaseState.OnInitHooksToBeRun, null);
}
incrementInitPhaseFlags(lView, InitPhaseState.OnInitHooksToBeRun);
}
}
// We do not need to mark transplanted views for refresh when doing exhaustive checks
// because all views will be reached anyways during the traversal.
if (!isInExhaustiveCheckNoChangesPass) {
// First mark transplanted views that are declared in this lView as needing a refresh at their
// insertion points. This is needed to avoid the situation where the template is defined in this
// `LView` but its declaration appears after the insertion component.
markTransplantedViewsForRefresh(lView);
}
runEffectsInView(lView);
detectChangesInEmbeddedViews(lView, ChangeDetectionMode.Global);
// Content query results must be refreshed before content hooks are called.
if (tView.contentQueries !== null) {
refreshContentQueries(tView, lView);
}
// execute content hooks (AfterContentInit, AfterContentChecked)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!isInCheckNoChangesPass) {
if (hooksInitPhaseCompleted) {
const contentCheckHooks = tView.contentCheckHooks;
if (contentCheckHooks !== null) {
executeCheckHooks(lView, contentCheckHooks);
}
} else {
const contentHooks = tView.contentHooks;
if (contentHooks !== null) {
executeInitAndCheckHooks(
lView,
contentHooks,
InitPhaseState.AfterContentInitHooksToBeRun,
);
}
incrementInitPhaseFlags(lView, InitPhaseState.AfterContentInitHooksToBeRun);
}
}
processHostBindingOpCodes(tView, lView);
// Refresh child component views.
const components = tView.components;
if (components !== null) {
detectChangesInChildComponents(lView, components, ChangeDetectionMode.Global);
}
// View queries must execute after refreshing child components because a template in this view
// could be inserted in a child component. If the view query executes before child component
// refresh, the template might not yet be inserted.
const viewQuery = tView.viewQuery;
if (viewQuery !== null) {
executeViewQueryFn<T>(RenderFlags.Update, viewQuery, context);
}
// execute view hooks (AfterViewInit, AfterViewChecked)
// PERF WARNING: do NOT extract this to a separate function without running benchmarks
if (!isInCheckNoChangesPass) {
if (hooksInitPhaseCompleted) {
const viewCheckHooks = tView.viewCheckHooks;
if (viewCheckHooks !== null) {
executeCheckHooks(lView, viewCheckHooks);
}
} else {
const viewHooks = tView.viewHooks;
if (viewHooks !== null) {
executeInitAndCheckHooks(lView, viewHooks, InitPhaseState.AfterViewInitHooksToBeRun);
}
incrementInitPhaseFlags(lView, InitPhaseState.AfterViewInitHooksToBeRun);
}
}
if (tView.firstUpdatePass === true) {
// We need to make sure that we only flip the flag on successful `refreshView` only
// Don't do this in `finally` block.
// If we did this in `finally` block then an exception could block the execution of styling
// instructions which in turn would be unable to insert themselves into the styling linked
// list. The result of this would be that if the exception would not be throw on subsequent CD
// the styling would be unable to process it data and reflect to the DOM.
tView.firstUpdatePass = false;
}
// Schedule any effects that are waiting on the update pass of this view.
if (lView[EFFECTS_TO_SCHEDULE]) {
for (const notifyEffect of lView[EFFECTS_TO_SCHEDULE]) {
notifyEffect();
}
// Once they've been run, we can drop the array.
lView[EFFECTS_TO_SCHEDULE] = null;
}
// Do not reset the dirty state when running in check no changes mode. We don't want components
// to behave differently depending on whether check no changes is enabled or not. For example:
// Marking an OnPush component as dirty from within the `ngAfterViewInit` hook in order to
// refresh a `NgClass` binding should work. If we would reset the dirty state in the check
// no changes cycle, the component would be not be dirty for the next update pass. This would
// be different in production mode where the component dirty state is not reset.
if (!isInCheckNoChangesPass) {
lView[FLAGS] &= ~(LViewFlags.Dirty | LViewFlags.FirstLViewPass);
}
} catch (e) {
if (!isInCheckNoChangesPass) {
// If refreshing a view causes an error, we need to remark the ancestors as needing traversal
// because the error might have caused a situation where views below the current location are
// dirty but will be unreachable because the "has dirty children" flag in the ancestors has been
// cleared during change detection and we failed to run to completion.
markAncestorsForTraversal(lView);
}
throw e;
} finally {
if (currentConsumer !== null) {
consumerAfterComputation(currentConsumer, prevConsumer);
if (returnConsumerToPool) {
maybeReturnReactiveLViewConsumer(currentConsumer);
}
}
leaveView();
}
}
/**
* Goes over embedded views (ones created through ViewContainerRef APIs) and refreshes
* them by executing an associated template function.
*/ | {
"end_byte": 14221,
"start_byte": 5685,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/change_detection.ts"
} |
angular/packages/core/src/render3/instructions/change_detection.ts_14222_19065 | function detectChangesInEmbeddedViews(lView: LView, mode: ChangeDetectionMode) {
for (
let lContainer = getFirstLContainer(lView);
lContainer !== null;
lContainer = getNextLContainer(lContainer)
) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
const embeddedLView = lContainer[i];
detectChangesInViewIfAttached(embeddedLView, mode);
}
}
}
/**
* Mark transplanted views as needing to be refreshed at their attachment points.
*
* @param lView The `LView` that may have transplanted views.
*/
function markTransplantedViewsForRefresh(lView: LView) {
for (
let lContainer = getFirstLContainer(lView);
lContainer !== null;
lContainer = getNextLContainer(lContainer)
) {
if (!(lContainer[FLAGS] & LContainerFlags.HasTransplantedViews)) continue;
const movedViews = lContainer[MOVED_VIEWS]!;
ngDevMode && assertDefined(movedViews, 'Transplanted View flags set but missing MOVED_VIEWS');
for (let i = 0; i < movedViews.length; i++) {
const movedLView = movedViews[i]!;
markViewForRefresh(movedLView);
}
}
}
/**
* Detects changes in a component by entering the component view and processing its bindings,
* queries, etc. if it is CheckAlways, OnPush and Dirty, etc.
*
* @param componentHostIdx Element index in LView[] (adjusted for HEADER_OFFSET)
*/
function detectChangesInComponent(
hostLView: LView,
componentHostIdx: number,
mode: ChangeDetectionMode,
): void {
ngDevMode && assertEqual(isCreationMode(hostLView), false, 'Should be run in update mode');
const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
detectChangesInViewIfAttached(componentView, mode);
}
/**
* Visits a view as part of change detection traversal.
*
* If the view is detached, no additional traversal happens.
*/
function detectChangesInViewIfAttached(lView: LView, mode: ChangeDetectionMode) {
if (!viewAttachedToChangeDetector(lView)) {
return;
}
detectChangesInView(lView, mode);
}
/**
* Visits a view as part of change detection traversal.
*
* The view is refreshed if:
* - If the view is CheckAlways or Dirty and ChangeDetectionMode is `Global`
* - If the view has the `RefreshView` flag
*
* The view is not refreshed, but descendants are traversed in `ChangeDetectionMode.Targeted` if the
* view HasChildViewsToRefresh flag is set.
*/
function detectChangesInView(lView: LView, mode: ChangeDetectionMode) {
const isInCheckNoChangesPass = ngDevMode && isInCheckNoChangesMode();
const tView = lView[TVIEW];
const flags = lView[FLAGS];
const consumer = lView[REACTIVE_TEMPLATE_CONSUMER];
// Refresh CheckAlways views in Global mode.
let shouldRefreshView: boolean = !!(
mode === ChangeDetectionMode.Global && flags & LViewFlags.CheckAlways
);
// Refresh Dirty views in Global mode, as long as we're not in checkNoChanges.
// CheckNoChanges never worked with `OnPush` components because the `Dirty` flag was
// cleared before checkNoChanges ran. Because there is now a loop for to check for
// backwards views, it gives an opportunity for `OnPush` components to be marked `Dirty`
// before the CheckNoChanges pass. We don't want existing errors that are hidden by the
// current CheckNoChanges bug to surface when making unrelated changes.
shouldRefreshView ||= !!(
flags & LViewFlags.Dirty &&
mode === ChangeDetectionMode.Global &&
!isInCheckNoChangesPass
);
// Always refresh views marked for refresh, regardless of mode.
shouldRefreshView ||= !!(flags & LViewFlags.RefreshView);
// Refresh views when they have a dirty reactive consumer, regardless of mode.
shouldRefreshView ||= !!(consumer?.dirty && consumerPollProducersForChange(consumer));
shouldRefreshView ||= !!(ngDevMode && isExhaustiveCheckNoChanges());
// Mark the Flags and `ReactiveNode` as not dirty before refreshing the component, so that they
// can be re-dirtied during the refresh process.
if (consumer) {
consumer.dirty = false;
}
lView[FLAGS] &= ~(LViewFlags.HasChildViewsToRefresh | LViewFlags.RefreshView);
if (shouldRefreshView) {
refreshView(tView, lView, tView.template, lView[CONTEXT]);
} else if (flags & LViewFlags.HasChildViewsToRefresh) {
runEffectsInView(lView);
detectChangesInEmbeddedViews(lView, ChangeDetectionMode.Targeted);
const components = tView.components;
if (components !== null) {
detectChangesInChildComponents(lView, components, ChangeDetectionMode.Targeted);
}
}
}
/** Refreshes child components in the current view (update mode). */
function detectChangesInChildComponents(
hostLView: LView,
components: number[],
mode: ChangeDetectionMode,
): void {
for (let i = 0; i < components.length; i++) {
detectChangesInComponent(hostLView, components[i], mode);
}
} | {
"end_byte": 19065,
"start_byte": 14222,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/change_detection.ts"
} |
angular/packages/core/src/render3/instructions/render.ts_0_5951 | /**
* @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 {retrieveHydrationInfo} from '../../hydration/utils';
import {assertEqual, assertNotReactive} from '../../util/assert';
import {RenderFlags} from '../interfaces/definition';
import {
CONTEXT,
FLAGS,
HOST,
HYDRATION,
INJECTOR,
LView,
LViewFlags,
QUERIES,
TVIEW,
TView,
} from '../interfaces/view';
import {enterView, leaveView} from '../state';
import {getComponentLViewByIndex, isCreationMode} from '../util/view_utils';
import {executeTemplate, executeViewQueryFn, refreshContentQueries} from './shared';
export function renderComponent(hostLView: LView, componentHostIdx: number) {
ngDevMode && assertEqual(isCreationMode(hostLView), true, 'Should be run in creation mode');
const componentView = getComponentLViewByIndex(componentHostIdx, hostLView);
const componentTView = componentView[TVIEW];
syncViewWithBlueprint(componentTView, componentView);
const hostRNode = componentView[HOST];
// Populate an LView with hydration info retrieved from the DOM via TransferState.
if (hostRNode !== null && componentView[HYDRATION] === null) {
componentView[HYDRATION] = retrieveHydrationInfo(hostRNode, componentView[INJECTOR]!);
}
renderView(componentTView, componentView, componentView[CONTEXT]);
}
/**
* Syncs an LView instance with its blueprint if they have gotten out of sync.
*
* Typically, blueprints and their view instances should always be in sync, so the loop here
* will be skipped. However, consider this case of two components side-by-side:
*
* App template:
* ```
* <comp></comp>
* <comp></comp>
* ```
*
* The following will happen:
* 1. App template begins processing.
* 2. First <comp> is matched as a component and its LView is created.
* 3. Second <comp> is matched as a component and its LView is created.
* 4. App template completes processing, so it's time to check child templates.
* 5. First <comp> template is checked. It has a directive, so its def is pushed to blueprint.
* 6. Second <comp> template is checked. Its blueprint has been updated by the first
* <comp> template, but its LView was created before this update, so it is out of sync.
*
* Note that embedded views inside ngFor loops will never be out of sync because these views
* are processed as soon as they are created.
*
* @param tView The `TView` that contains the blueprint for syncing
* @param lView The view to sync
*/
export function syncViewWithBlueprint(tView: TView, lView: LView) {
for (let i = lView.length; i < tView.blueprint.length; i++) {
lView.push(tView.blueprint[i]);
}
}
/**
* Processes a view in the creation mode. This includes a number of steps in a specific order:
* - creating view query functions (if any);
* - executing a template function in the creation mode;
* - updating static queries (if any);
* - creating child components defined in a given view.
*/
export function renderView<T>(tView: TView, lView: LView<T>, context: T): void {
ngDevMode && assertEqual(isCreationMode(lView), true, 'Should be run in creation mode');
ngDevMode && assertNotReactive(renderView.name);
enterView(lView);
try {
const viewQuery = tView.viewQuery;
if (viewQuery !== null) {
executeViewQueryFn<T>(RenderFlags.Create, viewQuery, context);
}
// Execute a template associated with this view, if it exists. A template function might not be
// defined for the root component views.
const templateFn = tView.template;
if (templateFn !== null) {
executeTemplate<T>(tView, lView, templateFn, RenderFlags.Create, context);
}
// This needs to be set before children are processed to support recursive components.
// This must be set to false immediately after the first creation run because in an
// ngFor loop, all the views will be created together before update mode runs and turns
// off firstCreatePass. If we don't set it here, instances will perform directive
// matching, etc again and again.
if (tView.firstCreatePass) {
tView.firstCreatePass = false;
}
// Mark all queries active in this view as dirty. This is necessary for signal-based queries to
// have a clear marking point where we can read query results atomically (for a given view).
lView[QUERIES]?.finishViewCreation(tView);
// We resolve content queries specifically marked as `static` in creation mode. Dynamic
// content queries are resolved during change detection (i.e. update mode), after embedded
// views are refreshed (see block above).
if (tView.staticContentQueries) {
refreshContentQueries(tView, lView);
}
// We must materialize query results before child components are processed
// in case a child component has projected a container. The LContainer needs
// to exist so the embedded views are properly attached by the container.
if (tView.staticViewQueries) {
executeViewQueryFn<T>(RenderFlags.Update, tView.viewQuery!, context);
}
// Render child component views.
const components = tView.components;
if (components !== null) {
renderChildComponents(lView, components);
}
} catch (error) {
// If we didn't manage to get past the first template pass due to
// an error, mark the view as corrupted so we can try to recover.
if (tView.firstCreatePass) {
tView.incompleteFirstPass = true;
tView.firstCreatePass = false;
}
throw error;
} finally {
lView[FLAGS] &= ~LViewFlags.CreationMode;
leaveView();
}
}
/** Renders child components in the current view (creation mode). */
function renderChildComponents(hostLView: LView, components: number[]): void {
for (let i = 0; i < components.length; i++) {
renderComponent(hostLView, components[i]);
}
}
| {
"end_byte": 5951,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/render.ts"
} |
angular/packages/core/src/render3/instructions/element_validation.ts_0_6943 | /**
* @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 {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../../errors';
import {Type} from '../../interface/type';
import {CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, SchemaMetadata} from '../../metadata/schema';
import {throwError} from '../../util/assert';
import {getComponentDef} from '../def_getters';
import {ComponentDef} from '../interfaces/definition';
import {TNodeType} from '../interfaces/node';
import {RComment, RElement} from '../interfaces/renderer_dom';
import {CONTEXT, DECLARATION_COMPONENT_VIEW, LView} from '../interfaces/view';
import {isAnimationProp} from '../util/attrs_utils';
let shouldThrowErrorOnUnknownElement = false;
/**
* Sets a strict mode for JIT-compiled components to throw an error on unknown elements,
* instead of just logging the error.
* (for AOT-compiled ones this check happens at build time).
*/
export function ɵsetUnknownElementStrictMode(shouldThrow: boolean) {
shouldThrowErrorOnUnknownElement = shouldThrow;
}
/**
* Gets the current value of the strict mode.
*/
export function ɵgetUnknownElementStrictMode() {
return shouldThrowErrorOnUnknownElement;
}
let shouldThrowErrorOnUnknownProperty = false;
/**
* Sets a strict mode for JIT-compiled components to throw an error on unknown properties,
* instead of just logging the error.
* (for AOT-compiled ones this check happens at build time).
*/
export function ɵsetUnknownPropertyStrictMode(shouldThrow: boolean) {
shouldThrowErrorOnUnknownProperty = shouldThrow;
}
/**
* Gets the current value of the strict mode.
*/
export function ɵgetUnknownPropertyStrictMode() {
return shouldThrowErrorOnUnknownProperty;
}
/**
* Validates that the element is known at runtime and produces
* an error if it's not the case.
* This check is relevant for JIT-compiled components (for AOT-compiled
* ones this check happens at build time).
*
* The element is considered known if either:
* - it's a known HTML element
* - it's a known custom element
* - the element matches any directive
* - the element is allowed by one of the schemas
*
* @param element Element to validate
* @param lView An `LView` that represents a current component that is being rendered
* @param tagName Name of the tag to check
* @param schemas Array of schemas
* @param hasDirectives Boolean indicating that the element matches any directive
*/
export function validateElementIsKnown(
element: RElement,
lView: LView,
tagName: string | null,
schemas: SchemaMetadata[] | null,
hasDirectives: boolean,
): void {
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (schemas === null) return;
// If the element matches any directive, it's considered as valid.
if (!hasDirectives && tagName !== null) {
// The element is unknown if it's an instance of HTMLUnknownElement, or it isn't registered
// as a custom element. Note that unknown elements with a dash in their name won't be instances
// of HTMLUnknownElement in browsers that support web components.
const isUnknown =
// Note that we can't check for `typeof HTMLUnknownElement === 'function'` because
// Domino doesn't expose HTMLUnknownElement globally.
(typeof HTMLUnknownElement !== 'undefined' &&
HTMLUnknownElement &&
element instanceof HTMLUnknownElement) ||
(typeof customElements !== 'undefined' &&
tagName.indexOf('-') > -1 &&
!customElements.get(tagName));
if (isUnknown && !matchingSchemas(schemas, tagName)) {
const isHostStandalone = isHostComponentStandalone(lView);
const templateLocation = getTemplateLocationDetails(lView);
const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
let message = `'${tagName}' is not a known element${templateLocation}:\n`;
message += `1. If '${tagName}' is an Angular component, then verify that it is ${
isHostStandalone
? "included in the '@Component.imports' of this component"
: 'a part of an @NgModule where this component is declared'
}.\n`;
if (tagName && tagName.indexOf('-') > -1) {
message += `2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the ${schemas} of this component to suppress this message.`;
} else {
message += `2. To allow any element add 'NO_ERRORS_SCHEMA' to the ${schemas} of this component.`;
}
if (shouldThrowErrorOnUnknownElement) {
throw new RuntimeError(RuntimeErrorCode.UNKNOWN_ELEMENT, message);
} else {
console.error(formatRuntimeError(RuntimeErrorCode.UNKNOWN_ELEMENT, message));
}
}
}
}
/**
* Validates that the property of the element is known at runtime and returns
* false if it's not the case.
* This check is relevant for JIT-compiled components (for AOT-compiled
* ones this check happens at build time).
*
* The property is considered known if either:
* - it's a known property of the element
* - the element is allowed by one of the schemas
* - the property is used for animations
*
* @param element Element to validate
* @param propName Name of the property to check
* @param tagName Name of the tag hosting the property
* @param schemas Array of schemas
*/
export function isPropertyValid(
element: RElement | RComment,
propName: string,
tagName: string | null,
schemas: SchemaMetadata[] | null,
): boolean {
// If `schemas` is set to `null`, that's an indication that this Component was compiled in AOT
// mode where this check happens at compile time. In JIT mode, `schemas` is always present and
// defined as an array (as an empty array in case `schemas` field is not defined) and we should
// execute the check below.
if (schemas === null) return true;
// The property is considered valid if the element matches the schema, it exists on the element,
// or it is synthetic.
if (matchingSchemas(schemas, tagName) || propName in element || isAnimationProp(propName)) {
return true;
}
// Note: `typeof Node` returns 'function' in most browsers, but is undefined with domino.
return typeof Node === 'undefined' || Node === null || !(element instanceof Node);
}
/**
* Logs or throws an error that a property is not supported on an element.
*
* @param propName Name of the invalid property
* @param tagName Name of the tag hosting the property
* @param nodeType Type of the node hosting the property
* @param lView An `LView` that represents a current component
*/
exp | {
"end_byte": 6943,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/element_validation.ts"
} |
angular/packages/core/src/render3/instructions/element_validation.ts_6944_13226 | rt function handleUnknownPropertyError(
propName: string,
tagName: string | null,
nodeType: TNodeType,
lView: LView,
): void {
// Special-case a situation when a structural directive is applied to
// an `<ng-template>` element, for example: `<ng-template *ngIf="true">`.
// In this case the compiler generates the `ɵɵtemplate` instruction with
// the `null` as the tagName. The directive matching logic at runtime relies
// on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
// a default value of the `tNode.value` is not feasible at this moment.
if (!tagName && nodeType === TNodeType.Container) {
tagName = 'ng-template';
}
const isHostStandalone = isHostComponentStandalone(lView);
const templateLocation = getTemplateLocationDetails(lView);
let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
const importLocation = isHostStandalone
? "included in the '@Component.imports' of this component"
: 'a part of an @NgModule where this component is declared';
if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
// Most likely this is a control flow directive (such as `*ngIf`) used in
// a template, but the directive or the `CommonModule` is not imported.
const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
message +=
`\nIf the '${propName}' is an Angular control flow directive, ` +
`please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
} else {
// May be an Angular component, which is not imported/declared?
message +=
`\n1. If '${tagName}' is an Angular component and it has the ` +
`'${propName}' input, then verify that it is ${importLocation}.`;
// May be a Web Component?
if (tagName && tagName.indexOf('-') > -1) {
message +=
`\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` +
`to the ${schemas} of this component to suppress this message.`;
message +=
`\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
} else {
// If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
message +=
`\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
}
}
reportUnknownPropertyError(message);
}
export function reportUnknownPropertyError(message: string) {
if (shouldThrowErrorOnUnknownProperty) {
throw new RuntimeError(RuntimeErrorCode.UNKNOWN_BINDING, message);
} else {
console.error(formatRuntimeError(RuntimeErrorCode.UNKNOWN_BINDING, message));
}
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode and also it relies on the constructor function being available.
*
* Gets a reference to the host component def (where a current component is declared).
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function getDeclarationComponentDef(lView: LView): ComponentDef<unknown> | null {
!ngDevMode && throwError('Must never be called in production mode');
const declarationLView = lView[DECLARATION_COMPONENT_VIEW] as LView<Type<unknown>>;
const context = declarationLView[CONTEXT];
// Unable to obtain a context.
if (!context) return null;
return context.constructor ? getComponentDef(context.constructor) : null;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Checks if the current component is declared inside of a standalone component template.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function isHostComponentStandalone(lView: LView): boolean {
!ngDevMode && throwError('Must never be called in production mode');
const componentDef = getDeclarationComponentDef(lView);
// Treat host component as non-standalone if we can't obtain the def.
return !!componentDef?.standalone;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Constructs a string describing the location of the host component template. The function is used
* in dev mode to produce error messages.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function getTemplateLocationDetails(lView: LView): string {
!ngDevMode && throwError('Must never be called in production mode');
const hostComponentDef = getDeclarationComponentDef(lView);
const componentClassName = hostComponentDef?.type?.name;
return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
}
/**
* The set of known control flow directives and their corresponding imports.
* We use this set to produce a more precises error message with a note
* that the `CommonModule` should also be included.
*/
export const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([
['ngIf', 'NgIf'],
['ngFor', 'NgFor'],
['ngSwitchCase', 'NgSwitchCase'],
['ngSwitchDefault', 'NgSwitchDefault'],
]);
/**
* Returns true if the tag name is allowed by specified schemas.
* @param schemas Array of schemas
* @param tagName Name of the tag
*/
export function matchingSchemas(schemas: SchemaMetadata[] | null, tagName: string | null): boolean {
if (schemas !== null) {
for (let i = 0; i < schemas.length; i++) {
const schema = schemas[i];
if (
schema === NO_ERRORS_SCHEMA ||
(schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1)
) {
return true;
}
}
}
return false;
}
| {
"end_byte": 13226,
"start_byte": 6944,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/element_validation.ts"
} |
angular/packages/core/src/render3/instructions/property.ts_0_2482 | /**
* @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 {TNode} from '../interfaces/node';
import {SanitizerFn} from '../interfaces/sanitization';
import {LView, RENDERER, TView} from '../interfaces/view';
import {getLView, getSelectedTNode, getTView, nextBindingIndex} from '../state';
import {
elementPropertyInternal,
setInputsForProperty,
storePropertyBindingMetadata,
} from './shared';
/**
* Update a property on a selected element.
*
* Operates on the element selected by index via the {@link select} instruction.
*
* 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 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 ɵɵproperty<T>(
propName: string,
value: T,
sanitizer?: SanitizerFn | null,
): typeof ɵɵproperty {
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 ɵɵproperty;
}
/**
* Given `<div style="..." my-dir>` and `MyDir` with `@Input('style')` we need to write to
* directive input.
*/
export function setDirectiveInputsWhichShadowsStyling(
tView: TView,
tNode: TNode,
lView: LView,
value: any,
isClassBased: boolean,
) {
const inputs = tNode.inputs!;
const property = isClassBased ? 'class' : 'style';
// We support both 'class' and `className` hence the fallback.
setInputsForProperty(tView, lView, inputs[property], property, value);
}
| {
"end_byte": 2482,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/property.ts"
} |
angular/packages/core/src/render3/instructions/interpolation.ts_0_6539 | /**
* @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 {assertEqual, assertLessThan} from '../../util/assert';
import {bindingUpdated, bindingUpdated2, bindingUpdated3, bindingUpdated4} from '../bindings';
import {LView} from '../interfaces/view';
import {getBindingIndex, incrementBindingIndex, nextBindingIndex, setBindingIndex} from '../state';
import {NO_CHANGE} from '../tokens';
import {renderStringify} from '../util/stringify_utils';
/**
* Create interpolation bindings with a variable number of expressions.
*
* If there are 1 to 8 expressions `interpolation1()` to `interpolation8()` should be used instead.
* Those are faster because there is no need to create an array of expressions and iterate over it.
*
* `values`:
* - has static text at even indexes,
* - has evaluated expressions at odd indexes.
*
* Returns the concatenated string when any of the arguments changes, `NO_CHANGE` otherwise.
*/
export function interpolationV(lView: LView, values: any[]): string | NO_CHANGE {
ngDevMode && assertLessThan(2, values.length, 'should have at least 3 values');
ngDevMode && assertEqual(values.length % 2, 1, 'should have an odd number of values');
let isBindingUpdated = false;
let bindingIndex = getBindingIndex();
for (let i = 1; i < values.length; i += 2) {
// Check if bindings (odd indexes) have changed
isBindingUpdated = bindingUpdated(lView, bindingIndex++, values[i]) || isBindingUpdated;
}
setBindingIndex(bindingIndex);
if (!isBindingUpdated) {
return NO_CHANGE;
}
// Build the updated content
let content = values[0];
for (let i = 1; i < values.length; i += 2) {
content += renderStringify(values[i]) + values[i + 1];
}
return content;
}
/**
* Creates an interpolation binding with 1 expression.
*
* @param prefix static value used for concatenation only.
* @param v0 value checked for change.
* @param suffix static value used for concatenation only.
*/
export function interpolation1(
lView: LView,
prefix: string,
v0: any,
suffix: string,
): string | NO_CHANGE {
const different = bindingUpdated(lView, nextBindingIndex(), v0);
return different ? prefix + renderStringify(v0) + suffix : NO_CHANGE;
}
/**
* Creates an interpolation binding with 2 expressions.
*/
export function interpolation2(
lView: LView,
prefix: string,
v0: any,
i0: string,
v1: any,
suffix: string,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
const different = bindingUpdated2(lView, bindingIndex, v0, v1);
incrementBindingIndex(2);
return different ? prefix + renderStringify(v0) + i0 + renderStringify(v1) + suffix : NO_CHANGE;
}
/**
* Creates an interpolation binding with 3 expressions.
*/
export function interpolation3(
lView: LView,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
suffix: string,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
const different = bindingUpdated3(lView, bindingIndex, v0, v1, v2);
incrementBindingIndex(3);
return different
? prefix + renderStringify(v0) + i0 + renderStringify(v1) + i1 + renderStringify(v2) + suffix
: NO_CHANGE;
}
/**
* Create an interpolation binding with 4 expressions.
*/
export function interpolation4(
lView: LView,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
i2: string,
v3: any,
suffix: string,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
const different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
incrementBindingIndex(4);
return different
? prefix +
renderStringify(v0) +
i0 +
renderStringify(v1) +
i1 +
renderStringify(v2) +
i2 +
renderStringify(v3) +
suffix
: NO_CHANGE;
}
/**
* Creates an interpolation binding with 5 expressions.
*/
export function interpolation5(
lView: LView,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
i2: string,
v3: any,
i3: string,
v4: any,
suffix: string,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated(lView, bindingIndex + 4, v4) || different;
incrementBindingIndex(5);
return different
? prefix +
renderStringify(v0) +
i0 +
renderStringify(v1) +
i1 +
renderStringify(v2) +
i2 +
renderStringify(v3) +
i3 +
renderStringify(v4) +
suffix
: NO_CHANGE;
}
/**
* Creates an interpolation binding with 6 expressions.
*/
export function interpolation6(
lView: LView,
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,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated2(lView, bindingIndex + 4, v4, v5) || different;
incrementBindingIndex(6);
return different
? prefix +
renderStringify(v0) +
i0 +
renderStringify(v1) +
i1 +
renderStringify(v2) +
i2 +
renderStringify(v3) +
i3 +
renderStringify(v4) +
i4 +
renderStringify(v5) +
suffix
: NO_CHANGE;
}
/**
* Creates an interpolation binding with 7 expressions.
*/
export function interpolation7(
lView: LView,
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,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated3(lView, bindingIndex + 4, v4, v5, v6) || different;
incrementBindingIndex(7);
return different
? prefix +
renderStringify(v0) +
i0 +
renderStringify(v1) +
i1 +
renderStringify(v2) +
i2 +
renderStringify(v3) +
i3 +
renderStringify(v4) +
i4 +
renderStringify(v5) +
i5 +
renderStringify(v6) +
suffix
: NO_CHANGE;
}
/**
* Creates an interpolation binding with 8 expressions.
*/ | {
"end_byte": 6539,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/interpolation.ts"
} |
angular/packages/core/src/render3/instructions/interpolation.ts_6540_7460 | export function interpolation8(
lView: LView,
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,
): string | NO_CHANGE {
const bindingIndex = getBindingIndex();
let different = bindingUpdated4(lView, bindingIndex, v0, v1, v2, v3);
different = bindingUpdated4(lView, bindingIndex + 4, v4, v5, v6, v7) || different;
incrementBindingIndex(8);
return different
? prefix +
renderStringify(v0) +
i0 +
renderStringify(v1) +
i1 +
renderStringify(v2) +
i2 +
renderStringify(v3) +
i3 +
renderStringify(v4) +
i4 +
renderStringify(v5) +
i5 +
renderStringify(v6) +
i6 +
renderStringify(v7) +
suffix
: NO_CHANGE;
} | {
"end_byte": 7460,
"start_byte": 6540,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/interpolation.ts"
} |
angular/packages/core/src/render3/instructions/write_to_directive_input.ts_0_2130 | /**
* @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, SIGNAL} from '@angular/core/primitives/signals';
import {InputSignalWithTransform} from '../../authoring/input/input_signal';
import {InputSignalNode} from '../../authoring/input/input_signal_node';
import {applyValueToInputField} from '../apply_value_input_field';
import {DirectiveDef} from '../interfaces/definition';
import {InputFlags} from '../interfaces/input_flags';
export function writeToDirectiveInput<T>(
def: DirectiveDef<T>,
instance: T,
publicName: string,
privateName: string,
flags: InputFlags,
value: unknown,
) {
const prevConsumer = setActiveConsumer(null);
try {
// If we know we are dealing with a signal input, we cache its reference
// in a tree-shakable way. The input signal node can then be used for
// value transform execution or actual value updates without introducing
// additional megamorphic accesses for accessing the instance field.
let inputSignalNode: InputSignalNode<unknown, unknown> | null = null;
if ((flags & InputFlags.SignalBased) !== 0) {
const field = (instance as any)[privateName] as InputSignalWithTransform<unknown, unknown>;
inputSignalNode = field[SIGNAL];
}
// If there is a signal node and a transform, run it before potentially
// delegating to features like `NgOnChanges`.
if (inputSignalNode !== null && inputSignalNode.transformFn !== undefined) {
value = inputSignalNode.transformFn(value);
}
// If there is a decorator input transform, run it.
if ((flags & InputFlags.HasDecoratorInputTransform) !== 0) {
value = def.inputTransforms![privateName]!.call(instance, value);
}
if (def.setInput !== null) {
def.setInput(instance, inputSignalNode, value, publicName, privateName);
} else {
applyValueToInputField(instance, inputSignalNode, privateName, value);
}
} finally {
setActiveConsumer(prevConsumer);
}
}
| {
"end_byte": 2130,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/write_to_directive_input.ts"
} |
angular/packages/core/src/render3/instructions/i18n_icu_container_visitor.ts_0_3443 | /**
* @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, assertNumber, assertNumberInRange} from '../../util/assert';
import {EMPTY_ARRAY} from '../../util/empty';
import {assertTIcu, assertTNodeForLView} from '../assert';
import {getCurrentICUCaseIndex} from '../i18n/i18n_util';
import {I18nRemoveOpCodes, TIcu} from '../interfaces/i18n';
import {TIcuContainerNode} from '../interfaces/node';
import {RNode} from '../interfaces/renderer_dom';
import {LView, TVIEW} from '../interfaces/view';
interface IcuIteratorState {
stack: any[];
index: number;
lView?: LView;
removes?: I18nRemoveOpCodes;
}
type IcuIterator = () => RNode | null;
function enterIcu(state: IcuIteratorState, tIcu: TIcu, lView: LView) {
state.index = 0;
const currentCase = getCurrentICUCaseIndex(tIcu, lView);
if (currentCase !== null) {
ngDevMode && assertNumberInRange(currentCase, 0, tIcu.cases.length - 1);
state.removes = tIcu.remove[currentCase];
} else {
state.removes = EMPTY_ARRAY as any;
}
}
function icuContainerIteratorNext(state: IcuIteratorState): RNode | null {
if (state.index < state.removes!.length) {
const removeOpCode = state.removes![state.index++] as number;
ngDevMode && assertNumber(removeOpCode, 'Expecting OpCode number');
if (removeOpCode > 0) {
const rNode = state.lView![removeOpCode];
ngDevMode && assertDomNode(rNode);
return rNode;
} else {
state.stack.push(state.index, state.removes);
// ICUs are represented by negative indices
const tIcuIndex = ~removeOpCode;
const tIcu = state.lView![TVIEW].data[tIcuIndex] as TIcu;
ngDevMode && assertTIcu(tIcu);
enterIcu(state, tIcu, state.lView!);
return icuContainerIteratorNext(state);
}
} else {
if (state.stack.length === 0) {
return null;
} else {
state.removes = state.stack.pop();
state.index = state.stack.pop();
return icuContainerIteratorNext(state);
}
}
}
export function loadIcuContainerVisitor() {
const _state: IcuIteratorState = {
stack: [],
index: -1,
};
/**
* Retrieves a set of root nodes from `TIcu.remove`. Used by `TNodeType.ICUContainer`
* to determine which root belong to the ICU.
*
* Example of usage.
* ```
* const nextRNode = icuContainerIteratorStart(tIcuContainerNode, lView);
* let rNode: RNode|null;
* while(rNode = nextRNode()) {
* console.log(rNode);
* }
* ```
*
* @param tIcuContainerNode Current `TIcuContainerNode`
* @param lView `LView` where the `RNode`s should be looked up.
*/
function icuContainerIteratorStart(
tIcuContainerNode: TIcuContainerNode,
lView: LView,
): IcuIterator {
_state.lView = lView;
while (_state.stack.length) _state.stack.pop();
ngDevMode && assertTNodeForLView(tIcuContainerNode, lView);
enterIcu(_state, tIcuContainerNode.value, lView);
return icuContainerIteratorNext.bind(null, _state);
}
return icuContainerIteratorStart;
}
export function createIcuIterator(tIcu: TIcu, lView: LView): IcuIterator {
const state: IcuIteratorState = {
stack: [],
index: -1,
lView,
};
ngDevMode && assertTIcu(tIcu);
enterIcu(state, tIcu, lView);
return icuContainerIteratorNext.bind(null, state);
}
| {
"end_byte": 3443,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/i18n_icu_container_visitor.ts"
} |
angular/packages/core/src/render3/instructions/get_current_view.ts_0_710 | /**
* @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 {OpaqueViewState} from '../interfaces/view';
import {getLView} from '../state';
/**
* Returns the current OpaqueViewState instance.
*
* Used in conjunction with the restoreView() instruction to save a snapshot
* of the current view and restore it when listeners are invoked. This allows
* walking the declaration view tree in listeners to get vars from parent views.
*
* @codeGenApi
*/
export function ɵɵgetCurrentView(): OpaqueViewState {
return getLView() as any as OpaqueViewState;
}
| {
"end_byte": 710,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/get_current_view.ts"
} |
angular/packages/core/src/render3/instructions/attribute.ts_0_1508 | /**
* @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 {getLView, getSelectedTNode, getTView, nextBindingIndex} from '../state';
import {elementAttributeInternal, storePropertyBindingMetadata} from './shared';
/**
* Updates the value of or removes a bound attribute on an Element.
*
* Used in the case of `[attr.title]="value"`
*
* @param name name The name of the attribute.
* @param value value The attribute is removed when value is `null` or `undefined`.
* Otherwise the attribute value is set to the stringified value.
* @param sanitizer An optional function used to sanitize the value.
* @param namespace Optional namespace to use when setting the attribute.
*
* @codeGenApi
*/
export function ɵɵattribute(
name: string,
value: any,
sanitizer?: SanitizerFn | null,
namespace?: string,
): typeof ɵɵattribute {
const lView = getLView();
const bindingIndex = nextBindingIndex();
if (bindingUpdated(lView, bindingIndex, value)) {
const tView = getTView();
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, name, value, sanitizer, namespace);
ngDevMode && storePropertyBindingMetadata(tView.data, tNode, 'attr.' + name, bindingIndex);
}
return ɵɵattribute;
}
| {
"end_byte": 1508,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/attribute.ts"
} |
angular/packages/core/src/render3/instructions/queries_signals.ts_0_2456 | /**
* @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/provider_token';
import {QueryFlags} from '../interfaces/query';
import {createContentQuery, createViewQuery} from '../query';
import {bindQueryToSignal} from '../query_reactive';
import {Signal} from '../reactivity/api';
import {getCurrentQueryIndex, setCurrentQueryIndex} from '../state';
/**
* Creates a new content query and binds it to a signal created by an authoring function.
*
* @param directiveIndex Current directive index
* @param target The target signal to which the query should be bound
* @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 ɵɵcontentQuerySignal<T>(
directiveIndex: number,
target: Signal<T>,
predicate: ProviderToken<unknown> | string[],
flags: QueryFlags,
read?: any,
): void {
bindQueryToSignal(target, createContentQuery(directiveIndex, predicate, flags, read));
}
/**
* Creates a new view query by initializing internal data structures and binding a new query to the
* target signal.
*
* @param target The target signal to assign the query results to.
* @param predicate The type or label that should match a given query
* @param flags Flags associated with the query
* @param read What to save in the query
*
* @codeGenApi
*/
export function ɵɵviewQuerySignal(
target: Signal<unknown>,
predicate: ProviderToken<unknown> | string[],
flags: QueryFlags,
read?: ProviderToken<unknown>,
): void {
bindQueryToSignal(target, createViewQuery(predicate, flags, read));
}
/**
* Advances the current query index by a specified offset.
*
* Adjusting the current query index is necessary in cases where a given directive has a mix of
* zone-based and signal-based queries. The signal-based queries don't require tracking of the
* current index (those are refreshed on demand and not during change detection) so this instruction
* is only necessary for backward-compatibility.
*
* @param index offset to apply to the current query index (defaults to 1)
*
* @codeGenApi
*/
export function ɵɵqueryAdvance(indexOffset: number = 1): void {
setCurrentQueryIndex(getCurrentQueryIndex() + indexOffset);
}
| {
"end_byte": 2456,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/queries_signals.ts"
} |
angular/packages/core/src/render3/instructions/style_map_interpolation.ts_0_5911 | /**
* @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} from '../state';
import {
interpolation1,
interpolation2,
interpolation3,
interpolation4,
interpolation5,
interpolation6,
interpolation7,
interpolation8,
interpolationV,
} from './interpolation';
import {ɵɵstyleMap} from './styling';
/**
*
* Update an interpolated style 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 style="key: {{v0}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate1('key: ', 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 ɵɵstyleMapInterpolate1(prefix: string, v0: any, suffix: string): void {
const lView = getLView();
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key1: {{v1}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate2('key: ', v0, '; key1: ', 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 ɵɵstyleMapInterpolate2(
prefix: string,
v0: any,
i0: string,
v1: any,
suffix: string,
): void {
const lView = getLView();
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key2: {{v1}}; key2: {{v2}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate3(
* 'key: ', v0, '; key1: ', v1, '; key2: ', 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 ɵɵstyleMapInterpolate3(
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);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate4(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', 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 ɵɵstyleMapInterpolate4(
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);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate5(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', 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 ɵɵstyleMapInterpolate5(
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,
);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolat | {
"end_byte": 5911,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_map_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/style_map_interpolation.ts_5913_11305 | style 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 style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}};
* key5: {{v5}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate6(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', 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 ɵɵstyleMapInterpolate6(
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,
);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate7(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', 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 ɵɵstyleMapInterpolate7(
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,
);
ɵɵstyleMap(interpolatedValue);
}
/**
*
* Update an interpolated style 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 style="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}; key7: {{v7}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolate8(
* 'key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', v6, '; key7: ', 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 ɵɵstyleMapInterpolate8(
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,
);
ɵɵstyleMap(interpolatedValue);
}
/**
* Update an interpolated style on an elemen | {
"end_byte": 11305,
"start_byte": 5913,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_map_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/style_map_interpolation.ts_11307_12393 | with 9 or more bound values surrounded by text.
*
* Used when the number of interpolated values exceeds 8.
*
* ```html
* <div
* class="key: {{v0}}; key1: {{v1}}; key2: {{v2}}; key3: {{v3}}; key4: {{v4}}; key5: {{v5}};
* key6: {{v6}}; key7: {{v7}}; key8: {{v8}}; key9: {{v9}}suffix"></div>
* ```
*
* Its compiled representation is:
*
* ```ts
* ɵɵstyleMapInterpolateV(
* ['key: ', v0, '; key1: ', v1, '; key2: ', v2, '; key3: ', v3, '; key4: ', v4, '; key5: ', v5,
* '; key6: ', v6, '; key7: ', v7, '; key8: ', v8, '; key9: ', 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, '; key2: ', value1, '; key2: ', value2, ..., value99, 'suffix']`)
* @codeGenApi
*/
export function ɵɵstyleMapInterpolateV(values: any[]): void {
const lView = getLView();
const interpolatedValue = interpolationV(lView, values);
ɵɵstyleMap(interpolatedValue);
}
| {
"end_byte": 12393,
"start_byte": 11307,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/style_map_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/mark_view_dirty.ts_0_2404 | /**
* @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 {NotificationSource} from '../../change_detection/scheduling/zoneless_scheduling';
import {isRootView} from '../interfaces/type_checks';
import {ENVIRONMENT, FLAGS, LView, LViewFlags} from '../interfaces/view';
import {isRefreshingViews} from '../state';
import {getLViewParent} from '../util/view_utils';
/**
* Marks current view and all ancestors dirty.
*
* Returns the root view because it is found as a byproduct of marking the view tree
* dirty, and can be used by methods that consume markViewDirty() to easily schedule
* change detection. Otherwise, such methods would need to traverse up the view tree
* an additional time to get the root view and schedule a tick on it.
*
* @param lView The starting LView to mark dirty
* @returns the root LView
*/
export function markViewDirty(lView: LView, source: NotificationSource): LView | null {
const dirtyBitsToUse = isRefreshingViews()
? // When we are actively refreshing views, we only use the `Dirty` bit to mark a view
// for check. This bit is ignored in ChangeDetectionMode.Targeted, which is used to
// synchronously rerun change detection on a specific set of views (those which have
// the `RefreshView` flag and those with dirty signal consumers). `LViewFlags.Dirty`
// does not support re-entrant change detection on its own.
LViewFlags.Dirty
: // When we are not actively refreshing a view tree, it is absolutely
// valid to update state and mark views dirty. We use the `RefreshView` flag in this
// case to allow synchronously rerunning change detection. This applies today to
// afterRender hooks as well as animation listeners which execute after detecting
// changes in a view when the render factory flushes.
LViewFlags.RefreshView | LViewFlags.Dirty;
lView[ENVIRONMENT].changeDetectionScheduler?.notify(source);
while (lView) {
lView[FLAGS] |= dirtyBitsToUse;
const parent = getLViewParent(lView);
// Stop traversing up as soon as you find a root view that wasn't attached to any container
if (isRootView(lView) && !parent) {
return lView;
}
// continue otherwise
lView = parent!;
}
return null;
}
| {
"end_byte": 2404,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/mark_view_dirty.ts"
} |
angular/packages/core/src/render3/instructions/attribute_interpolation.ts_0_7210 | /**
* @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 {getBindingIndex, getLView, getSelectedTNode, getTView} from '../state';
import {NO_CHANGE} from '../tokens';
import {
interpolation1,
interpolation2,
interpolation3,
interpolation4,
interpolation5,
interpolation6,
interpolation7,
interpolation8,
interpolationV,
} from './interpolation';
import {elementAttributeInternal, storePropertyBindingMetadata} from './shared';
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate1('title', 'prefix', v0, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate1(
attrName: string,
prefix: string,
v0: any,
suffix: string,
sanitizer?: SanitizerFn,
namespace?: string,
): typeof ɵɵattributeInterpolate1 {
const lView = getLView();
const interpolatedValue = interpolation1(lView, prefix, v0, suffix);
if (interpolatedValue !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 1,
prefix,
suffix,
);
}
return ɵɵattributeInterpolate1;
}
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}-{{v1}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate2('title', 'prefix', v0, '-', v1, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate2(
attrName: string,
prefix: string,
v0: any,
i0: string,
v1: any,
suffix: string,
sanitizer?: SanitizerFn,
namespace?: string,
): typeof ɵɵattributeInterpolate2 {
const lView = getLView();
const interpolatedValue = interpolation2(lView, prefix, v0, i0, v1, suffix);
if (interpolatedValue !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 2,
prefix,
i0,
suffix,
);
}
return ɵɵattributeInterpolate2;
}
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}-{{v1}}-{{v2}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate3(
* 'title', 'prefix', v0, '-', v1, '-', v2, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate3(
attrName: string,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
suffix: string,
sanitizer?: SanitizerFn,
namespace?: string,
): typeof ɵɵattributeInterpolate3 {
const lView = getLView();
const interpolatedValue = interpolation3(lView, prefix, v0, i0, v1, i1, v2, suffix);
if (interpolatedValue !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 3,
prefix,
i0,
i1,
suffix,
);
}
return ɵɵattributeInterpolate3;
}
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate4(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate4(
attrName: string,
prefix: string,
v0: any,
i0: string,
v1: any,
i1: string,
v2: any,
i2: string,
v3: any,
suffix: string,
sanitizer?: SanitizerFn,
namespace?: string,
): typeof ɵɵattributeInterpolate4 {
const lView = getLView();
const interpolatedValue = interpolation4(lView, prefix, v0, i0, v1, i1, v2, i2, v3, suffix);
if (interpolatedValue !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 4,
prefix,
i0,
i1,
i2,
suffix,
);
}
return ɵɵattributeInterpolate4;
}
/**
*
* Update an interpolat | {
"end_byte": 7210,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/attribute_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/attribute_interpolation.ts_7212_13948 | attribute 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 attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate5(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate5(
attrName: 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,
namespace?: string,
): typeof ɵɵattributeInterpolate5 {
const lView = getLView();
const interpolatedValue = interpolation5(
lView,
prefix,
v0,
i0,
v1,
i1,
v2,
i2,
v3,
i3,
v4,
suffix,
);
if (interpolatedValue !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 5,
prefix,
i0,
i1,
i2,
i3,
suffix,
);
}
return ɵɵattributeInterpolate5;
}
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate6(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate6(
attrName: 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,
namespace?: string,
): typeof ɵɵattributeInterpolate6 {
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 tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 6,
prefix,
i0,
i1,
i2,
i3,
i4,
suffix,
);
}
return ɵɵattributeInterpolate6;
}
/**
*
* Update an interpolated attribute 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 attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate7(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate7(
attrName: 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,
namespace?: string,
): typeof ɵɵattributeInterpolate7 {
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 tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 7,
prefix,
i0,
i1,
i2,
i3,
i4,
i5,
suffix,
);
}
return ɵɵattributeInterpolate7;
}
/**
*
* Update an interpolated attribute on an eleme | {
"end_byte": 13948,
"start_byte": 7212,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/attribute_interpolation.ts"
} |
angular/packages/core/src/render3/instructions/attribute_interpolation.ts_13950_18284 | with 8 bound values surrounded by text.
*
* Used when the value passed to a property has 8 interpolated values in it:
*
* ```html
* <div attr.title="prefix{{v0}}-{{v1}}-{{v2}}-{{v3}}-{{v4}}-{{v5}}-{{v6}}-{{v7}}suffix"></div>
* ```
*
* Its compiled representation is::
*
* ```ts
* ɵɵattributeInterpolate8(
* 'title', 'prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, 'suffix');
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolate8(
attrName: 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,
namespace?: string,
): typeof ɵɵattributeInterpolate8 {
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 tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolatedValue, sanitizer, namespace);
ngDevMode &&
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - 8,
prefix,
i0,
i1,
i2,
i3,
i4,
i5,
i6,
suffix,
);
}
return ɵɵattributeInterpolate8;
}
/**
* Update an interpolated attribute on an element with 9 or more bound 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
* ɵɵattributeInterpolateV(
* 'title', ['prefix', v0, '-', v1, '-', v2, '-', v3, '-', v4, '-', v5, '-', v6, '-', v7, '-', v9,
* 'suffix']);
* ```
*
* @param attrName The name of the attribute 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 ɵɵattributeInterpolateV(
attrName: string,
values: any[],
sanitizer?: SanitizerFn,
namespace?: string,
): typeof ɵɵattributeInterpolateV {
const lView = getLView();
const interpolated = interpolationV(lView, values);
if (interpolated !== NO_CHANGE) {
const tNode = getSelectedTNode();
elementAttributeInternal(tNode, lView, attrName, interpolated, sanitizer, namespace);
if (ngDevMode) {
const interpolationInBetween = [values[0]]; // prefix
for (let i = 2; i < values.length; i += 2) {
interpolationInBetween.push(values[i]);
}
storePropertyBindingMetadata(
getTView().data,
tNode,
'attr.' + attrName,
getBindingIndex() - interpolationInBetween.length + 1,
...interpolationInBetween,
);
}
}
return ɵɵattributeInterpolateV;
}
| {
"end_byte": 18284,
"start_byte": 13950,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/instructions/attribute_interpolation.ts"
} |
angular/packages/core/src/render3/util/change_detection_utils.ts_0_1660 | /**
* @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 {NotificationSource} from '../../change_detection/scheduling/zoneless_scheduling';
import {assertDefined} from '../../util/assert';
import {getComponentViewByInstance} from '../context_discovery';
import {detectChangesInternal} from '../instructions/change_detection';
import {markViewDirty} from '../instructions/mark_view_dirty';
import {FLAGS, LViewFlags} from '../interfaces/view';
import {getRootComponents} from './discovery_utils';
/**
* Marks a component for check (in case of OnPush components) and synchronously
* performs change detection on the application this component belongs to.
*
* @param component Component to {@link ChangeDetectorRef#markForCheck mark for check}.
*
* @publicApi
*/
export function applyChanges(component: {}): void {
ngDevMode && assertDefined(component, 'component');
markViewDirty(getComponentViewByInstance(component), NotificationSource.DebugApplyChanges);
getRootComponents(component).forEach((rootComponent) => detectChanges(rootComponent));
}
/**
* Synchronously perform change detection on a component (and possibly its sub-components).
*
* This function triggers change detection in a synchronous way on a component.
*
* @param component The component which the change detection should be performed on.
*/
function detectChanges(component: {}): void {
const view = getComponentViewByInstance(component);
view[FLAGS] |= LViewFlags.RefreshView;
detectChangesInternal(view);
}
| {
"end_byte": 1660,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/change_detection_utils.ts"
} |
angular/packages/core/src/render3/util/global_utils.ts_0_4884 | /**
* @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 {global} from '../../util/global';
import {setupFrameworkInjectorProfiler} from '../debug/framework_injector_profiler';
import {setProfiler} from '../profiler';
import {isSignal} from '../reactivity/api';
import {applyChanges} from './change_detection_utils';
import {
getComponent,
getContext,
getDirectiveMetadata,
getDirectives,
getHostElement,
getInjector,
getListeners,
getOwningComponent,
getRootComponents,
} from './discovery_utils';
import {
getDependenciesFromInjectable,
getInjectorMetadata,
getInjectorProviders,
getInjectorResolutionPath,
} from './injector_discovery_utils';
/**
* This file introduces series of globally accessible debug tools
* to allow for the Angular debugging story to function.
*
* To see this in action run the following command:
*
* bazel run //packages/core/test/bundling/todo:devserver
*
* Then load `localhost:5432` and start using the console tools.
*/
/**
* This value reflects the property on the window where the dev
* tools are patched (window.ng).
* */
export const GLOBAL_PUBLISH_EXPANDO_KEY = 'ng';
// Typing for externally published global util functions
// Ideally we should be able to use `NgGlobalPublishUtils` using declaration merging but that doesn't work with API extractor yet.
// Have included the typings to have type safety when working with editors that support it (VSCode).
interface NgGlobalPublishUtils {
ɵgetLoadedRoutes(route: any): any;
}
const globalUtilsFunctions = {
/**
* Warning: functions that start with `ɵ` are considered *INTERNAL* and should not be relied upon
* in application's code. The contract of those functions might be changed in any release and/or a
* function can be removed completely.
*/
'ɵgetDependenciesFromInjectable': getDependenciesFromInjectable,
'ɵgetInjectorProviders': getInjectorProviders,
'ɵgetInjectorResolutionPath': getInjectorResolutionPath,
'ɵgetInjectorMetadata': getInjectorMetadata,
'ɵsetProfiler': setProfiler,
'getDirectiveMetadata': getDirectiveMetadata,
'getComponent': getComponent,
'getContext': getContext,
'getListeners': getListeners,
'getOwningComponent': getOwningComponent,
'getHostElement': getHostElement,
'getInjector': getInjector,
'getRootComponents': getRootComponents,
'getDirectives': getDirectives,
'applyChanges': applyChanges,
'isSignal': isSignal,
};
type CoreGlobalUtilsFunctions = keyof typeof globalUtilsFunctions;
type ExternalGlobalUtilsFunctions = keyof NgGlobalPublishUtils;
let _published = false;
/**
* Publishes a collection of default debug tools onto`window.ng`.
*
* These functions are available globally when Angular is in development
* mode and are automatically stripped away from prod mode is on.
*/
export function publishDefaultGlobalUtils() {
if (!_published) {
_published = true;
if (typeof window !== 'undefined') {
// Only configure the injector profiler when running in the browser.
setupFrameworkInjectorProfiler();
}
for (const [methodName, method] of Object.entries(globalUtilsFunctions)) {
publishGlobalUtil(methodName as CoreGlobalUtilsFunctions, method);
}
}
}
/**
* Default debug tools available under `window.ng`.
*/
export type GlobalDevModeUtils = {
[GLOBAL_PUBLISH_EXPANDO_KEY]: typeof globalUtilsFunctions;
};
/**
* Publishes the given function to `window.ng` so that it can be
* used from the browser console when an application is not in production.
*/
export function publishGlobalUtil<K extends CoreGlobalUtilsFunctions>(
name: K,
fn: (typeof globalUtilsFunctions)[K],
): void {
publishUtil(name, fn);
}
/**
* Publishes the given function to `window.ng` from package other than @angular/core
* So that it can be used from the browser console when an application is not in production.
*/
export function publishExternalGlobalUtil<K extends ExternalGlobalUtilsFunctions>(
name: K,
fn: NgGlobalPublishUtils[K],
): void {
publishUtil(name, fn);
}
function publishUtil(name: string, fn: Function) {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for AngularJS (via `goog.provide('ng....')`).
const w = global;
ngDevMode && assertDefined(fn, 'function not defined');
w[GLOBAL_PUBLISH_EXPANDO_KEY] ??= {} as any;
w[GLOBAL_PUBLISH_EXPANDO_KEY][name] = fn;
}
}
| {
"end_byte": 4884,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/global_utils.ts"
} |
angular/packages/core/src/render3/util/stringify_utils.ts_0_2474 | /**
* @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 {NG_COMP_DEF} from '../fields';
/**
* Used for stringify render output in Ivy.
* Important! This function is very performance-sensitive and we should
* be extra careful not to introduce megamorphic reads in it.
* Check `core/test/render3/perf/render_stringify` for benchmarks and alternate implementations.
*/
export function renderStringify(value: any): string {
if (typeof value === 'string') return value;
if (value == null) return '';
// Use `String` so that it invokes the `toString` method of the value. Note that this
// appears to be faster than calling `value.toString` (see `render_stringify` benchmark).
return String(value);
}
/**
* Used to stringify a value so that it can be displayed in an error message.
*
* Important! This function contains a megamorphic read and should only be
* used for error messages.
*/
export function stringifyForError(value: any): string {
if (typeof value === 'function') return value.name || value.toString();
if (typeof value === 'object' && value != null && typeof value.type === 'function') {
return value.type.name || value.type.toString();
}
return renderStringify(value);
}
/**
* Used to stringify a `Type` and including the file path and line number in which it is defined, if
* possible, for better debugging experience.
*
* Important! This function contains a megamorphic read and should only be used for error messages.
*/
export function debugStringifyTypeForError(type: Type<any>): string {
// TODO(pmvald): Do some refactoring so that we can use getComponentDef here without creating
// circular deps.
let componentDef = (type as any)[NG_COMP_DEF] || null;
if (componentDef !== null && componentDef.debugInfo) {
return stringifyTypeFromDebugInfo(componentDef.debugInfo);
}
return stringifyForError(type);
}
// TODO(pmvald): Do some refactoring so that we can use the type ClassDebugInfo for the param
// debugInfo here without creating circular deps.
function stringifyTypeFromDebugInfo(debugInfo: any): string {
if (!debugInfo.filePath || !debugInfo.lineNumber) {
return debugInfo.className;
} else {
return `${debugInfo.className} (at ${debugInfo.filePath}:${debugInfo.lineNumber})`;
}
}
| {
"end_byte": 2474,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/stringify_utils.ts"
} |
angular/packages/core/src/render3/util/injector_utils.ts_0_2951 | /**
* @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 Injector} from '../../di/injector';
import {assertGreaterThan, assertNotEqual, assertNumber} from '../../util/assert';
import {ChainedInjector} from '../chained_injector';
import {
NO_PARENT_INJECTOR,
RelativeInjectorLocation,
RelativeInjectorLocationFlags,
} from '../interfaces/injector';
import {DECLARATION_VIEW, HEADER_OFFSET, LView} from '../interfaces/view';
/// Parent Injector Utils ///////////////////////////////////////////////////////////////
export function hasParentInjector(parentLocation: RelativeInjectorLocation): boolean {
return parentLocation !== NO_PARENT_INJECTOR;
}
export function getParentInjectorIndex(parentLocation: RelativeInjectorLocation): number {
if (ngDevMode) {
assertNumber(parentLocation, 'Number expected');
assertNotEqual(parentLocation as any, -1, 'Not a valid state.');
const parentInjectorIndex = parentLocation & RelativeInjectorLocationFlags.InjectorIndexMask;
assertGreaterThan(
parentInjectorIndex,
HEADER_OFFSET,
'Parent injector must be pointing past HEADER_OFFSET.',
);
}
return parentLocation & RelativeInjectorLocationFlags.InjectorIndexMask;
}
export function getParentInjectorViewOffset(parentLocation: RelativeInjectorLocation): number {
return parentLocation >> RelativeInjectorLocationFlags.ViewOffsetShift;
}
/**
* Unwraps a parent injector location number to find the view offset from the current injector,
* then walks up the declaration view tree until the view is found that contains the parent
* injector.
*
* @param location The location of the parent injector, which contains the view offset
* @param startView The LView instance from which to start walking up the view tree
* @returns The LView instance that contains the parent injector
*/
export function getParentInjectorView(location: RelativeInjectorLocation, startView: LView): LView {
let viewOffset = getParentInjectorViewOffset(location);
let parentView = startView;
// For most cases, the parent injector can be found on the host node (e.g. for component
// or container), but we must keep the loop here to support the rarer case of deeply nested
// <ng-template> tags or inline views, where the parent injector might live many views
// above the child injector.
while (viewOffset > 0) {
parentView = parentView[DECLARATION_VIEW]!;
viewOffset--;
}
return parentView;
}
/**
* Detects whether an injector is an instance of a `ChainedInjector`,
* created based on the `OutletInjector`.
*/
export function isRouterOutletInjector(currentInjector: Injector): boolean {
return (
currentInjector instanceof ChainedInjector &&
typeof (currentInjector.injector as any).__ngOutletInjector === 'function'
);
}
| {
"end_byte": 2951,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/injector_utils.ts"
} |
angular/packages/core/src/render3/util/attrs_utils.ts_0_7877 | /**
* @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 {CharCode} from '../../util/char_code';
import {AttributeMarker} from '../interfaces/attribute_marker';
import {TAttributes} from '../interfaces/node';
import {CssSelector} from '../interfaces/projection';
import {Renderer} from '../interfaces/renderer';
import {RElement} from '../interfaces/renderer_dom';
/**
* Assigns all attribute values to the provided element via the inferred renderer.
*
* This function accepts two forms of attribute entries:
*
* default: (key, value):
* attrs = [key1, value1, key2, value2]
*
* namespaced: (NAMESPACE_MARKER, uri, name, value)
* attrs = [NAMESPACE_MARKER, uri, name, value, NAMESPACE_MARKER, uri, name, value]
*
* The `attrs` array can contain a mix of both the default and namespaced entries.
* The "default" values are set without a marker, but if the function comes across
* a marker value then it will attempt to set a namespaced value. If the marker is
* not of a namespaced value then the function will quit and return the index value
* where it stopped during the iteration of the attrs array.
*
* See [AttributeMarker] to understand what the namespace marker value is.
*
* Note that this instruction does not support assigning style and class values to
* an element. See `elementStart` and `elementHostAttrs` to learn how styling values
* are applied to an element.
* @param renderer The renderer to be used
* @param native The element that the attributes will be assigned to
* @param attrs The attribute array of values that will be assigned to the element
* @returns the index value that was last accessed in the attributes array
*/
export function setUpAttributes(renderer: Renderer, native: RElement, attrs: TAttributes): number {
let i = 0;
while (i < attrs.length) {
const value = attrs[i];
if (typeof value === 'number') {
// only namespaces are supported. Other value types (such as style/class
// entries) are not supported in this function.
if (value !== AttributeMarker.NamespaceURI) {
break;
}
// we just landed on the marker value ... therefore
// we should skip to the next entry
i++;
const namespaceURI = attrs[i++] as string;
const attrName = attrs[i++] as string;
const attrVal = attrs[i++] as string;
ngDevMode && ngDevMode.rendererSetAttribute++;
renderer.setAttribute(native, attrName, attrVal, namespaceURI);
} else {
// attrName is string;
const attrName = value as string;
const attrVal = attrs[++i];
// Standard attributes
ngDevMode && ngDevMode.rendererSetAttribute++;
if (isAnimationProp(attrName)) {
renderer.setProperty(native, attrName, attrVal);
} else {
renderer.setAttribute(native, attrName, attrVal as string);
}
i++;
}
}
// another piece of code may iterate over the same attributes array. Therefore
// it may be helpful to return the exact spot where the attributes array exited
// whether by running into an unsupported marker or if all the static values were
// iterated over.
return i;
}
/**
* Test whether the given value is a marker that indicates that the following
* attribute values in a `TAttributes` array are only the names of attributes,
* and not name-value pairs.
* @param marker The attribute marker to test.
* @returns true if the marker is a "name-only" marker (e.g. `Bindings`, `Template` or `I18n`).
*/
export function isNameOnlyAttributeMarker(marker: string | AttributeMarker | CssSelector) {
return (
marker === AttributeMarker.Bindings ||
marker === AttributeMarker.Template ||
marker === AttributeMarker.I18n
);
}
export function isAnimationProp(name: string): boolean {
// Perf note: accessing charCodeAt to check for the first character of a string is faster as
// compared to accessing a character at index 0 (ex. name[0]). The main reason for this is that
// charCodeAt doesn't allocate memory to return a substring.
return name.charCodeAt(0) === CharCode.AT_SIGN;
}
/**
* Merges `src` `TAttributes` into `dst` `TAttributes` removing any duplicates in the process.
*
* This merge function keeps the order of attrs same.
*
* @param dst Location of where the merged `TAttributes` should end up.
* @param src `TAttributes` which should be appended to `dst`
*/
export function mergeHostAttrs(
dst: TAttributes | null,
src: TAttributes | null,
): TAttributes | null {
if (src === null || src.length === 0) {
// do nothing
} else if (dst === null || dst.length === 0) {
// We have source, but dst is empty, just make a copy.
dst = src.slice();
} else {
let srcMarker: AttributeMarker = AttributeMarker.ImplicitAttributes;
for (let i = 0; i < src.length; i++) {
const item = src[i];
if (typeof item === 'number') {
srcMarker = item;
} else {
if (srcMarker === AttributeMarker.NamespaceURI) {
// Case where we need to consume `key1`, `key2`, `value` items.
} else if (
srcMarker === AttributeMarker.ImplicitAttributes ||
srcMarker === AttributeMarker.Styles
) {
// Case where we have to consume `key1` and `value` only.
mergeHostAttribute(dst, srcMarker, item as string, null, src[++i] as string);
} else {
// Case where we have to consume `key1` only.
mergeHostAttribute(dst, srcMarker, item as string, null, null);
}
}
}
}
return dst;
}
/**
* Append `key`/`value` to existing `TAttributes` taking region marker and duplicates into account.
*
* @param dst `TAttributes` to append to.
* @param marker Region where the `key`/`value` should be added.
* @param key1 Key to add to `TAttributes`
* @param key2 Key to add to `TAttributes` (in case of `AttributeMarker.NamespaceURI`)
* @param value Value to add or to overwrite to `TAttributes` Only used if `marker` is not Class.
*/
export function mergeHostAttribute(
dst: TAttributes,
marker: AttributeMarker,
key1: string,
key2: string | null,
value: string | null,
): void {
let i = 0;
// Assume that new markers will be inserted at the end.
let markerInsertPosition = dst.length;
// scan until correct type.
if (marker === AttributeMarker.ImplicitAttributes) {
markerInsertPosition = -1;
} else {
while (i < dst.length) {
const dstValue = dst[i++];
if (typeof dstValue === 'number') {
if (dstValue === marker) {
markerInsertPosition = -1;
break;
} else if (dstValue > marker) {
// We need to save this as we want the markers to be inserted in specific order.
markerInsertPosition = i - 1;
break;
}
}
}
}
// search until you find place of insertion
while (i < dst.length) {
const item = dst[i];
if (typeof item === 'number') {
// since `i` started as the index after the marker, we did not find it if we are at the next
// marker
break;
} else if (item === key1) {
// We already have same token
if (key2 === null) {
if (value !== null) {
dst[i + 1] = value;
}
return;
} else if (key2 === dst[i + 1]) {
dst[i + 2] = value!;
return;
}
}
// Increment counter.
i++;
if (key2 !== null) i++;
if (value !== null) i++;
}
// insert at location.
if (markerInsertPosition !== -1) {
dst.splice(markerInsertPosition, 0, marker);
i = markerInsertPosition + 1;
}
dst.splice(i++, 0, key1);
if (key2 !== null) {
dst.splice(i++, 0, key2);
}
if (value !== null) {
dst.splice(i++, 0, value);
}
}
| {
"end_byte": 7877,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/attrs_utils.ts"
} |
angular/packages/core/src/render3/util/misc_utils.ts_0_2155 | /**
* @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 {PLATFORM_ID} from '../../application/application_tokens';
import {Injector} from '../../di';
import {inject} from '../../di/injector_compatibility';
import {RElement} from '../interfaces/renderer_dom';
/**
*
* @codeGenApi
*/
export function ɵɵresolveWindow(element: RElement & {ownerDocument: Document}) {
return element.ownerDocument.defaultView;
}
/**
*
* @codeGenApi
*/
export function ɵɵresolveDocument(element: RElement & {ownerDocument: Document}) {
return element.ownerDocument;
}
/**
*
* @codeGenApi
*/
export function ɵɵresolveBody(element: RElement & {ownerDocument: Document}) {
return element.ownerDocument.body;
}
/**
* The special delimiter we use to separate property names, prefixes, and suffixes
* in property binding metadata. See storeBindingMetadata().
*
* We intentionally use the Unicode "REPLACEMENT CHARACTER" (U+FFFD) as a delimiter
* because it is a very uncommon character that is unlikely to be part of a user's
* property names or interpolation strings. If it is in fact used in a property
* binding, DebugElement.properties will not return the correct value for that
* binding. However, there should be no runtime effect for real applications.
*
* This character is typically rendered as a question mark inside of a diamond.
* See https://en.wikipedia.org/wiki/Specials_(Unicode_block)
*
*/
export const INTERPOLATION_DELIMITER = `�`;
/**
* Unwrap a value which might be behind a closure (for forward declaration reasons).
*/
export function maybeUnwrapFn<T>(value: T | (() => T)): T {
if (value instanceof Function) {
return value();
} else {
return value;
}
}
/**
* Detects whether the code is invoked in a browser.
* Later on, this check should be replaced with a tree-shakable
* flag (e.g. `!isServer`).
*/
export function isPlatformBrowser(injector?: Injector): boolean {
return (injector ?? inject(Injector)).get(PLATFORM_ID) === 'browser';
}
| {
"end_byte": 2155,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/misc_utils.ts"
} |
angular/packages/core/src/render3/util/view_traversal_utils.ts_0_2413 | /**
* @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 {assertLView} from '../assert';
import {readPatchedLView} from '../context_discovery';
import {LContainer} from '../interfaces/container';
import {isLContainer, isLView} from '../interfaces/type_checks';
import {CHILD_HEAD, CONTEXT, FLAGS, LView, LViewFlags, NEXT, PARENT} from '../interfaces/view';
import {getLViewParent} from './view_utils';
/**
* Retrieve the root view from any component or `LView` by walking the parent `LView` until
* reaching the root `LView`.
*
* @param componentOrLView any component or `LView`
*/
export function getRootView<T>(componentOrLView: LView | {}): LView<T> {
ngDevMode && assertDefined(componentOrLView, 'component');
let lView = isLView(componentOrLView) ? componentOrLView : readPatchedLView(componentOrLView)!;
while (lView && !(lView[FLAGS] & LViewFlags.IsRoot)) {
lView = getLViewParent(lView)!;
}
ngDevMode && assertLView(lView);
return lView as LView<T>;
}
/**
* Returns the context information associated with the application where the target is situated. It
* does this by walking the parent views until it gets to the root view, then getting the context
* off of that.
*
* @param viewOrComponent the `LView` or component to get the root context for.
*/
export function getRootContext<T>(viewOrComponent: LView<T> | {}): T {
const rootView = getRootView(viewOrComponent);
ngDevMode &&
assertDefined(rootView[CONTEXT], 'Root view has no context. Perhaps it is disconnected?');
return rootView[CONTEXT] as T;
}
/**
* Gets the first `LContainer` in the LView or `null` if none exists.
*/
export function getFirstLContainer(lView: LView): LContainer | null {
return getNearestLContainer(lView[CHILD_HEAD]);
}
/**
* Gets the next `LContainer` that is a sibling of the given container.
*/
export function getNextLContainer(container: LContainer): LContainer | null {
return getNearestLContainer(container[NEXT]);
}
function getNearestLContainer(viewOrContainer: LContainer | LView | null) {
while (viewOrContainer !== null && !isLContainer(viewOrContainer)) {
viewOrContainer = viewOrContainer[NEXT];
}
return viewOrContainer as LContainer | null;
}
| {
"end_byte": 2413,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/view_traversal_utils.ts"
} |
angular/packages/core/src/render3/util/discovery_utils.ts_0_8219 | /**
* @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 {Injector} from '../../di/injector';
import {ViewEncapsulation} from '../../metadata/view';
import {assertLView} from '../assert';
import {
discoverLocalRefs,
getComponentAtNodeIndex,
getDirectivesAtNodeIndex,
getLContext,
readPatchedLView,
} from '../context_discovery';
import {getComponentDef, getDirectiveDef} from '../def_getters';
import {NodeInjector} from '../di';
import {DirectiveDef} from '../interfaces/definition';
import {TElementNode, TNode, TNodeProviderIndexes} from '../interfaces/node';
import {CLEANUP, CONTEXT, FLAGS, LView, LViewFlags, TVIEW, TViewType} from '../interfaces/view';
import {getRootContext} from './view_traversal_utils';
import {getLViewParent, unwrapRNode} from './view_utils';
/**
* Retrieves the component instance associated with a given DOM element.
*
* @usageNotes
* Given the following DOM structure:
*
* ```html
* <app-root>
* <div>
* <child-comp></child-comp>
* </div>
* </app-root>
* ```
*
* Calling `getComponent` on `<child-comp>` will return the instance of `ChildComponent`
* associated with this DOM element.
*
* Calling the function on `<app-root>` will return the `MyApp` instance.
*
*
* @param element DOM element from which the component should be retrieved.
* @returns Component instance associated with the element or `null` if there
* is no component associated with it.
*
* @publicApi
*/
export function getComponent<T>(element: Element): T | null {
ngDevMode && assertDomElement(element);
const context = getLContext(element);
if (context === null) return null;
if (context.component === undefined) {
const lView = context.lView;
if (lView === null) {
return null;
}
context.component = getComponentAtNodeIndex(context.nodeIndex, lView);
}
return context.component as unknown as T;
}
/**
* If inside an embedded view (e.g. `*ngIf` or `*ngFor`), retrieves the context of the embedded
* view that the element is part of. Otherwise retrieves the instance of the component whose view
* owns the element (in this case, the result is the same as calling `getOwningComponent`).
*
* @param element Element for which to get the surrounding component instance.
* @returns Instance of the component that is around the element or null if the element isn't
* inside any component.
*
* @publicApi
*/
export function getContext<T extends {}>(element: Element): T | null {
assertDomElement(element);
const context = getLContext(element)!;
const lView = context ? context.lView : null;
return lView === null ? null : (lView[CONTEXT] as T);
}
/**
* Retrieves the component instance whose view contains the DOM element.
*
* For example, if `<child-comp>` is used in the template of `<app-comp>`
* (i.e. a `ViewChild` of `<app-comp>`), calling `getOwningComponent` on `<child-comp>`
* would return `<app-comp>`.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Component instance whose view owns the DOM element or null if the element is not
* part of a component view.
*
* @publicApi
*/
export function getOwningComponent<T>(elementOrDir: Element | {}): T | null {
const context = getLContext(elementOrDir)!;
let lView = context ? context.lView : null;
if (lView === null) return null;
let parent: LView | null;
while (lView[TVIEW].type === TViewType.Embedded && (parent = getLViewParent(lView)!)) {
lView = parent;
}
return lView[FLAGS] & LViewFlags.IsRoot ? null : (lView[CONTEXT] as unknown as T);
}
/**
* Retrieves all root components associated with a DOM element, directive or component instance.
* Root components are those which have been bootstrapped by Angular.
*
* @param elementOrDir DOM element, component or directive instance
* for which to retrieve the root components.
* @returns Root components associated with the target object.
*
* @publicApi
*/
export function getRootComponents(elementOrDir: Element | {}): {}[] {
const lView = readPatchedLView<{}>(elementOrDir);
return lView !== null ? [getRootContext(lView)] : [];
}
/**
* Retrieves an `Injector` associated with an element, component or directive instance.
*
* @param elementOrDir DOM element, component or directive instance for which to
* retrieve the injector.
* @returns Injector associated with the element, component or directive instance.
*
* @publicApi
*/
export function getInjector(elementOrDir: Element | {}): Injector {
const context = getLContext(elementOrDir)!;
const lView = context ? context.lView : null;
if (lView === null) return Injector.NULL;
const tNode = lView[TVIEW].data[context.nodeIndex] as TElementNode;
return new NodeInjector(tNode, lView);
}
/**
* Retrieve a set of injection tokens at a given DOM node.
*
* @param element Element for which the injection tokens should be retrieved.
*/
export function getInjectionTokens(element: Element): any[] {
const context = getLContext(element)!;
const lView = context ? context.lView : null;
if (lView === null) return [];
const tView = lView[TVIEW];
const tNode = tView.data[context.nodeIndex] as TNode;
const providerTokens: any[] = [];
const startIndex = tNode.providerIndexes & TNodeProviderIndexes.ProvidersStartIndexMask;
const endIndex = tNode.directiveEnd;
for (let i = startIndex; i < endIndex; i++) {
let value = tView.data[i];
if (isDirectiveDefHack(value)) {
// The fact that we sometimes store Type and sometimes DirectiveDef in this location is a
// design flaw. We should always store same type so that we can be monomorphic. The issue
// is that for Components/Directives we store the def instead the type. The correct behavior
// is that we should always be storing injectable type in this location.
value = value.type;
}
providerTokens.push(value);
}
return providerTokens;
}
/**
* Retrieves directive instances associated with a given DOM node. Does not include
* component instances.
*
* @usageNotes
* Given the following DOM structure:
*
* ```html
* <app-root>
* <button my-button></button>
* <my-comp></my-comp>
* </app-root>
* ```
*
* Calling `getDirectives` on `<button>` will return an array with an instance of the `MyButton`
* directive that is associated with the DOM node.
*
* Calling `getDirectives` on `<my-comp>` will return an empty array.
*
* @param node DOM node for which to get the directives.
* @returns Array of directives associated with the node.
*
* @publicApi
*/
export function getDirectives(node: Node): {}[] {
// Skip text nodes because we can't have directives associated with them.
if (node instanceof Text) {
return [];
}
const context = getLContext(node)!;
const lView = context ? context.lView : null;
if (lView === null) {
return [];
}
const tView = lView[TVIEW];
const nodeIndex = context.nodeIndex;
if (!tView?.data[nodeIndex]) {
return [];
}
if (context.directives === undefined) {
context.directives = getDirectivesAtNodeIndex(nodeIndex, lView);
}
// The `directives` in this case are a named array called `LComponentView`. Clone the
// result so we don't expose an internal data structure in the user's console.
return context.directives === null ? [] : [...context.directives];
}
/**
* Partial metadata for a given directive instance.
* This information might be useful for debugging purposes or tooling.
* Currently only `inputs` and `outputs` metadata is available.
*
* @publicApi
*/
export interface DirectiveDebugMetadata {
inputs: Record<string, string>;
outputs: Record<string, string>;
}
/**
* Partial metadata for a given component instance.
* This information might be useful for debugging purposes or tooling.
* Currently the following fields are available:
* - inputs
* - outputs
* - encapsulation
* - changeDetection
*
* @publicApi
*/ | {
"end_byte": 8219,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/discovery_utils.ts"
} |
angular/packages/core/src/render3/util/discovery_utils.ts_8220_16273 | export interface ComponentDebugMetadata extends DirectiveDebugMetadata {
encapsulation: ViewEncapsulation;
changeDetection: ChangeDetectionStrategy;
}
/**
* Returns the debug (partial) metadata for a particular directive or component instance.
* The function accepts an instance of a directive or component and returns the corresponding
* metadata.
*
* @param directiveOrComponentInstance Instance of a directive or component
* @returns metadata of the passed directive or component
*
* @publicApi
*/
export function getDirectiveMetadata(
directiveOrComponentInstance: any,
): ComponentDebugMetadata | DirectiveDebugMetadata | null {
const {constructor} = directiveOrComponentInstance;
if (!constructor) {
throw new Error('Unable to find the instance constructor');
}
// In case a component inherits from a directive, we may have component and directive metadata
// To ensure we don't get the metadata of the directive, we want to call `getComponentDef` first.
const componentDef = getComponentDef(constructor);
if (componentDef) {
const inputs = extractInputDebugMetadata(componentDef.inputs);
return {
inputs,
outputs: componentDef.outputs,
encapsulation: componentDef.encapsulation,
changeDetection: componentDef.onPush
? ChangeDetectionStrategy.OnPush
: ChangeDetectionStrategy.Default,
};
}
const directiveDef = getDirectiveDef(constructor);
if (directiveDef) {
const inputs = extractInputDebugMetadata(directiveDef.inputs);
return {inputs, outputs: directiveDef.outputs};
}
return null;
}
/**
* Retrieve map of local references.
*
* The references are retrieved as a map of local reference name to element or directive instance.
*
* @param target DOM element, component or directive instance for which to retrieve
* the local references.
*/
export function getLocalRefs(target: {}): {[key: string]: any} {
const context = getLContext(target);
if (context === null) return {};
if (context.localRefs === undefined) {
const lView = context.lView;
if (lView === null) {
return {};
}
context.localRefs = discoverLocalRefs(lView, context.nodeIndex);
}
return context.localRefs || {};
}
/**
* Retrieves the host element of a component or directive instance.
* The host element is the DOM element that matched the selector of the directive.
*
* @param componentOrDirective Component or directive instance for which the host
* element should be retrieved.
* @returns Host element of the target.
*
* @publicApi
*/
export function getHostElement(componentOrDirective: {}): Element {
return getLContext(componentOrDirective)!.native as unknown as Element;
}
/**
* Retrieves the rendered text for a given component.
*
* This function retrieves the host element of a component and
* and then returns the `textContent` for that element. This implies
* that the text returned will include re-projected content of
* the component as well.
*
* @param component The component to return the content text for.
*/
export function getRenderedText(component: any): string {
const hostElement = getHostElement(component);
return hostElement.textContent || '';
}
/**
* Event listener configuration returned from `getListeners`.
* @publicApi
*/
export interface Listener {
/** Name of the event listener. */
name: string;
/** Element that the listener is bound to. */
element: Element;
/** Callback that is invoked when the event is triggered. */
callback: (value: any) => any;
/** Whether the listener is using event capturing. */
useCapture: boolean;
/**
* Type of the listener (e.g. a native DOM event or a custom @Output).
*/
type: 'dom' | 'output';
}
/**
* Retrieves a list of event listeners associated with a DOM element. The list does include host
* listeners, but it does not include event listeners defined outside of the Angular context
* (e.g. through `addEventListener`).
*
* @usageNotes
* Given the following DOM structure:
*
* ```html
* <app-root>
* <div (click)="doSomething()"></div>
* </app-root>
* ```
*
* Calling `getListeners` on `<div>` will return an object that looks as follows:
*
* ```ts
* {
* name: 'click',
* element: <div>,
* callback: () => doSomething(),
* useCapture: false
* }
* ```
*
* @param element Element for which the DOM listeners should be retrieved.
* @returns Array of event listeners on the DOM element.
*
* @publicApi
*/
export function getListeners(element: Element): Listener[] {
ngDevMode && assertDomElement(element);
const lContext = getLContext(element);
const lView = lContext === null ? null : lContext.lView;
if (lView === null) return [];
const tView = lView[TVIEW];
const lCleanup = lView[CLEANUP];
const tCleanup = tView.cleanup;
const listeners: Listener[] = [];
if (tCleanup && lCleanup) {
for (let i = 0; i < tCleanup.length; ) {
const firstParam = tCleanup[i++];
const secondParam = tCleanup[i++];
if (typeof firstParam === 'string') {
const name: string = firstParam;
const listenerElement = unwrapRNode(lView[secondParam]) as any as Element;
const callback: (value: any) => any = lCleanup[tCleanup[i++]];
const useCaptureOrIndx = tCleanup[i++];
// if useCaptureOrIndx is boolean then report it as is.
// if useCaptureOrIndx is positive number then it in unsubscribe method
// if useCaptureOrIndx is negative number then it is a Subscription
const type =
typeof useCaptureOrIndx === 'boolean' || useCaptureOrIndx >= 0 ? 'dom' : 'output';
const useCapture = typeof useCaptureOrIndx === 'boolean' ? useCaptureOrIndx : false;
if (element == listenerElement) {
listeners.push({element, name, callback, useCapture, type});
}
}
}
}
listeners.sort(sortListeners);
return listeners;
}
function sortListeners(a: Listener, b: Listener) {
if (a.name == b.name) return 0;
return a.name < b.name ? -1 : 1;
}
/**
* This function should not exist because it is megamorphic and only mostly correct.
*
* See call site for more info.
*/
function isDirectiveDefHack(obj: any): obj is DirectiveDef<any> {
return (
obj.type !== undefined &&
obj.declaredInputs !== undefined &&
obj.findHostDirectiveDefs !== undefined
);
}
/**
* Retrieve the component `LView` from component/element.
*
* NOTE: `LView` is a private and should not be leaked outside.
* Don't export this method to `ng.*` on window.
*
* @param target DOM element or component instance for which to retrieve the LView.
*/
export function getComponentLView(target: any): LView {
const lContext = getLContext(target)!;
const nodeIndx = lContext.nodeIndex;
const lView = lContext.lView!;
ngDevMode && assertLView(lView);
const componentLView = lView[nodeIndx];
ngDevMode && assertLView(componentLView);
return componentLView;
}
/** Asserts that a value is a DOM Element. */
function assertDomElement(value: any) {
if (typeof Element !== 'undefined' && !(value instanceof Element)) {
throw new Error('Expecting instance of DOM Element');
}
}
/**
* A directive definition holds additional metadata using bitwise flags to indicate
* for example whether it is signal based.
*
* This information needs to be separate from the `publicName -> minifiedName`
* mappings for backwards compatibility.
*/
function extractInputDebugMetadata<T>(inputs: DirectiveDef<T>['inputs']) {
const res: DirectiveDebugMetadata['inputs'] = {};
for (const key in inputs) {
if (!inputs.hasOwnProperty(key)) {
continue;
}
const value = inputs[key];
if (value === undefined) {
continue;
}
let minifiedName: string;
if (Array.isArray(value)) {
minifiedName = value[0];
// flags are not used for now.
// TODO: Consider exposing flag information in discovery.
} else {
minifiedName = value;
}
res[key] = minifiedName;
}
return res;
} | {
"end_byte": 16273,
"start_byte": 8220,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/discovery_utils.ts"
} |
angular/packages/core/src/render3/util/injector_discovery_utils.ts_0_8768 | /**
* @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 {ENVIRONMENT_INITIALIZER} from '../../di/initializer_token';
import {InjectionToken} from '../../di/injection_token';
import {Injector} from '../../di/injector';
import {getInjectorDef, InjectorType} from '../../di/interface/defs';
import {InternalInjectFlags} from '../../di/interface/injector';
import {ValueProvider} from '../../di/interface/provider';
import {INJECTOR_DEF_TYPES} from '../../di/internal_tokens';
import {NullInjector} from '../../di/null_injector';
import {SingleProvider, walkProviderTree} from '../../di/provider_collection';
import {EnvironmentInjector, R3Injector} from '../../di/r3_injector';
import {Type} from '../../interface/type';
import {NgModuleRef as viewEngine_NgModuleRef} from '../../linker/ng_module_factory';
import {deepForEach} from '../../util/array_utils';
import {throwError} from '../../util/assert';
import {assertTNode, assertTNodeForLView} from '../assert';
import {ChainedInjector} from '../chained_injector';
import {getFrameworkDIDebugData} from '../debug/framework_injector_profiler';
import {InjectedService, ProviderRecord} from '../debug/injector_profiler';
import {getComponentDef} from '../def_getters';
import {
getNodeInjectorLView,
getNodeInjectorTNode,
getParentInjectorLocation,
NodeInjector,
} from '../di';
import {NodeInjectorOffset} from '../interfaces/injector';
import {TContainerNode, TElementContainerNode, TElementNode, TNode} from '../interfaces/node';
import {RElement} from '../interfaces/renderer_dom';
import {INJECTOR, LView, TVIEW} from '../interfaces/view';
import {
getParentInjectorIndex,
getParentInjectorView,
hasParentInjector,
isRouterOutletInjector,
} from './injector_utils';
import {getNativeByTNode} from './view_utils';
/**
* Discovers the dependencies of an injectable instance. Provides DI information about each
* dependency that the injectable was instantiated with, including where they were provided from.
*
* @param injector An injector instance
* @param token a DI token that was constructed by the given injector instance
* @returns an object that contains the created instance of token as well as all of the dependencies
* that it was instantiated with OR undefined if the token was not created within the given
* injector.
*/
export function getDependenciesFromInjectable<T>(
injector: Injector,
token: Type<T> | InjectionToken<T>,
): {instance: T; dependencies: Omit<InjectedService, 'injectedIn'>[]} | undefined {
// First we check to see if the token given maps to an actual instance in the injector given.
// We use `self: true` because we only want to look at the injector we were given.
// We use `optional: true` because it's possible that the token we were given was never
// constructed by the injector we were given.
const instance = injector.get(token, null, {self: true, optional: true});
if (instance === null) {
throw new Error(`Unable to determine instance of ${token} in given injector`);
}
const unformattedDependencies = getDependenciesForTokenInInjector(token, injector);
const resolutionPath = getInjectorResolutionPath(injector);
const dependencies = unformattedDependencies.map((dep) => {
// injectedIn contains private fields, so we omit it from the response
const formattedDependency: Omit<InjectedService, 'injectedIn'> = {
value: dep.value,
};
// convert injection flags to booleans
const flags = dep.flags as InternalInjectFlags;
formattedDependency.flags = {
optional: (InternalInjectFlags.Optional & flags) === InternalInjectFlags.Optional,
host: (InternalInjectFlags.Host & flags) === InternalInjectFlags.Host,
self: (InternalInjectFlags.Self & flags) === InternalInjectFlags.Self,
skipSelf: (InternalInjectFlags.SkipSelf & flags) === InternalInjectFlags.SkipSelf,
};
// find the injector that provided the dependency
for (let i = 0; i < resolutionPath.length; i++) {
const injectorToCheck = resolutionPath[i];
// if skipSelf is true we skip the first injector
if (i === 0 && formattedDependency.flags.skipSelf) {
continue;
}
// host only applies to NodeInjectors
if (formattedDependency.flags.host && injectorToCheck instanceof EnvironmentInjector) {
break;
}
const instance = injectorToCheck.get(dep.token as Type<unknown>, null, {
self: true,
optional: true,
});
if (instance !== null) {
// if host flag is true we double check that we can get the service from the first element
// in the resolution path by using the host flag. This is done to make sure that we've found
// the correct providing injector, and not a node injector that is connected to our path via
// a router outlet.
if (formattedDependency.flags.host) {
const firstInjector = resolutionPath[0];
const lookupFromFirstInjector = firstInjector.get(dep.token as Type<unknown>, null, {
...formattedDependency.flags,
optional: true,
});
if (lookupFromFirstInjector !== null) {
formattedDependency.providedIn = injectorToCheck;
}
break;
}
formattedDependency.providedIn = injectorToCheck;
break;
}
// if self is true we stop after the first injector
if (i === 0 && formattedDependency.flags.self) {
break;
}
}
if (dep.token) formattedDependency.token = dep.token;
return formattedDependency;
});
return {instance, dependencies};
}
function getDependenciesForTokenInInjector<T>(
token: Type<T> | InjectionToken<T>,
injector: Injector,
): InjectedService[] {
const {resolverToTokenToDependencies} = getFrameworkDIDebugData();
if (!(injector instanceof NodeInjector)) {
return resolverToTokenToDependencies.get(injector)?.get?.(token as Type<T>) ?? [];
}
const lView = getNodeInjectorLView(injector);
const tokenDependencyMap = resolverToTokenToDependencies.get(lView);
const dependencies = tokenDependencyMap?.get(token as Type<T>) ?? [];
// In the NodeInjector case, all injections for every node are stored in the same lView.
// We use the injectedIn field of the dependency to filter out the dependencies that
// do not come from the same node as the instance we're looking at.
return dependencies.filter((dependency) => {
const dependencyNode = dependency.injectedIn?.tNode;
if (dependencyNode === undefined) {
return false;
}
const instanceNode = getNodeInjectorTNode(injector);
assertTNode(dependencyNode);
assertTNode(instanceNode!);
return dependencyNode === instanceNode;
});
}
/**
* Gets the class associated with an injector that contains a provider `imports` array in it's
* definition
*
* For Module Injectors this returns the NgModule constructor.
*
* For Standalone injectors this returns the standalone component constructor.
*
* @param injector Injector an injector instance
* @returns the constructor where the `imports` array that configures this injector is located
*/
function getProviderImportsContainer(injector: Injector): Type<unknown> | null {
const {standaloneInjectorToComponent} = getFrameworkDIDebugData();
// standalone components configure providers through a component def, so we have to
// use the standalone component associated with this injector if Injector represents
// a standalone components EnvironmentInjector
if (standaloneInjectorToComponent.has(injector)) {
return standaloneInjectorToComponent.get(injector)!;
}
// Module injectors configure providers through their NgModule def, so we use the
// injector to lookup its NgModuleRef and through that grab its instance
const defTypeRef = injector.get(viewEngine_NgModuleRef, null, {self: true, optional: true})!;
// If we can't find an associated imports container, return null.
// This could be the case if this function is called with an R3Injector that does not represent
// a standalone component or NgModule.
if (defTypeRef === null) {
return null;
}
// In standalone applications, the root environment injector created by bootstrapApplication
// may have no associated "instance".
if (defTypeRef.instance === null) {
return null;
}
return defTypeRef.instance.constructor;
}
/**
* Gets the providers configured on a NodeInjector
*
* @param injector A NodeInjector instance
* @returns ProviderRecord[] an array of objects representing the providers configured on this
* injector
*/ | {
"end_byte": 8768,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/injector_discovery_utils.ts"
} |
angular/packages/core/src/render3/util/injector_discovery_utils.ts_8769_16014 | function getNodeInjectorProviders(injector: NodeInjector): ProviderRecord[] {
const diResolver = getNodeInjectorTNode(injector);
const {resolverToProviders} = getFrameworkDIDebugData();
return resolverToProviders.get(diResolver as TNode) ?? [];
}
/**
* Gets a mapping of providers configured on an injector to their import paths
*
* ModuleA -> imports ModuleB
* ModuleB -> imports ModuleC
* ModuleB -> provides MyServiceA
* ModuleC -> provides MyServiceB
*
* getProviderImportPaths(ModuleA)
* > Map(2) {
* MyServiceA => [ModuleA, ModuleB]
* MyServiceB => [ModuleA, ModuleB, ModuleC]
* }
*
* @param providerImportsContainer constructor of class that contains an `imports` array in it's
* definition
* @returns A Map object that maps providers to an array of constructors representing it's import
* path
*
*/
function getProviderImportPaths(
providerImportsContainer: Type<unknown>,
): Map<SingleProvider, (Type<unknown> | InjectorType<unknown>)[]> {
const providerToPath = new Map<SingleProvider, (Type<unknown> | InjectorType<unknown>)[]>();
const visitedContainers = new Set<Type<unknown>>();
const visitor = walkProviderTreeToDiscoverImportPaths(providerToPath, visitedContainers);
walkProviderTree(providerImportsContainer, visitor, [], new Set());
return providerToPath;
}
/**
*
* Higher order function that returns a visitor for WalkProviderTree
*
* Takes in a Map and Set to keep track of the providers and containers
* visited, so that we can discover the import paths of these providers
* during the traversal.
*
* This visitor takes advantage of the fact that walkProviderTree performs a
* postorder traversal of the provider tree for the passed in container. Because postorder
* traversal recursively processes subtrees from leaf nodes until the traversal reaches the root,
* we write a visitor that constructs provider import paths in reverse.
*
*
* We use the visitedContainers set defined outside this visitor
* because we want to run some logic only once for
* each container in the tree. That logic can be described as:
*
*
* 1. for each discovered_provider and discovered_path in the incomplete provider paths we've
* already discovered
* 2. get the first container in discovered_path
* 3. if that first container is in the imports array of the container we're visiting
* Then the container we're visiting is also in the import path of discovered_provider, so we
* unshift discovered_path with the container we're currently visiting
*
*
* Example Run:
* ```
* ┌──────────┐
* │containerA│
* ┌─imports-─┤ ├──imports─┐
* │ │ provA │ │
* │ │ provB │ │
* │ └──────────┘ │
* │ │
* ┌▼─────────┐ ┌────────▼─┐
* │containerB│ │containerC│
* │ │ │ │
* │ provD │ │ provF │
* │ provE │ │ provG │
* └──────────┘ └──────────┘
* ```
*
* Each step of the traversal,
*
* ```
* visitor(provD, containerB)
* providerToPath === Map { provD => [containerB] }
* visitedContainers === Set { containerB }
*
* visitor(provE, containerB)
* providerToPath === Map { provD => [containerB], provE => [containerB] }
* visitedContainers === Set { containerB }
*
* visitor(provF, containerC)
* providerToPath === Map { provD => [containerB], provE => [containerB], provF => [containerC] }
* visitedContainers === Set { containerB, containerC }
*
* visitor(provG, containerC)
* providerToPath === Map {
* provD => [containerB], provE => [containerB], provF => [containerC], provG => [containerC]
* }
* visitedContainers === Set { containerB, containerC }
*
* visitor(provA, containerA)
* providerToPath === Map {
* provD => [containerA, containerB],
* provE => [containerA, containerB],
* provF => [containerA, containerC],
* provG => [containerA, containerC],
* provA => [containerA]
* }
* visitedContainers === Set { containerB, containerC, containerA }
*
* visitor(provB, containerA)
* providerToPath === Map {
* provD => [containerA, containerB],
* provE => [containerA, containerB],
* provF => [containerA, containerC],
* provG => [containerA, containerC],
* provA => [containerA]
* provB => [containerA]
* }
* visitedContainers === Set { containerB, containerC, containerA }
* ```
*
* @param providerToPath Map map of providers to paths that this function fills
* @param visitedContainers Set a set to keep track of the containers we've already visited
* @return function(provider SingleProvider, container: Type<unknown> | InjectorType<unknown>) =>
* void
*/
function walkProviderTreeToDiscoverImportPaths(
providerToPath: Map<SingleProvider, (Type<unknown> | InjectorType<unknown>)[]>,
visitedContainers: Set<Type<unknown>>,
): (provider: SingleProvider, container: Type<unknown> | InjectorType<unknown>) => void {
return (provider: SingleProvider, container: Type<unknown> | InjectorType<unknown>) => {
// If the provider is not already in the providerToPath map,
// add an entry with the provider as the key and an array containing the current container as
// the value
if (!providerToPath.has(provider)) {
providerToPath.set(provider, [container]);
}
// This block will run exactly once for each container in the import tree.
// This is where we run the logic to check the imports array of the current
// container to see if it's the next container in the path for our currently
// discovered providers.
if (!visitedContainers.has(container)) {
// Iterate through the providers we've already seen
for (const prov of providerToPath.keys()) {
const existingImportPath = providerToPath.get(prov)!;
let containerDef = getInjectorDef(container);
if (!containerDef) {
const ngModule: Type<unknown> | undefined = (container as any).ngModule as
| Type<unknown>
| undefined;
containerDef = getInjectorDef(ngModule);
}
if (!containerDef) {
return;
}
const lastContainerAddedToPath = existingImportPath[0];
let isNextStepInPath = false;
deepForEach(containerDef.imports, (moduleImport) => {
if (isNextStepInPath) {
return;
}
isNextStepInPath =
(moduleImport as any).ngModule === lastContainerAddedToPath ||
moduleImport === lastContainerAddedToPath;
if (isNextStepInPath) {
providerToPath.get(prov)?.unshift(container);
}
});
}
}
visitedContainers.add(container);
};
}
/**
* Gets the providers configured on an EnvironmentInjector
*
* @param injector EnvironmentInjector
* @returns an array of objects representing the providers of the given injector
*/
function getEnvironmentInjectorProviders(injector: EnvironmentInjector): ProviderRecord[] {
const providerRecordsWithoutImportPaths =
getFrameworkDIDebugData().resolverToProviders.get(injector) ?? [];
// platform | {
"end_byte": 16014,
"start_byte": 8769,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/injector_discovery_utils.ts"
} |
angular/packages/core/src/render3/util/injector_discovery_utils.ts_16015_23824 | injector has no provider imports container so can we skip trying to
// find import paths
if (isPlatformInjector(injector)) {
return providerRecordsWithoutImportPaths;
}
const providerImportsContainer = getProviderImportsContainer(injector);
if (providerImportsContainer === null) {
// We assume that if an environment injector exists without an associated provider imports
// container, it was created without such a container. Some examples cases where this could
// happen:
// - The root injector of a standalone application
// - A router injector created by using the providers array in a lazy loaded route
// - A manually created injector that is attached to the injector tree
// Since each of these cases has no provider container, there is no concept of import paths,
// so we can simply return the provider records.
return providerRecordsWithoutImportPaths;
}
const providerToPath = getProviderImportPaths(providerImportsContainer);
const providerRecords = [];
for (const providerRecord of providerRecordsWithoutImportPaths) {
const provider = providerRecord.provider;
// Ignore these special providers for now until we have a cleaner way of
// determing when they are provided by the framework vs provided by the user.
const token = (provider as ValueProvider).provide;
if (token === ENVIRONMENT_INITIALIZER || token === INJECTOR_DEF_TYPES) {
continue;
}
let importPath = providerToPath.get(provider) ?? [];
const def = getComponentDef(providerImportsContainer);
const isStandaloneComponent = !!def?.standalone;
// We prepend the component constructor in the standalone case
// because walkProviderTree does not visit this constructor during it's traversal
if (isStandaloneComponent) {
importPath = [providerImportsContainer, ...importPath];
}
providerRecords.push({...providerRecord, importPath});
}
return providerRecords;
}
function isPlatformInjector(injector: Injector) {
return injector instanceof R3Injector && injector.scopes.has('platform');
}
/**
* Gets the providers configured on an injector.
*
* @param injector the injector to lookup the providers of
* @returns ProviderRecord[] an array of objects representing the providers of the given injector
*/
export function getInjectorProviders(injector: Injector): ProviderRecord[] {
if (injector instanceof NodeInjector) {
return getNodeInjectorProviders(injector);
} else if (injector instanceof EnvironmentInjector) {
return getEnvironmentInjectorProviders(injector as EnvironmentInjector);
}
throwError('getInjectorProviders only supports NodeInjector and EnvironmentInjector');
}
/**
*
* Given an injector, this function will return
* an object containing the type and source of the injector.
*
* | | type | source |
* |--------------|-------------|-------------------------------------------------------------|
* | NodeInjector | element | DOM element that created this injector |
* | R3Injector | environment | `injector.source` |
* | NullInjector | null | null |
*
* @param injector the Injector to get metadata for
* @returns an object containing the type and source of the given injector. If the injector metadata
* cannot be determined, returns null.
*/
export function getInjectorMetadata(
injector: Injector,
):
| {type: 'element'; source: RElement}
| {type: 'environment'; source: string | null}
| {type: 'null'; source: null}
| null {
if (injector instanceof NodeInjector) {
const lView = getNodeInjectorLView(injector);
const tNode = getNodeInjectorTNode(injector)!;
assertTNodeForLView(tNode, lView);
return {type: 'element', source: getNativeByTNode(tNode, lView) as RElement};
}
if (injector instanceof R3Injector) {
return {type: 'environment', source: injector.source ?? null};
}
if (injector instanceof NullInjector) {
return {type: 'null', source: null};
}
return null;
}
export function getInjectorResolutionPath(injector: Injector): Injector[] {
const resolutionPath: Injector[] = [injector];
getInjectorResolutionPathHelper(injector, resolutionPath);
return resolutionPath;
}
function getInjectorResolutionPathHelper(
injector: Injector,
resolutionPath: Injector[],
): Injector[] {
const parent = getInjectorParent(injector);
// if getInjectorParent can't find a parent, then we've either reached the end
// of the path, or we need to move from the Element Injector tree to the
// module injector tree using the first injector in our path as the connection point.
if (parent === null) {
if (injector instanceof NodeInjector) {
const firstInjector = resolutionPath[0];
if (firstInjector instanceof NodeInjector) {
const moduleInjector = getModuleInjectorOfNodeInjector(firstInjector);
if (moduleInjector === null) {
throwError('NodeInjector must have some connection to the module injector tree');
}
resolutionPath.push(moduleInjector);
getInjectorResolutionPathHelper(moduleInjector, resolutionPath);
}
return resolutionPath;
}
} else {
resolutionPath.push(parent);
getInjectorResolutionPathHelper(parent, resolutionPath);
}
return resolutionPath;
}
/**
* Gets the parent of an injector.
*
* This function is not able to make the jump from the Element Injector Tree to the Module
* injector tree. This is because the "parent" (the next step in the reoslution path)
* of a root NodeInjector is dependent on which NodeInjector ancestor initiated
* the DI lookup. See getInjectorResolutionPath for a function that can make this jump.
*
* In the below diagram:
* ```ts
* getInjectorParent(NodeInjectorB)
* > NodeInjectorA
* getInjectorParent(NodeInjectorA) // or getInjectorParent(getInjectorParent(NodeInjectorB))
* > null // cannot jump to ModuleInjector tree
* ```
*
* ```
* ┌───────┐ ┌───────────────────┐
* ┌───────────┤ModuleA├───Injector────►│EnvironmentInjector│
* │ └───┬───┘ └───────────────────┘
* │ │
* │ bootstraps
* │ │
* │ │
* │ ┌────▼─────┐ ┌─────────────┐
* declares │ComponentA├────Injector────►│NodeInjectorA│
* │ └────┬─────┘ └─────▲───────┘
* │ │ │
* │ renders parent
* │ │ │
* │ ┌────▼─────┐ ┌─────┴───────┐
* └─────────►│ComponentB├────Injector────►│NodeInjectorB│
* └──────────┘ └─────────────┘
*```
*
* @param injector an Injector to get the parent of
* @returns Injector the parent of the given injector
*/
function getInjectorParent(injector: Injector): Injector | null {
if (injector instanceof R3Injector) {
const parent = injector.parent;
if (isRouterOutletInjector(parent)) {
// This is a special case for a `ChainedInjector` instance, which represents
// a combination of a Router's `OutletInjector` and an EnvironmentInjector,
// which represents a `@defer` block. Since the `OutletInjector` doesn't store
// any tokens itself, we point to the parent injector instead. See the
// `OutletInjector.__ngOutletInjector` field for additional information.
return (parent as ChainedInjector).parentInjector;
}
return parent;
}
let tNode: TElementNode | TContainer | {
"end_byte": 23824,
"start_byte": 16015,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/injector_discovery_utils.ts"
} |
angular/packages/core/src/render3/util/injector_discovery_utils.ts_23825_27088 | ode | TElementContainerNode | null;
let lView: LView<unknown>;
if (injector instanceof NodeInjector) {
tNode = getNodeInjectorTNode(injector);
lView = getNodeInjectorLView(injector);
} else if (injector instanceof NullInjector) {
return null;
} else if (injector instanceof ChainedInjector) {
return injector.parentInjector;
} else {
throwError(
'getInjectorParent only support injectors of type R3Injector, NodeInjector, NullInjector',
);
}
const parentLocation = getParentInjectorLocation(
tNode as TElementNode | TContainerNode | TElementContainerNode,
lView,
);
if (hasParentInjector(parentLocation)) {
const parentInjectorIndex = getParentInjectorIndex(parentLocation);
const parentLView = getParentInjectorView(parentLocation, lView);
const parentTView = parentLView[TVIEW];
const parentTNode = parentTView.data[parentInjectorIndex + NodeInjectorOffset.TNODE] as TNode;
return new NodeInjector(
parentTNode as TElementNode | TContainerNode | TElementContainerNode,
parentLView,
);
} else {
const chainedInjector = lView[INJECTOR] as ChainedInjector;
// Case where chainedInjector.injector is an OutletInjector and chainedInjector.injector.parent
// is a NodeInjector.
// todo(aleksanderbodurri): ideally nothing in packages/core should deal
// directly with router concerns. Refactor this so that we can make the jump from
// NodeInjector -> OutletInjector -> NodeInjector
// without explicitly relying on types contracts from packages/router
const injectorParent = (chainedInjector.injector as any)?.parent as Injector;
if (injectorParent instanceof NodeInjector) {
return injectorParent;
}
}
return null;
}
/**
* Gets the module injector of a NodeInjector.
*
* @param injector NodeInjector to get module injector of
* @returns Injector representing module injector of the given NodeInjector
*/
function getModuleInjectorOfNodeInjector(injector: NodeInjector): Injector {
let lView: LView<unknown>;
if (injector instanceof NodeInjector) {
lView = getNodeInjectorLView(injector);
} else {
throwError('getModuleInjectorOfNodeInjector must be called with a NodeInjector');
}
const inj = lView[INJECTOR] as R3Injector | ChainedInjector;
const moduleInjector = inj instanceof ChainedInjector ? inj.parentInjector : inj.parent;
if (!moduleInjector) {
throwError('NodeInjector must have some connection to the module injector tree');
}
return moduleInjector;
}
| {
"end_byte": 27088,
"start_byte": 23825,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/injector_discovery_utils.ts"
} |
angular/packages/core/src/render3/util/view_utils.ts_0_7420 | /**
* @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 {NotificationSource} from '../../change_detection/scheduling/zoneless_scheduling';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {
assertDefined,
assertGreaterThan,
assertGreaterThanOrEqual,
assertIndexInRange,
assertLessThan,
} from '../../util/assert';
import {assertLView, assertTNode, assertTNodeForLView} from '../assert';
import {LContainer, TYPE} from '../interfaces/container';
import {TConstants, TNode} from '../interfaces/node';
import {RNode} from '../interfaces/renderer_dom';
import {isLContainer, isLView} from '../interfaces/type_checks';
import {
DECLARATION_VIEW,
ENVIRONMENT,
FLAGS,
HEADER_OFFSET,
HOST,
LView,
LViewFlags,
ON_DESTROY_HOOKS,
PARENT,
PREORDER_HOOK_FLAGS,
PreOrderHookFlags,
REACTIVE_TEMPLATE_CONSUMER,
TData,
TView,
} from '../interfaces/view';
/**
* For efficiency reasons we often put several different data types (`RNode`, `LView`, `LContainer`)
* in same location in `LView`. This is because we don't want to pre-allocate space for it
* because the storage is sparse. This file contains utilities for dealing with such data types.
*
* How do we know what is stored at a given location in `LView`.
* - `Array.isArray(value) === false` => `RNode` (The normal storage value)
* - `Array.isArray(value) === true` => then the `value[0]` represents the wrapped value.
* - `typeof value[TYPE] === 'object'` => `LView`
* - This happens when we have a component at a given location
* - `typeof value[TYPE] === true` => `LContainer`
* - This happens when we have `LContainer` binding at a given location.
*
*
* NOTE: it is assumed that `Array.isArray` and `typeof` operations are very efficient.
*/
/**
* Returns `RNode`.
* @param value wrapped value of `RNode`, `LView`, `LContainer`
*/
export function unwrapRNode(value: RNode | LView | LContainer): RNode {
while (Array.isArray(value)) {
value = value[HOST] as any;
}
return value as RNode;
}
/**
* Returns `LView` or `null` if not found.
* @param value wrapped value of `RNode`, `LView`, `LContainer`
*/
export function unwrapLView(value: RNode | LView | LContainer): LView | null {
while (Array.isArray(value)) {
// This check is same as `isLView()` but we don't call at as we don't want to call
// `Array.isArray()` twice and give JITer more work for inlining.
if (typeof value[TYPE] === 'object') return value as LView;
value = value[HOST] as any;
}
return null;
}
/**
* Retrieves an element value from the provided `viewData`, by unwrapping
* from any containers, component views, or style contexts.
*/
export function getNativeByIndex(index: number, lView: LView): RNode {
ngDevMode && assertIndexInRange(lView, index);
ngDevMode && assertGreaterThanOrEqual(index, HEADER_OFFSET, 'Expected to be past HEADER_OFFSET');
return unwrapRNode(lView[index]);
}
/**
* Retrieve an `RNode` for a given `TNode` and `LView`.
*
* This function guarantees in dev mode to retrieve a non-null `RNode`.
*
* @param tNode
* @param lView
*/
export function getNativeByTNode(tNode: TNode, lView: LView): RNode {
ngDevMode && assertTNodeForLView(tNode, lView);
ngDevMode && assertIndexInRange(lView, tNode.index);
const node: RNode = unwrapRNode(lView[tNode.index]);
return node;
}
/**
* Retrieve an `RNode` or `null` for a given `TNode` and `LView`.
*
* Some `TNode`s don't have associated `RNode`s. For example `Projection`
*
* @param tNode
* @param lView
*/
export function getNativeByTNodeOrNull(tNode: TNode | null, lView: LView): RNode | null {
const index = tNode === null ? -1 : tNode.index;
if (index !== -1) {
ngDevMode && assertTNodeForLView(tNode!, lView);
const node: RNode | null = unwrapRNode(lView[index]);
return node;
}
return null;
}
// fixme(misko): The return Type should be `TNode|null`
export function getTNode(tView: TView, index: number): TNode {
ngDevMode && assertGreaterThan(index, -1, 'wrong index for TNode');
ngDevMode && assertLessThan(index, tView.data.length, 'wrong index for TNode');
const tNode = tView.data[index] as TNode;
ngDevMode && tNode !== null && assertTNode(tNode);
return tNode;
}
/** Retrieves a value from any `LView` or `TData`. */
export function load<T>(view: LView | TData, index: number): T {
ngDevMode && assertIndexInRange(view, index);
return view[index];
}
export function getComponentLViewByIndex(nodeIndex: number, hostView: LView): LView {
// Could be an LView or an LContainer. If LContainer, unwrap to find LView.
ngDevMode && assertIndexInRange(hostView, nodeIndex);
const slotValue = hostView[nodeIndex];
const lView = isLView(slotValue) ? slotValue : slotValue[HOST];
return lView;
}
/** Checks whether a given view is in creation mode */
export function isCreationMode(view: LView): boolean {
return (view[FLAGS] & LViewFlags.CreationMode) === LViewFlags.CreationMode;
}
/**
* Returns a boolean for whether the view is attached to the change detection tree.
*
* Note: This determines whether a view should be checked, not whether it's inserted
* into a container. For that, you'll want `viewAttachedToContainer` below.
*/
export function viewAttachedToChangeDetector(view: LView): boolean {
return (view[FLAGS] & LViewFlags.Attached) === LViewFlags.Attached;
}
/** Returns a boolean for whether the view is attached to a container. */
export function viewAttachedToContainer(view: LView): boolean {
return isLContainer(view[PARENT]);
}
/** Returns a constant from `TConstants` instance. */
export function getConstant<T>(consts: TConstants | null, index: null | undefined): null;
export function getConstant<T>(consts: TConstants, index: number): T | null;
export function getConstant<T>(
consts: TConstants | null,
index: number | null | undefined,
): T | null;
export function getConstant<T>(
consts: TConstants | null,
index: number | null | undefined,
): T | null {
if (index === null || index === undefined) return null;
ngDevMode && assertIndexInRange(consts!, index);
return consts![index] as unknown as T;
}
/**
* Resets the pre-order hook flags of the view.
* @param lView the LView on which the flags are reset
*/
export function resetPreOrderHookFlags(lView: LView) {
lView[PREORDER_HOOK_FLAGS] = 0 as PreOrderHookFlags;
}
/**
* Adds the `RefreshView` flag from the lView and updates HAS_CHILD_VIEWS_TO_REFRESH flag of
* parents.
*/
export function markViewForRefresh(lView: LView) {
if (lView[FLAGS] & LViewFlags.RefreshView) {
return;
}
lView[FLAGS] |= LViewFlags.RefreshView;
if (viewAttachedToChangeDetector(lView)) {
markAncestorsForTraversal(lView);
}
}
/**
* Walks up the LView hierarchy.
* @param nestingLevel Number of times to walk up in hierarchy.
* @param currentView View from which to start the lookup.
*/
export function walkUpViews(nestingLevel: number, currentView: LView): LView {
while (nestingLevel > 0) {
ngDevMode &&
assertDefined(
currentView[DECLARATION_VIEW],
'Declaration view should be defined if nesting level is greater than 0.',
);
currentView = currentView[DECLARATION_VIEW]!;
nestingLevel--;
}
return currentView;
} | {
"end_byte": 7420,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/view_utils.ts"
} |
angular/packages/core/src/render3/util/view_utils.ts_7422_10259 | export function requiresRefreshOrTraversal(lView: LView) {
return !!(
lView[FLAGS] & (LViewFlags.RefreshView | LViewFlags.HasChildViewsToRefresh) ||
lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty
);
}
/**
* Updates the `HasChildViewsToRefresh` flag on the parents of the `LView` as well as the
* parents above.
*/
export function updateAncestorTraversalFlagsOnAttach(lView: LView) {
lView[ENVIRONMENT].changeDetectionScheduler?.notify(NotificationSource.ViewAttached);
if (lView[FLAGS] & LViewFlags.Dirty) {
lView[FLAGS] |= LViewFlags.RefreshView;
}
if (requiresRefreshOrTraversal(lView)) {
markAncestorsForTraversal(lView);
}
}
/**
* Ensures views above the given `lView` are traversed during change detection even when they are
* not dirty.
*
* This is done by setting the `HAS_CHILD_VIEWS_TO_REFRESH` flag up to the root, stopping when the
* flag is already `true` or the `lView` is detached.
*/
export function markAncestorsForTraversal(lView: LView) {
lView[ENVIRONMENT].changeDetectionScheduler?.notify(NotificationSource.MarkAncestorsForTraversal);
let parent = getLViewParent(lView);
while (parent !== null) {
// We stop adding markers to the ancestors once we reach one that already has the marker. This
// is to avoid needlessly traversing all the way to the root when the marker already exists.
if (parent[FLAGS] & LViewFlags.HasChildViewsToRefresh) {
break;
}
parent[FLAGS] |= LViewFlags.HasChildViewsToRefresh;
if (!viewAttachedToChangeDetector(parent)) {
break;
}
parent = getLViewParent(parent);
}
}
/**
* Stores a LView-specific destroy callback.
*/
export function storeLViewOnDestroy(lView: LView, onDestroyCallback: () => void) {
if ((lView[FLAGS] & LViewFlags.Destroyed) === LViewFlags.Destroyed) {
throw new RuntimeError(
RuntimeErrorCode.VIEW_ALREADY_DESTROYED,
ngDevMode && 'View has already been destroyed.',
);
}
if (lView[ON_DESTROY_HOOKS] === null) {
lView[ON_DESTROY_HOOKS] = [];
}
lView[ON_DESTROY_HOOKS].push(onDestroyCallback);
}
/**
* Removes previously registered LView-specific destroy callback.
*/
export function removeLViewOnDestroy(lView: LView, onDestroyCallback: () => void) {
if (lView[ON_DESTROY_HOOKS] === null) return;
const destroyCBIdx = lView[ON_DESTROY_HOOKS].indexOf(onDestroyCallback);
if (destroyCBIdx !== -1) {
lView[ON_DESTROY_HOOKS].splice(destroyCBIdx, 1);
}
}
/**
* Gets the parent LView of the passed LView, if the PARENT is an LContainer, will get the parent of
* that LContainer, which is an LView
* @param lView the lView whose parent to get
*/
export function getLViewParent(lView: LView): LView | null {
ngDevMode && assertLView(lView);
const parent = lView[PARENT];
return isLContainer(parent) ? parent[PARENT] : parent;
} | {
"end_byte": 10259,
"start_byte": 7422,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/util/view_utils.ts"
} |
angular/packages/core/src/render3/features/ng_onchanges_feature.ts_0_4479 | /**
* @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 {InputSignalNode} from '../../authoring/input/input_signal_node';
import {OnChanges} from '../../interface/lifecycle_hooks';
import {SimpleChange, SimpleChanges} from '../../interface/simple_change';
import {assertString} from '../../util/assert';
import {EMPTY_OBJ} from '../../util/empty';
import {applyValueToInputField} from '../apply_value_input_field';
import {DirectiveDef, DirectiveDefFeature} from '../interfaces/definition';
/**
* The NgOnChangesFeature decorates a component with support for the ngOnChanges
* lifecycle hook, so it should be included in any component that implements
* that hook.
*
* If the component or directive uses inheritance, the NgOnChangesFeature MUST
* be included as a feature AFTER {@link InheritDefinitionFeature}, otherwise
* inherited properties will not be propagated to the ngOnChanges lifecycle
* hook.
*
* Example usage:
*
* ```
* static ɵcmp = defineComponent({
* ...
* inputs: {name: 'publicName'},
* features: [NgOnChangesFeature]
* });
* ```
*
* @codeGenApi
*/
export const ɵɵNgOnChangesFeature: () => DirectiveDefFeature = /* @__PURE__ */ (() => {
const ɵɵNgOnChangesFeatureImpl = () => NgOnChangesFeatureImpl;
// This option ensures that the ngOnChanges lifecycle hook will be inherited
// from superclasses (in InheritDefinitionFeature).
/** @nocollapse */
ɵɵNgOnChangesFeatureImpl.ngInherit = true;
return ɵɵNgOnChangesFeatureImpl;
})();
export function NgOnChangesFeatureImpl<T>(definition: DirectiveDef<T>) {
if (definition.type.prototype.ngOnChanges) {
definition.setInput = ngOnChangesSetInput;
}
return rememberChangeHistoryAndInvokeOnChangesHook;
}
/**
* This is a synthetic lifecycle hook which gets inserted into `TView.preOrderHooks` to simulate
* `ngOnChanges`.
*
* The hook reads the `NgSimpleChangesStore` data from the component instance and if changes are
* found it invokes `ngOnChanges` on the component instance.
*
* @param this Component instance. Because this function gets inserted into `TView.preOrderHooks`,
* it is guaranteed to be called with component instance.
*/
function rememberChangeHistoryAndInvokeOnChangesHook(this: OnChanges) {
const simpleChangesStore = getSimpleChangesStore(this);
const current = simpleChangesStore?.current;
if (current) {
const previous = simpleChangesStore!.previous;
if (previous === EMPTY_OBJ) {
simpleChangesStore!.previous = current;
} else {
// New changes are copied to the previous store, so that we don't lose history for inputs
// which were not changed this time
for (let key in current) {
previous[key] = current[key];
}
}
simpleChangesStore!.current = null;
this.ngOnChanges(current);
}
}
function ngOnChangesSetInput<T>(
this: DirectiveDef<T>,
instance: T,
inputSignalNode: null | InputSignalNode<unknown, unknown>,
value: unknown,
publicName: string,
privateName: string,
): void {
const declaredName = (this.declaredInputs as {[key: string]: string})[publicName];
ngDevMode && assertString(declaredName, 'Name of input in ngOnChanges has to be a string');
const simpleChangesStore =
getSimpleChangesStore(instance) ||
setSimpleChangesStore(instance, {previous: EMPTY_OBJ, current: null});
const current = simpleChangesStore.current || (simpleChangesStore.current = {});
const previous = simpleChangesStore.previous;
const previousChange = previous[declaredName];
current[declaredName] = new SimpleChange(
previousChange && previousChange.currentValue,
value,
previous === EMPTY_OBJ,
);
applyValueToInputField(instance, inputSignalNode, privateName, value);
}
const SIMPLE_CHANGES_STORE = '__ngSimpleChanges__';
function getSimpleChangesStore(instance: any): null | NgSimpleChangesStore {
return instance[SIMPLE_CHANGES_STORE] || null;
}
function setSimpleChangesStore(instance: any, store: NgSimpleChangesStore): NgSimpleChangesStore {
return (instance[SIMPLE_CHANGES_STORE] = store);
}
/**
* Data structure which is monkey-patched on the component instance and used by `ngOnChanges`
* life-cycle hook to track previous input values.
*/
interface NgSimpleChangesStore {
previous: SimpleChanges;
current: SimpleChanges | null;
}
| {
"end_byte": 4479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/ng_onchanges_feature.ts"
} |
angular/packages/core/src/render3/features/host_directives_feature.ts_0_8946 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {resolveForwardRef} from '../../di';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {Type} from '../../interface/type';
import {assertEqual} from '../../util/assert';
import {EMPTY_OBJ} from '../../util/empty';
import {getComponentDef, getDirectiveDef} from '../def_getters';
import {
DirectiveDef,
DirectiveDefFeature,
HostDirectiveBindingMap,
HostDirectiveDef,
HostDirectiveDefs,
} from '../interfaces/definition';
/** Values that can be used to define a host directive through the `HostDirectivesFeature`. */
type HostDirectiveConfig =
| Type<unknown>
| {
directive: Type<unknown>;
inputs?: string[];
outputs?: string[];
};
/**
* This feature adds the host directives behavior to a directive definition by patching a
* function onto it. The expectation is that the runtime will invoke the function during
* directive matching.
*
* For example:
* ```ts
* class ComponentWithHostDirective {
* static ɵcmp = defineComponent({
* type: ComponentWithHostDirective,
* features: [ɵɵHostDirectivesFeature([
* SimpleHostDirective,
* {directive: AdvancedHostDirective, inputs: ['foo: alias'], outputs: ['bar']},
* ])]
* });
* }
* ```
*
* @codeGenApi
*/
export function ɵɵHostDirectivesFeature(
rawHostDirectives: HostDirectiveConfig[] | (() => HostDirectiveConfig[]),
) {
const feature: DirectiveDefFeature = (definition: DirectiveDef<unknown>) => {
const resolved = (
Array.isArray(rawHostDirectives) ? rawHostDirectives : rawHostDirectives()
).map((dir) => {
return typeof dir === 'function'
? {directive: resolveForwardRef(dir), inputs: EMPTY_OBJ, outputs: EMPTY_OBJ}
: {
directive: resolveForwardRef(dir.directive),
inputs: bindingArrayToMap(dir.inputs),
outputs: bindingArrayToMap(dir.outputs),
};
});
if (definition.hostDirectives === null) {
definition.findHostDirectiveDefs = findHostDirectiveDefs;
definition.hostDirectives = resolved;
} else {
definition.hostDirectives.unshift(...resolved);
}
};
feature.ngInherit = true;
return feature;
}
function findHostDirectiveDefs(
currentDef: DirectiveDef<unknown>,
matchedDefs: DirectiveDef<unknown>[],
hostDirectiveDefs: HostDirectiveDefs,
): void {
if (currentDef.hostDirectives !== null) {
for (const hostDirectiveConfig of currentDef.hostDirectives) {
const hostDirectiveDef = getDirectiveDef(hostDirectiveConfig.directive)!;
if (typeof ngDevMode === 'undefined' || ngDevMode) {
validateHostDirective(hostDirectiveConfig, hostDirectiveDef);
}
// We need to patch the `declaredInputs` so that
// `ngOnChanges` can map the properties correctly.
patchDeclaredInputs(hostDirectiveDef.declaredInputs, hostDirectiveConfig.inputs);
// Host directives execute before the host so that its host bindings can be overwritten.
findHostDirectiveDefs(hostDirectiveDef, matchedDefs, hostDirectiveDefs);
hostDirectiveDefs.set(hostDirectiveDef, hostDirectiveConfig);
matchedDefs.push(hostDirectiveDef);
}
}
}
/**
* Converts an array in the form of `['publicName', 'alias', 'otherPublicName', 'otherAlias']` into
* a map in the form of `{publicName: 'alias', otherPublicName: 'otherAlias'}`.
*/
function bindingArrayToMap(bindings: string[] | undefined): HostDirectiveBindingMap {
if (bindings === undefined || bindings.length === 0) {
return EMPTY_OBJ;
}
const result: HostDirectiveBindingMap = {};
for (let i = 0; i < bindings.length; i += 2) {
result[bindings[i]] = bindings[i + 1];
}
return result;
}
/**
* `ngOnChanges` has some leftover legacy ViewEngine behavior where the keys inside the
* `SimpleChanges` event refer to the *declared* name of the input, not its public name or its
* minified name. E.g. in `@Input('alias') foo: string`, the name in the `SimpleChanges` object
* will always be `foo`, and not `alias` or the minified name of `foo` in apps using property
* minification.
*
* This is achieved through the `DirectiveDef.declaredInputs` map that is constructed when the
* definition is declared. When a property is written to the directive instance, the
* `NgOnChangesFeature` will try to remap the property name being written to using the
* `declaredInputs`.
*
* Since the host directive input remapping happens during directive matching, `declaredInputs`
* won't contain the new alias that the input is available under. This function addresses the
* issue by patching the host directive aliases to the `declaredInputs`. There is *not* a risk of
* this patching accidentally introducing new inputs to the host directive, because `declaredInputs`
* is used *only* by the `NgOnChangesFeature` when determining what name is used in the
* `SimpleChanges` object which won't be reached if an input doesn't exist.
*/
function patchDeclaredInputs(
declaredInputs: Record<string, string>,
exposedInputs: HostDirectiveBindingMap,
): void {
for (const publicName in exposedInputs) {
if (exposedInputs.hasOwnProperty(publicName)) {
const remappedPublicName = exposedInputs[publicName];
const privateName = declaredInputs[publicName];
// We *technically* shouldn't be able to hit this case because we can't have multiple
// inputs on the same property and we have validations against conflicting aliases in
// `validateMappings`. If we somehow did, it would lead to `ngOnChanges` being invoked
// with the wrong name so we have a non-user-friendly assertion here just in case.
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
declaredInputs.hasOwnProperty(remappedPublicName)
) {
assertEqual(
declaredInputs[remappedPublicName],
declaredInputs[publicName],
`Conflicting host directive input alias ${publicName}.`,
);
}
declaredInputs[remappedPublicName] = privateName;
}
}
}
/**
* Verifies that the host directive has been configured correctly.
* @param hostDirectiveConfig Host directive configuration object.
* @param directiveDef Directive definition of the host directive.
*/
function validateHostDirective(
hostDirectiveConfig: HostDirectiveDef<unknown>,
directiveDef: DirectiveDef<any> | null,
): asserts directiveDef is DirectiveDef<unknown> {
const type = hostDirectiveConfig.directive;
if (directiveDef === null) {
if (getComponentDef(type) !== null) {
throw new RuntimeError(
RuntimeErrorCode.HOST_DIRECTIVE_COMPONENT,
`Host directive ${type.name} cannot be a component.`,
);
}
throw new RuntimeError(
RuntimeErrorCode.HOST_DIRECTIVE_UNRESOLVABLE,
`Could not resolve metadata for host directive ${type.name}. ` +
`Make sure that the ${type.name} class is annotated with an @Directive decorator.`,
);
}
if (!directiveDef.standalone) {
throw new RuntimeError(
RuntimeErrorCode.HOST_DIRECTIVE_NOT_STANDALONE,
`Host directive ${directiveDef.type.name} must be standalone.`,
);
}
validateMappings('input', directiveDef, hostDirectiveConfig.inputs);
validateMappings('output', directiveDef, hostDirectiveConfig.outputs);
}
/**
* Checks that the host directive inputs/outputs configuration is valid.
* @param bindingType Kind of binding that is being validated. Used in the error message.
* @param def Definition of the host directive that is being validated against.
* @param hostDirectiveBindings Host directive mapping object that shold be validated.
*/
function validateMappings<T>(
bindingType: 'input' | 'output',
def: DirectiveDef<T>,
hostDirectiveBindings: HostDirectiveBindingMap,
) {
const className = def.type.name;
const bindings = bindingType === 'input' ? def.inputs : def.outputs;
for (const publicName in hostDirectiveBindings) {
if (hostDirectiveBindings.hasOwnProperty(publicName)) {
if (!bindings.hasOwnProperty(publicName)) {
throw new RuntimeError(
RuntimeErrorCode.HOST_DIRECTIVE_UNDEFINED_BINDING,
`Directive ${className} does not have an ${bindingType} with a public name of ${publicName}.`,
);
}
const remappedPublicName = hostDirectiveBindings[publicName];
if (bindings.hasOwnProperty(remappedPublicName) && remappedPublicName !== publicName) {
throw new RuntimeError(
RuntimeErrorCode.HOST_DIRECTIVE_CONFLICTING_ALIAS,
`Cannot alias ${bindingType} ${publicName} of host directive ${className} to ${remappedPublicName}, because it already has a different ${bindingType} with the same public name.`,
);
}
}
}
}
| {
"end_byte": 8946,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/host_directives_feature.ts"
} |
angular/packages/core/src/render3/features/copy_definition_feature.ts_0_3343 | /**
* @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 {ComponentDef, DirectiveDef} from '../interfaces/definition';
import {isComponentDef} from '../interfaces/type_checks';
import {getSuperType} from './inherit_definition_feature';
/**
* Fields which exist on either directive or component definitions, and need to be copied from
* parent to child classes by the `ɵɵCopyDefinitionFeature`.
*/
const COPY_DIRECTIVE_FIELDS: (keyof DirectiveDef<unknown>)[] = [
// The child class should use the providers of its parent.
'providersResolver',
// Not listed here are any fields which are handled by the `ɵɵInheritDefinitionFeature`, such
// as inputs, outputs, and host binding functions.
];
/**
* Fields which exist only on component definitions, and need to be copied from parent to child
* classes by the `ɵɵCopyDefinitionFeature`.
*
* The type here allows any field of `ComponentDef` which is not also a property of `DirectiveDef`,
* since those should go in `COPY_DIRECTIVE_FIELDS` above.
*/
const COPY_COMPONENT_FIELDS: Exclude<keyof ComponentDef<unknown>, keyof DirectiveDef<unknown>>[] = [
// The child class should use the template function of its parent, including all template
// semantics.
'template',
'decls',
'consts',
'vars',
'onPush',
'ngContentSelectors',
// The child class should use the CSS styles of its parent, including all styling semantics.
'styles',
'encapsulation',
// The child class should be checked by the runtime in the same way as its parent.
'schemas',
];
/**
* Copies the fields not handled by the `ɵɵInheritDefinitionFeature` from the supertype of a
* definition.
*
* This exists primarily to support ngcc migration of an existing View Engine pattern, where an
* entire decorator is inherited from a parent to a child class. When ngcc detects this case, it
* generates a skeleton definition on the child class, and applies this feature.
*
* The `ɵɵCopyDefinitionFeature` then copies any needed fields from the parent class' definition,
* including things like the component template function.
*
* @param definition The definition of a child class which inherits from a parent class with its
* own definition.
*
* @codeGenApi
*/
export function ɵɵCopyDefinitionFeature(definition: DirectiveDef<any> | ComponentDef<any>): void {
let superType = getSuperType(definition.type)!;
let superDef: DirectiveDef<any> | ComponentDef<any> | undefined = undefined;
if (isComponentDef(definition)) {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵcmp!;
} else {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵdir!;
}
// Needed because `definition` fields are readonly.
const defAny = definition as any;
// Copy over any fields that apply to either directives or components.
for (const field of COPY_DIRECTIVE_FIELDS) {
defAny[field] = superDef[field];
}
if (isComponentDef(superDef)) {
// Copy over any component-specific fields.
for (const field of COPY_COMPONENT_FIELDS) {
defAny[field] = superDef[field];
}
}
}
| {
"end_byte": 3343,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/copy_definition_feature.ts"
} |
angular/packages/core/src/render3/features/providers_feature.ts_0_1708 | /**
* @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 {ProcessProvidersFunction, Provider} from '../../di/interface/provider';
import {providersResolver} from '../di_setup';
import {DirectiveDef} from '../interfaces/definition';
/**
* This feature resolves the providers of a directive (or component),
* and publish them into the DI system, making it visible to others for injection.
*
* For example:
* ```ts
* class ComponentWithProviders {
* constructor(private greeter: GreeterDE) {}
*
* static ɵcmp = defineComponent({
* type: ComponentWithProviders,
* selectors: [['component-with-providers']],
* factory: () => new ComponentWithProviders(directiveInject(GreeterDE as any)),
* decls: 1,
* vars: 1,
* template: function(fs: RenderFlags, ctx: ComponentWithProviders) {
* if (fs & RenderFlags.Create) {
* ɵɵtext(0);
* }
* if (fs & RenderFlags.Update) {
* ɵɵtextInterpolate(ctx.greeter.greet());
* }
* },
* features: [ɵɵProvidersFeature([GreeterDE])]
* });
* }
* ```
*
* @param definition
*
* @codeGenApi
*/
export function ɵɵProvidersFeature<T>(providers: Provider[], viewProviders: Provider[] = []) {
return (definition: DirectiveDef<T>) => {
definition.providersResolver = (
def: DirectiveDef<T>,
processProvidersFn?: ProcessProvidersFunction,
) => {
return providersResolver(
def, //
processProvidersFn ? processProvidersFn(providers) : providers, //
viewProviders,
);
};
};
}
| {
"end_byte": 1708,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/providers_feature.ts"
} |
angular/packages/core/src/render3/features/inherit_definition_feature.ts_0_8841 | /**
* @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, Writable} from '../../interface/type';
import {EMPTY_ARRAY, EMPTY_OBJ} from '../../util/empty';
import {fillProperties} from '../../util/property';
import {
ComponentDef,
ContentQueriesFunction,
DirectiveDef,
DirectiveDefFeature,
HostBindingsFunction,
RenderFlags,
ViewQueriesFunction,
} from '../interfaces/definition';
import {TAttributes} from '../interfaces/node';
import {isComponentDef} from '../interfaces/type_checks';
import {mergeHostAttrs} from '../util/attrs_utils';
import {stringifyForError} from '../util/stringify_utils';
export function getSuperType(
type: Type<any>,
): Type<any> & {ɵcmp?: ComponentDef<any>; ɵdir?: DirectiveDef<any>} {
return Object.getPrototypeOf(type.prototype).constructor;
}
type WritableDef = Writable<DirectiveDef<any> | ComponentDef<any>>;
/**
* Merges the definition from a super class to a sub class.
* @param definition The definition that is a SubClass of another directive of component
*
* @codeGenApi
*/
export function ɵɵInheritDefinitionFeature(
definition: DirectiveDef<any> | ComponentDef<any>,
): void {
let superType = getSuperType(definition.type);
let shouldInheritFields = true;
const inheritanceChain: WritableDef[] = [definition];
while (superType) {
let superDef: DirectiveDef<any> | ComponentDef<any> | undefined = undefined;
if (isComponentDef(definition)) {
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵcmp || superType.ɵdir;
} else {
if (superType.ɵcmp) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INHERITANCE,
ngDevMode &&
`Directives cannot inherit Components. Directive ${stringifyForError(
definition.type,
)} is attempting to extend component ${stringifyForError(superType)}`,
);
}
// Don't use getComponentDef/getDirectiveDef. This logic relies on inheritance.
superDef = superType.ɵdir;
}
if (superDef) {
if (shouldInheritFields) {
inheritanceChain.push(superDef);
// Some fields in the definition may be empty, if there were no values to put in them that
// would've justified object creation. Unwrap them if necessary.
const writeableDef = definition as WritableDef;
writeableDef.inputs = maybeUnwrapEmpty(definition.inputs);
writeableDef.inputTransforms = maybeUnwrapEmpty(definition.inputTransforms);
writeableDef.declaredInputs = maybeUnwrapEmpty(definition.declaredInputs);
writeableDef.outputs = maybeUnwrapEmpty(definition.outputs);
// Merge hostBindings
const superHostBindings = superDef.hostBindings;
superHostBindings && inheritHostBindings(definition, superHostBindings);
// Merge queries
const superViewQuery = superDef.viewQuery;
const superContentQueries = superDef.contentQueries;
superViewQuery && inheritViewQuery(definition, superViewQuery);
superContentQueries && inheritContentQueries(definition, superContentQueries);
// Merge inputs and outputs
mergeInputsWithTransforms(definition, superDef);
fillProperties(definition.outputs, superDef.outputs);
// Merge animations metadata.
// If `superDef` is a Component, the `data` field is present (defaults to an empty object).
if (isComponentDef(superDef) && superDef.data.animation) {
// If super def is a Component, the `definition` is also a Component, since Directives can
// not inherit Components (we throw an error above and cannot reach this code).
const defData = (definition as ComponentDef<any>).data;
defData.animation = (defData.animation || []).concat(superDef.data.animation);
}
}
// Run parent features
const features = superDef.features;
if (features) {
for (let i = 0; i < features.length; i++) {
const feature = features[i];
if (feature && feature.ngInherit) {
(feature as DirectiveDefFeature)(definition);
}
// If `InheritDefinitionFeature` is a part of the current `superDef`, it means that this
// def already has all the necessary information inherited from its super class(es), so we
// can stop merging fields from super classes. However we need to iterate through the
// prototype chain to look for classes that might contain other "features" (like
// NgOnChanges), which we should invoke for the original `definition`. We set the
// `shouldInheritFields` flag to indicate that, essentially skipping fields inheritance
// logic and only invoking functions from the "features" list.
if (feature === ɵɵInheritDefinitionFeature) {
shouldInheritFields = false;
}
}
}
}
superType = Object.getPrototypeOf(superType);
}
mergeHostAttrsAcrossInheritance(inheritanceChain);
}
function mergeInputsWithTransforms<T>(target: WritableDef, source: DirectiveDef<any>) {
for (const key in source.inputs) {
if (!source.inputs.hasOwnProperty(key)) {
continue;
}
if (target.inputs.hasOwnProperty(key)) {
continue;
}
const value = source.inputs[key];
if (value === undefined) {
continue;
}
target.inputs[key] = value;
target.declaredInputs[key] = source.declaredInputs[key];
// If the input is inherited, and we have a transform for it, we also inherit it.
// Note that transforms should not be inherited if the input has its own metadata
// in the `source` directive itself already (i.e. the input is re-declared/overridden).
if (source.inputTransforms !== null) {
// Note: transforms are stored with their minified names.
// Perf: only access the minified name when there are source transforms.
const minifiedName = Array.isArray(value) ? value[0] : value;
if (!source.inputTransforms.hasOwnProperty(minifiedName)) {
continue;
}
target.inputTransforms ??= {};
target.inputTransforms[minifiedName] = source.inputTransforms[minifiedName];
}
}
}
/**
* Merge the `hostAttrs` and `hostVars` from the inherited parent to the base class.
*
* @param inheritanceChain A list of `WritableDefs` starting at the top most type and listing
* sub-types in order. For each type take the `hostAttrs` and `hostVars` and merge it with the child
* type.
*/
function mergeHostAttrsAcrossInheritance(inheritanceChain: WritableDef[]) {
let hostVars: number = 0;
let hostAttrs: TAttributes | null = null;
// We process the inheritance order from the base to the leaves here.
for (let i = inheritanceChain.length - 1; i >= 0; i--) {
const def = inheritanceChain[i];
// For each `hostVars`, we need to add the superclass amount.
def.hostVars = hostVars += def.hostVars;
// for each `hostAttrs` we need to merge it with superclass.
def.hostAttrs = mergeHostAttrs(
def.hostAttrs,
(hostAttrs = mergeHostAttrs(hostAttrs, def.hostAttrs)),
);
}
}
function maybeUnwrapEmpty<T>(value: T[]): T[];
function maybeUnwrapEmpty<T>(value: T): T;
function maybeUnwrapEmpty(value: any): any {
if (value === EMPTY_OBJ) {
return {};
} else if (value === EMPTY_ARRAY) {
return [];
} else {
return value;
}
}
function inheritViewQuery(definition: WritableDef, superViewQuery: ViewQueriesFunction<any>) {
const prevViewQuery = definition.viewQuery;
if (prevViewQuery) {
definition.viewQuery = (rf, ctx) => {
superViewQuery(rf, ctx);
prevViewQuery(rf, ctx);
};
} else {
definition.viewQuery = superViewQuery;
}
}
function inheritContentQueries(
definition: WritableDef,
superContentQueries: ContentQueriesFunction<any>,
) {
const prevContentQueries = definition.contentQueries;
if (prevContentQueries) {
definition.contentQueries = (rf, ctx, directiveIndex) => {
superContentQueries(rf, ctx, directiveIndex);
prevContentQueries(rf, ctx, directiveIndex);
};
} else {
definition.contentQueries = superContentQueries;
}
}
function inheritHostBindings(
definition: WritableDef,
superHostBindings: HostBindingsFunction<any>,
) {
const prevHostBindings = definition.hostBindings;
if (prevHostBindings) {
definition.hostBindings = (rf: RenderFlags, ctx: any) => {
superHostBindings(rf, ctx);
prevHostBindings(rf, ctx);
};
} else {
definition.hostBindings = superHostBindings;
}
}
| {
"end_byte": 8841,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/inherit_definition_feature.ts"
} |
angular/packages/core/src/render3/features/input_transforms_feature.ts_0_1311 | /**
* @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 {Writable} from '../../interface/type';
import {DirectiveDef, InputTransformFunction} from '../interfaces/definition';
/**
* Decorates the directive definition with support for input transform functions.
*
* If the directive uses inheritance, the feature should be included before the
* `InheritDefinitionFeature` to ensure that the `inputTransforms` field is populated.
*
* @codeGenApi
*/
export function ɵɵInputTransformsFeature<T>(definition: DirectiveDef<T>): void {
const inputs = definition.inputConfig;
const inputTransforms: Record<string, InputTransformFunction> = {};
for (const minifiedKey in inputs) {
if (inputs.hasOwnProperty(minifiedKey)) {
// Note: the private names are used for the keys, rather than the public ones, because public
// names can be re-aliased in host directives which would invalidate the lookup.
const value = inputs[minifiedKey];
if (Array.isArray(value) && value[3]) {
inputTransforms[minifiedKey] = value[3];
}
}
}
(definition as Writable<DirectiveDef<T>>).inputTransforms = inputTransforms;
}
| {
"end_byte": 1311,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/input_transforms_feature.ts"
} |
angular/packages/core/src/render3/features/external_styles_feature.ts_0_1314 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ComponentDef, ComponentDefFeature} from '../interfaces/definition';
/**
* A feature that adds support for external runtime styles for a component.
* An external runtime style is a URL to a CSS stylesheet that contains the styles
* for a given component. For browsers, this URL will be used in an appended `link` element
* when the component is rendered. This feature is typically used for Hot Module Replacement
* (HMR) of component stylesheets by leveraging preexisting global stylesheet HMR available
* in most development servers.
*
* @codeGenApi
*/
export function ɵɵExternalStylesFeature(styleUrls: string[]): ComponentDefFeature {
return (definition: ComponentDef<unknown>) => {
if (styleUrls.length < 1) {
return;
}
definition.getExternalStyles = (encapsulationId) => {
// Add encapsulation ID search parameter `component` to support external style encapsulation
const urls = styleUrls.map(
(value) =>
value + '?ngcomp' + (encapsulationId ? '=' + encodeURIComponent(encapsulationId) : ''),
);
return urls;
};
};
}
| {
"end_byte": 1314,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/features/external_styles_feature.ts"
} |
angular/packages/core/src/render3/deps_tracker/api.ts_0_5172 | /**
* @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 {NgModuleType} from '../../metadata/ng_module_def';
import {
ComponentType,
DependencyTypeList,
DirectiveType,
NgModuleScopeInfoFromDecorator,
PipeType,
} from '../interfaces/definition';
/**
* Represents the set of dependencies of a type in a certain context.
*/
interface ScopeData {
pipes: Set<PipeType<any>>;
directives: Set<DirectiveType<any> | ComponentType<any> | Type<any>>;
/**
* If true it indicates that calculating this scope somehow was not successful. The consumers
* should interpret this as empty dependencies. The application of this flag is when calculating
* scope recursively, the presence of this flag in a scope dependency implies that the scope is
* also poisoned and thus we can return immediately without having to continue the recursion. The
* reason for this error is displayed as an error message in the console as per JIT behavior
* today. In addition to that, in local compilation the other build/compilations run in parallel
* with local compilation may or may not reveal some details about the error as well.
*/
isPoisoned?: boolean;
}
/**
* Represents scope data for standalone components as calculated during runtime by the deps
* tracker.
*/
interface StandaloneCompScopeData extends ScopeData {
// Standalone components include the imported NgModules in their dependencies in order to
// determine their injector info. The following field stores the set of such NgModules.
ngModules: Set<NgModuleType<any>>;
}
/** Represents scope data for NgModule as calculated during runtime by the deps tracker. */
export interface NgModuleScope {
compilation: ScopeData;
exported: ScopeData;
}
/**
* Represents scope data for standalone component as calculated during runtime by the deps tracker.
*/
export interface StandaloneComponentScope {
compilation: StandaloneCompScopeData;
}
/** Component dependencies info as calculated during runtime by the deps tracker. */
export interface ComponentDependencies {
dependencies: DependencyTypeList;
}
/**
* Public API for runtime deps tracker (RDT).
*
* All downstream tools should only use these methods.
*/
export interface DepsTrackerApi {
/**
* Computes the component dependencies, i.e., a set of components/directive/pipes that could be
* present in the component's template (This set might contain directives/components/pipes not
* necessarily used in the component's template depending on the implementation).
*
* Standalone components should specify `rawImports` as this information is not available from
* their type. The consumer (e.g., {@link getStandaloneDefFunctions}) is expected to pass this
* parameter.
*
* The implementation is expected to use some caching mechanism in order to optimize the resources
* needed to do this computation.
*/
getComponentDependencies(
cmp: ComponentType<any>,
rawImports?: (Type<any> | (() => Type<any>))[],
): ComponentDependencies;
/**
* Registers an NgModule into the tracker with the given scope info.
*
* This method should be called for every NgModule whether it is compiled in local mode or not.
* This is needed in order to compute component's dependencies as some dependencies might be in
* different compilation units with different compilation mode.
*/
registerNgModule(type: Type<any>, scopeInfo: NgModuleScopeInfoFromDecorator): void;
/**
* Clears the scope cache for NgModule or standalone component. This will force re-calculation of
* the scope, which could be an expensive operation as it involves aggregating transitive closure.
*
* The main application of this method is for test beds where we want to clear the cache to
* enforce scope update after overriding.
*/
clearScopeCacheFor(type: Type<any>): void;
/**
* Returns the scope of NgModule. Mainly to be used by JIT and test bed.
*
* The scope value here is memoized. To enforce a new calculation bust the cache by using
* `clearScopeCacheFor` method.
*/
getNgModuleScope(type: NgModuleType<any>): NgModuleScope;
/**
* Returns the scope of standalone component. Mainly to be used by JIT. This method should be
* called lazily after the initial parsing so that all the forward refs can be resolved.
*
* @param rawImports the imports statement as appears on the component decorate which consists of
* Type as well as forward refs.
*
* The scope value here is memoized. To enforce a new calculation bust the cache by using
* `clearScopeCacheFor` method.
*/
getStandaloneComponentScope(
type: ComponentType<any>,
rawImports: (Type<any> | (() => Type<any>))[],
): StandaloneComponentScope;
/**
* Checks if the NgModule declaring the component is not loaded into the browser yet. Always
* returns false for standalone components.
*/
isOrphanComponent(cmp: ComponentType<any>): boolean;
}
| {
"end_byte": 5172,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/deps_tracker/api.ts"
} |
angular/packages/core/src/render3/deps_tracker/deps_tracker.ts_0_1362 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {resolveForwardRef} from '../../di';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {Type} from '../../interface/type';
import {NgModuleType} from '../../metadata/ng_module_def';
import {flatten} from '../../util/array_utils';
import type {
ComponentType,
NgModuleScopeInfoFromDecorator,
RawScopeInfoFromDecorator,
} from '../interfaces/definition';
import {isComponent, isDirective, isNgModule, isPipe, verifyStandaloneImport} from '../jit/util';
import {getComponentDef, getNgModuleDef, isStandalone} from '../def_getters';
import {maybeUnwrapFn} from '../util/misc_utils';
import {
ComponentDependencies,
DepsTrackerApi,
NgModuleScope,
StandaloneComponentScope,
} from './api';
/**
* Indicates whether to use the runtime dependency tracker for scope calculation in JIT compilation.
* The value "false" means the old code path based on patching scope info into the types will be
* used.
*
* @deprecated For migration purposes only, to be removed soon.
*/
export const USE_RUNTIME_DEPS_TRACKER_FOR_JIT = true;
/**
* An implementation of DepsTrackerApi which will be used for JIT and local compilation.
*/ | {
"end_byte": 1362,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/deps_tracker/deps_tracker.ts"
} |
angular/packages/core/src/render3/deps_tracker/deps_tracker.ts_1363_8899 | class DepsTracker implements DepsTrackerApi {
private ownerNgModule = new Map<ComponentType<any>, NgModuleType<any>>();
private ngModulesWithSomeUnresolvedDecls = new Set<NgModuleType<any>>();
private ngModulesScopeCache = new Map<NgModuleType<any>, NgModuleScope>();
private standaloneComponentsScopeCache = new Map<ComponentType<any>, StandaloneComponentScope>();
/**
* Attempts to resolve ng module's forward ref declarations as much as possible and add them to
* the `ownerNgModule` map. This method normally should be called after the initial parsing when
* all the forward refs are resolved (e.g., when trying to render a component)
*/
private resolveNgModulesDecls(): void {
if (this.ngModulesWithSomeUnresolvedDecls.size === 0) {
return;
}
for (const moduleType of this.ngModulesWithSomeUnresolvedDecls) {
const def = getNgModuleDef(moduleType);
if (def?.declarations) {
for (const decl of maybeUnwrapFn(def.declarations)) {
if (isComponent(decl)) {
this.ownerNgModule.set(decl, moduleType);
}
}
}
}
this.ngModulesWithSomeUnresolvedDecls.clear();
}
/** @override */
getComponentDependencies(
type: ComponentType<any>,
rawImports?: RawScopeInfoFromDecorator[],
): ComponentDependencies {
this.resolveNgModulesDecls();
const def = getComponentDef(type);
if (def === null) {
throw new Error(
`Attempting to get component dependencies for a type that is not a component: ${type}`,
);
}
if (def.standalone) {
const scope = this.getStandaloneComponentScope(type, rawImports);
if (scope.compilation.isPoisoned) {
return {dependencies: []};
}
return {
dependencies: [
...scope.compilation.directives,
...scope.compilation.pipes,
...scope.compilation.ngModules,
],
};
} else {
if (!this.ownerNgModule.has(type)) {
// This component is orphan! No need to handle the error since the component rendering
// pipeline (e.g., view_container_ref) will check for this error based on configs.
return {dependencies: []};
}
const scope = this.getNgModuleScope(this.ownerNgModule.get(type)!);
if (scope.compilation.isPoisoned) {
return {dependencies: []};
}
return {
dependencies: [...scope.compilation.directives, ...scope.compilation.pipes],
};
}
}
/**
* @override
* This implementation does not make use of param scopeInfo since it assumes the scope info is
* already added to the type itself through methods like {@link ɵɵsetNgModuleScope}
*/
registerNgModule(type: Type<any>, scopeInfo: NgModuleScopeInfoFromDecorator): void {
if (!isNgModule(type)) {
throw new Error(`Attempting to register a Type which is not NgModule as NgModule: ${type}`);
}
// Lazily process the NgModules later when needed.
this.ngModulesWithSomeUnresolvedDecls.add(type);
}
/** @override */
clearScopeCacheFor(type: Type<any>): void {
this.ngModulesScopeCache.delete(type as NgModuleType);
this.standaloneComponentsScopeCache.delete(type as ComponentType<any>);
}
/** @override */
getNgModuleScope(type: NgModuleType<any>): NgModuleScope {
if (this.ngModulesScopeCache.has(type)) {
return this.ngModulesScopeCache.get(type)!;
}
const scope = this.computeNgModuleScope(type);
this.ngModulesScopeCache.set(type, scope);
return scope;
}
/** Compute NgModule scope afresh. */
private computeNgModuleScope(type: NgModuleType<any>): NgModuleScope {
const def = getNgModuleDef(type, true);
const scope: NgModuleScope = {
exported: {directives: new Set(), pipes: new Set()},
compilation: {directives: new Set(), pipes: new Set()},
};
// Analyzing imports
for (const imported of maybeUnwrapFn(def.imports)) {
if (isNgModule(imported)) {
const importedScope = this.getNgModuleScope(imported);
// When this module imports another, the imported module's exported directives and pipes
// are added to the compilation scope of this module.
addSet(importedScope.exported.directives, scope.compilation.directives);
addSet(importedScope.exported.pipes, scope.compilation.pipes);
} else if (isStandalone(imported)) {
if (isDirective(imported) || isComponent(imported)) {
scope.compilation.directives.add(imported);
} else if (isPipe(imported)) {
scope.compilation.pipes.add(imported);
} else {
// The standalone thing is neither a component nor a directive nor a pipe ... (what?)
throw new RuntimeError(
RuntimeErrorCode.RUNTIME_DEPS_INVALID_IMPORTED_TYPE,
'The standalone imported type is neither a component nor a directive nor a pipe',
);
}
} else {
// The import is neither a module nor a module-with-providers nor a standalone thing. This
// is going to be an error. So we short circuit.
scope.compilation.isPoisoned = true;
break;
}
}
// Analyzing declarations
if (!scope.compilation.isPoisoned) {
for (const decl of maybeUnwrapFn(def.declarations)) {
// Cannot declare another NgModule or a standalone thing
if (isNgModule(decl) || isStandalone(decl)) {
scope.compilation.isPoisoned = true;
break;
}
if (isPipe(decl)) {
scope.compilation.pipes.add(decl);
} else {
// decl is either a directive or a component. The component may not yet have the ɵcmp due
// to async compilation.
scope.compilation.directives.add(decl);
}
}
}
// Analyzing exports
for (const exported of maybeUnwrapFn(def.exports)) {
if (isNgModule(exported)) {
// When this module exports another, the exported module's exported directives and pipes
// are added to both the compilation and exported scopes of this module.
const exportedScope = this.getNgModuleScope(exported);
// Based on the current logic there is no way to have poisoned exported scope. So no need to
// check for it.
addSet(exportedScope.exported.directives, scope.exported.directives);
addSet(exportedScope.exported.pipes, scope.exported.pipes);
// Some test toolings which run in JIT mode depend on this behavior that the exported scope
// should also be present in the compilation scope, even though AoT does not support this
// and it is also in odds with NgModule metadata definitions. Without this some tests in
// Google will fail.
addSet(exportedScope.exported.directives, scope.compilation.directives);
addSet(exportedScope.exported.pipes, scope.compilation.pipes);
} else if (isPipe(exported)) {
scope.exported.pipes.add(exported);
} else {
scope.exported.directives.add(exported);
}
}
return scope;
}
/** @override */
getStandaloneComponentScope(
type: ComponentType<any>,
rawImports?: RawScopeInfoFromDecorator[],
): StandaloneComponentScope {
if (this.standaloneComponentsScopeCache.has(type)) {
return this.standaloneComponentsScopeCache.get(type)!;
}
const ans = this.computeStandaloneComponentScope(type, rawImports);
this.standaloneComponentsScopeCache.set(type, ans);
return ans;
}
| {
"end_byte": 8899,
"start_byte": 1363,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/deps_tracker/deps_tracker.ts"
} |
angular/packages/core/src/render3/deps_tracker/deps_tracker.ts_8903_11109 | vate computeStandaloneComponentScope(
type: ComponentType<any>,
rawImports?: RawScopeInfoFromDecorator[],
): StandaloneComponentScope {
const ans: StandaloneComponentScope = {
compilation: {
// Standalone components are always able to self-reference.
directives: new Set([type]),
pipes: new Set(),
ngModules: new Set(),
},
};
for (const rawImport of flatten(rawImports ?? [])) {
const imported = resolveForwardRef(rawImport) as Type<any>;
try {
verifyStandaloneImport(imported, type);
} catch (e) {
// Short-circuit if an import is not valid
ans.compilation.isPoisoned = true;
return ans;
}
if (isNgModule(imported)) {
ans.compilation.ngModules.add(imported);
const importedScope = this.getNgModuleScope(imported);
// Short-circuit if an imported NgModule has corrupted exported scope.
if (importedScope.exported.isPoisoned) {
ans.compilation.isPoisoned = true;
return ans;
}
addSet(importedScope.exported.directives, ans.compilation.directives);
addSet(importedScope.exported.pipes, ans.compilation.pipes);
} else if (isPipe(imported)) {
ans.compilation.pipes.add(imported);
} else if (isDirective(imported) || isComponent(imported)) {
ans.compilation.directives.add(imported);
} else {
// The imported thing is not module/pipe/directive/component, so we error and short-circuit
// here
ans.compilation.isPoisoned = true;
return ans;
}
}
return ans;
}
/** @override */
isOrphanComponent(cmp: Type<any>): boolean {
const def = getComponentDef(cmp);
if (!def || def.standalone) {
return false;
}
this.resolveNgModulesDecls();
return !this.ownerNgModule.has(cmp as ComponentType<any>);
}
}
function addSet<T>(sourceSet: Set<T>, targetSet: Set<T>): void {
for (const m of sourceSet) {
targetSet.add(m);
}
}
/** The deps tracker to be used in the current Angular app in dev mode. */
export const depsTracker = new DepsTracker();
export const TEST_ONLY = {DepsTracker};
| {
"end_byte": 11109,
"start_byte": 8903,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/deps_tracker/deps_tracker.ts"
} |
angular/packages/core/src/render3/jit/jit_options.ts_0_1192 | /**
* @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 {ViewEncapsulation} from '../../metadata/view';
export interface JitCompilerOptions {
defaultEncapsulation?: ViewEncapsulation;
preserveWhitespaces?: boolean;
}
let jitOptions: JitCompilerOptions | null = null;
export function setJitOptions(options: JitCompilerOptions): void {
if (jitOptions !== null) {
if (options.defaultEncapsulation !== jitOptions.defaultEncapsulation) {
ngDevMode &&
console.error(
'Provided value for `defaultEncapsulation` can not be changed once it has been set.',
);
return;
}
if (options.preserveWhitespaces !== jitOptions.preserveWhitespaces) {
ngDevMode &&
console.error(
'Provided value for `preserveWhitespaces` can not be changed once it has been set.',
);
return;
}
}
jitOptions = options;
}
export function getJitOptions(): JitCompilerOptions | null {
return jitOptions;
}
export function resetJitOptions(): void {
jitOptions = null;
}
| {
"end_byte": 1192,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/jit_options.ts"
} |
angular/packages/core/src/render3/jit/pipe.ts_0_2453 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
getCompilerFacade,
JitCompilerUsage,
R3PipeMetadataFacade,
} from '../../compiler/compiler_facade';
import {reflectDependencies} from '../../di/jit/util';
import {Type} from '../../interface/type';
import {Pipe} from '../../metadata/directives';
import {NG_FACTORY_DEF, NG_PIPE_DEF} from '../fields';
import {angularCoreEnv} from './environment';
import {NG_STANDALONE_DEFAULT_VALUE} from '../standalone-default-value';
export function compilePipe(type: Type<any>, meta: Pipe): void {
let ngPipeDef: any = null;
let ngFactoryDef: any = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const metadata = getPipeMetadata(type, meta);
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'pipe',
type: metadata.type,
});
ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${metadata.name}/ɵfac.js`, {
name: metadata.name,
type: metadata.type,
typeArgumentCount: 0,
deps: reflectDependencies(type),
target: compiler.FactoryTarget.Pipe,
});
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
Object.defineProperty(type, NG_PIPE_DEF, {
get: () => {
if (ngPipeDef === null) {
const metadata = getPipeMetadata(type, meta);
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'pipe',
type: metadata.type,
});
ngPipeDef = compiler.compilePipe(
angularCoreEnv,
`ng:///${metadata.name}/ɵpipe.js`,
metadata,
);
}
return ngPipeDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
function getPipeMetadata(type: Type<any>, meta: Pipe): R3PipeMetadataFacade {
return {
type: type,
name: type.name,
pipeName: meta.name,
pure: meta.pure !== undefined ? meta.pure : true,
isStandalone: meta.standalone === undefined ? NG_STANDALONE_DEFAULT_VALUE : !!meta.standalone,
};
}
| {
"end_byte": 2453,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/pipe.ts"
} |
angular/packages/core/src/render3/jit/partial.ts_0_5385 | /**
* @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 {
FactoryTarget,
getCompilerFacade,
JitCompilerUsage,
R3DeclareComponentFacade,
R3DeclareDirectiveFacade,
R3DeclareFactoryFacade,
R3DeclareInjectableFacade,
R3DeclareInjectorFacade,
R3DeclareNgModuleFacade,
R3DeclarePipeFacade,
} from '../../compiler/compiler_facade';
import {Type} from '../../interface/type';
import {setClassMetadata, setClassMetadataAsync} from '../metadata';
import {angularCoreEnv} from './environment';
/**
* Compiles a partial directive declaration object into a full directive definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareDirective(decl: R3DeclareDirectiveFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'directive',
type: decl.type,
});
return compiler.compileDirectiveDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵfac.js`,
decl,
);
}
/**
* Evaluates the class metadata declaration.
*
* @codeGenApi
*/
export function ɵɵngDeclareClassMetadata(decl: {
type: Type<any>;
decorators: any[];
ctorParameters?: () => any[];
propDecorators?: {[field: string]: any};
}): void {
setClassMetadata(
decl.type,
decl.decorators,
decl.ctorParameters ?? null,
decl.propDecorators ?? null,
);
}
/**
* Evaluates the class metadata of a component that contains deferred blocks.
*
* @codeGenApi
*/
export function ɵɵngDeclareClassMetadataAsync(decl: {
type: Type<any>;
resolveDeferredDeps: () => Promise<Type<unknown>>[];
resolveMetadata: (...types: Type<unknown>[]) => {
decorators: any[];
ctorParameters: (() => any[]) | null;
propDecorators: {[field: string]: any} | null;
};
}): void {
setClassMetadataAsync(decl.type, decl.resolveDeferredDeps, (...types: Type<unknown>[]) => {
const meta = decl.resolveMetadata(...types);
setClassMetadata(decl.type, meta.decorators, meta.ctorParameters, meta.propDecorators);
});
}
/**
* Compiles a partial component declaration object into a full component definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareComponent(decl: R3DeclareComponentFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'component',
type: decl.type,
});
return compiler.compileComponentDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵcmp.js`,
decl,
);
}
/**
* Compiles a partial pipe declaration object into a full pipe definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareFactory(decl: R3DeclareFactoryFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: getFactoryKind(decl.target),
type: decl.type,
});
return compiler.compileFactoryDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵfac.js`,
decl,
);
}
function getFactoryKind(target: FactoryTarget) {
switch (target) {
case FactoryTarget.Directive:
return 'directive';
case FactoryTarget.Component:
return 'component';
case FactoryTarget.Injectable:
return 'injectable';
case FactoryTarget.Pipe:
return 'pipe';
case FactoryTarget.NgModule:
return 'NgModule';
}
}
/**
* Compiles a partial injectable declaration object into a full injectable definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareInjectable(decl: R3DeclareInjectableFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'injectable',
type: decl.type,
});
return compiler.compileInjectableDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵprov.js`,
decl,
);
}
/**
* These enums are used in the partial factory declaration calls.
*/
export {FactoryTarget} from '../../compiler/compiler_facade';
/**
* Compiles a partial injector declaration object into a full injector definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareInjector(decl: R3DeclareInjectorFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'NgModule',
type: decl.type,
});
return compiler.compileInjectorDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵinj.js`,
decl,
);
}
/**
* Compiles a partial NgModule declaration object into a full NgModule definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclareNgModule(decl: R3DeclareNgModuleFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'NgModule',
type: decl.type,
});
return compiler.compileNgModuleDeclaration(
angularCoreEnv,
`ng:///${decl.type.name}/ɵmod.js`,
decl,
);
}
/**
* Compiles a partial pipe declaration object into a full pipe definition object.
*
* @codeGenApi
*/
export function ɵɵngDeclarePipe(decl: R3DeclarePipeFacade): unknown {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'pipe',
type: decl.type,
});
return compiler.compilePipeDeclaration(angularCoreEnv, `ng:///${decl.type.name}/ɵpipe.js`, decl);
}
| {
"end_byte": 5385,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/partial.ts"
} |
angular/packages/core/src/render3/jit/module.ts_0_8317 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
getCompilerFacade,
JitCompilerUsage,
R3InjectorMetadataFacade,
} from '../../compiler/compiler_facade';
import {resolveForwardRef} from '../../di/forward_ref';
import {NG_INJ_DEF} from '../../di/interface/defs';
import {ModuleWithProviders} from '../../di/interface/provider';
import {reflectDependencies} from '../../di/jit/util';
import {Type} from '../../interface/type';
import {registerNgModuleType} from '../../linker/ng_module_registration';
import {Component} from '../../metadata/directives';
import {NgModule} from '../../metadata/ng_module';
import {NgModuleDef, NgModuleTransitiveScopes, NgModuleType} from '../../metadata/ng_module_def';
import {deepForEach, flatten} from '../../util/array_utils';
import {assertDefined} from '../../util/assert';
import {EMPTY_ARRAY} from '../../util/empty';
import {GENERATED_COMP_IDS} from '../definition';
import {
getComponentDef,
getDirectiveDef,
getNgModuleDef,
getPipeDef,
isStandalone,
} from '../def_getters';
import {depsTracker, USE_RUNTIME_DEPS_TRACKER_FOR_JIT} from '../deps_tracker/deps_tracker';
import {NG_COMP_DEF, NG_DIR_DEF, NG_FACTORY_DEF, NG_MOD_DEF, NG_PIPE_DEF} from '../fields';
import {ComponentDef} from '../interfaces/definition';
import {maybeUnwrapFn} from '../util/misc_utils';
import {stringifyForError} from '../util/stringify_utils';
import {angularCoreEnv} from './environment';
import {patchModuleCompilation} from './module_patch';
import {isModuleWithProviders, isNgModule} from './util';
interface ModuleQueueItem {
moduleType: Type<any>;
ngModule: NgModule;
}
const moduleQueue: ModuleQueueItem[] = [];
/**
* Enqueues moduleDef to be checked later to see if scope can be set on its
* component declarations.
*/
function enqueueModuleForDelayedScoping(moduleType: Type<any>, ngModule: NgModule) {
moduleQueue.push({moduleType, ngModule});
}
let flushingModuleQueue = false;
/**
* Loops over queued module definitions, if a given module definition has all of its
* declarations resolved, it dequeues that module definition and sets the scope on
* its declarations.
*/
export function flushModuleScopingQueueAsMuchAsPossible() {
if (!flushingModuleQueue) {
flushingModuleQueue = true;
try {
for (let i = moduleQueue.length - 1; i >= 0; i--) {
const {moduleType, ngModule} = moduleQueue[i];
if (ngModule.declarations && ngModule.declarations.every(isResolvedDeclaration)) {
// dequeue
moduleQueue.splice(i, 1);
setScopeOnDeclaredComponents(moduleType, ngModule);
}
}
} finally {
flushingModuleQueue = false;
}
}
}
/**
* Returns truthy if a declaration has resolved. If the declaration happens to be
* an array of declarations, it will recurse to check each declaration in that array
* (which may also be arrays).
*/
function isResolvedDeclaration(declaration: any[] | Type<any>): boolean {
if (Array.isArray(declaration)) {
return declaration.every(isResolvedDeclaration);
}
return !!resolveForwardRef(declaration);
}
/**
* Compiles a module in JIT mode.
*
* This function automatically gets called when a class has a `@NgModule` decorator.
*/
export function compileNgModule(moduleType: Type<any>, ngModule: NgModule = {}): void {
patchModuleCompilation();
compileNgModuleDefs(moduleType as NgModuleType, ngModule);
if (ngModule.id !== undefined) {
registerNgModuleType(moduleType as NgModuleType, ngModule.id);
}
// Because we don't know if all declarations have resolved yet at the moment the
// NgModule decorator is executing, we're enqueueing the setting of module scope
// on its declarations to be run at a later time when all declarations for the module,
// including forward refs, have resolved.
enqueueModuleForDelayedScoping(moduleType, ngModule);
}
/**
* Compiles and adds the `ɵmod`, `ɵfac` and `ɵinj` properties to the module class.
*
* It's possible to compile a module via this API which will allow duplicate declarations in its
* root.
*/
export function compileNgModuleDefs(
moduleType: NgModuleType,
ngModule: NgModule,
allowDuplicateDeclarationsInRoot: boolean = false,
): void {
ngDevMode && assertDefined(moduleType, 'Required value moduleType');
ngDevMode && assertDefined(ngModule, 'Required value ngModule');
const declarations: Type<any>[] = flatten(ngModule.declarations || EMPTY_ARRAY);
let ngModuleDef: any = null;
Object.defineProperty(moduleType, NG_MOD_DEF, {
configurable: true,
get: () => {
if (ngModuleDef === null) {
if (ngDevMode && ngModule.imports && ngModule.imports.indexOf(moduleType) > -1) {
// We need to assert this immediately, because allowing it to continue will cause it to
// go into an infinite loop before we've reached the point where we throw all the errors.
throw new Error(`'${stringifyForError(moduleType)}' module can't import itself`);
}
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'NgModule',
type: moduleType,
});
ngModuleDef = compiler.compileNgModule(angularCoreEnv, `ng:///${moduleType.name}/ɵmod.js`, {
type: moduleType,
bootstrap: flatten(ngModule.bootstrap || EMPTY_ARRAY).map(resolveForwardRef),
declarations: declarations.map(resolveForwardRef),
imports: flatten(ngModule.imports || EMPTY_ARRAY)
.map(resolveForwardRef)
.map(expandModuleWithProviders),
exports: flatten(ngModule.exports || EMPTY_ARRAY)
.map(resolveForwardRef)
.map(expandModuleWithProviders),
schemas: ngModule.schemas ? flatten(ngModule.schemas) : null,
id: ngModule.id || null,
});
// Set `schemas` on ngModuleDef to an empty array in JIT mode to indicate that runtime
// should verify that there are no unknown elements in a template. In AOT mode, that check
// happens at compile time and `schemas` information is not present on Component and Module
// defs after compilation (so the check doesn't happen the second time at runtime).
if (!ngModuleDef.schemas) {
ngModuleDef.schemas = [];
}
}
return ngModuleDef;
},
});
let ngFactoryDef: any = null;
Object.defineProperty(moduleType, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'NgModule',
type: moduleType,
});
ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${moduleType.name}/ɵfac.js`, {
name: moduleType.name,
type: moduleType,
deps: reflectDependencies(moduleType),
target: compiler.FactoryTarget.NgModule,
typeArgumentCount: 0,
});
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
let ngInjectorDef: any = null;
Object.defineProperty(moduleType, NG_INJ_DEF, {
get: () => {
if (ngInjectorDef === null) {
ngDevMode && verifySemanticsOfNgModuleDef(moduleType, allowDuplicateDeclarationsInRoot);
const meta: R3InjectorMetadataFacade = {
name: moduleType.name,
type: moduleType,
providers: ngModule.providers || EMPTY_ARRAY,
imports: [
(ngModule.imports || EMPTY_ARRAY).map(resolveForwardRef),
(ngModule.exports || EMPTY_ARRAY).map(resolveForwardRef),
],
};
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'NgModule',
type: moduleType,
});
ngInjectorDef = compiler.compileInjector(
angularCoreEnv,
`ng:///${moduleType.name}/ɵinj.js`,
meta,
);
}
return ngInjectorDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
expo | {
"end_byte": 8317,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/module.ts"
} |
angular/packages/core/src/render3/jit/module.ts_8319_16159 | function generateStandaloneInDeclarationsError(type: Type<any>, location: string) {
const prefix = `Unexpected "${stringifyForError(type)}" found in the "declarations" array of the`;
const suffix =
`"${stringifyForError(type)}" is marked as standalone and can't be declared ` +
'in any NgModule - did you intend to import it instead (by adding it to the "imports" array)?';
return `${prefix} ${location}, ${suffix}`;
}
function verifySemanticsOfNgModuleDef(
moduleType: NgModuleType,
allowDuplicateDeclarationsInRoot: boolean,
importingModule?: NgModuleType,
): void {
if (verifiedNgModule.get(moduleType)) return;
// skip verifications of standalone components, directives, and pipes
if (isStandalone(moduleType)) return;
verifiedNgModule.set(moduleType, true);
moduleType = resolveForwardRef(moduleType);
let ngModuleDef: NgModuleDef<any>;
if (importingModule) {
ngModuleDef = getNgModuleDef(moduleType)!;
if (!ngModuleDef) {
throw new Error(
`Unexpected value '${moduleType.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`,
);
}
} else {
ngModuleDef = getNgModuleDef(moduleType, true);
}
const errors: string[] = [];
const declarations = maybeUnwrapFn(ngModuleDef.declarations);
const imports = maybeUnwrapFn(ngModuleDef.imports);
flatten(imports)
.map(unwrapModuleWithProvidersImports)
.forEach((modOrStandaloneCmpt) => {
verifySemanticsOfNgModuleImport(modOrStandaloneCmpt, moduleType);
verifySemanticsOfNgModuleDef(modOrStandaloneCmpt, false, moduleType);
});
const exports = maybeUnwrapFn(ngModuleDef.exports);
declarations.forEach(verifyDeclarationsHaveDefinitions);
declarations.forEach(verifyDirectivesHaveSelector);
declarations.forEach((declarationType) => verifyNotStandalone(declarationType, moduleType));
const combinedDeclarations: Type<any>[] = [
...declarations.map(resolveForwardRef),
...flatten(imports.map(computeCombinedExports)).map(resolveForwardRef),
];
exports.forEach(verifyExportsAreDeclaredOrReExported);
declarations.forEach((decl) => verifyDeclarationIsUnique(decl, allowDuplicateDeclarationsInRoot));
const ngModule = getAnnotation<NgModule>(moduleType, 'NgModule');
if (ngModule) {
ngModule.imports &&
flatten(ngModule.imports)
.map(unwrapModuleWithProvidersImports)
.forEach((mod) => {
verifySemanticsOfNgModuleImport(mod, moduleType);
verifySemanticsOfNgModuleDef(mod, false, moduleType);
});
ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyCorrectBootstrapType);
ngModule.bootstrap && deepForEach(ngModule.bootstrap, verifyComponentIsPartOfNgModule);
}
// Throw Error if any errors were detected.
if (errors.length) {
throw new Error(errors.join('\n'));
}
////////////////////////////////////////////////////////////////////////////////////////////////
function verifyDeclarationsHaveDefinitions(type: Type<any>): void {
type = resolveForwardRef(type);
const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type);
if (!def) {
errors.push(
`Unexpected value '${stringifyForError(type)}' declared by the module '${stringifyForError(
moduleType,
)}'. Please add a @Pipe/@Directive/@Component annotation.`,
);
}
}
function verifyDirectivesHaveSelector(type: Type<any>): void {
type = resolveForwardRef(type);
const def = getDirectiveDef(type);
if (!getComponentDef(type) && def && def.selectors.length == 0) {
errors.push(`Directive ${stringifyForError(type)} has no selector, please add it!`);
}
}
function verifyNotStandalone(type: Type<any>, moduleType: NgModuleType): void {
type = resolveForwardRef(type);
const def = getComponentDef(type) || getDirectiveDef(type) || getPipeDef(type);
if (def?.standalone) {
const location = `"${stringifyForError(moduleType)}" NgModule`;
errors.push(generateStandaloneInDeclarationsError(type, location));
}
}
function verifyExportsAreDeclaredOrReExported(type: Type<any>) {
type = resolveForwardRef(type);
const kind =
(getComponentDef(type) && 'component') ||
(getDirectiveDef(type) && 'directive') ||
(getPipeDef(type) && 'pipe');
if (kind) {
// only checked if we are declared as Component, Directive, or Pipe
// Modules don't need to be declared or imported.
if (combinedDeclarations.lastIndexOf(type) === -1) {
// We are exporting something which we don't explicitly declare or import.
errors.push(
`Can't export ${kind} ${stringifyForError(type)} from ${stringifyForError(
moduleType,
)} as it was neither declared nor imported!`,
);
}
}
}
function verifyDeclarationIsUnique(type: Type<any>, suppressErrors: boolean) {
type = resolveForwardRef(type);
const existingModule = ownerNgModule.get(type);
if (existingModule && existingModule !== moduleType) {
if (!suppressErrors) {
const modules = [existingModule, moduleType].map(stringifyForError).sort();
errors.push(
`Type ${stringifyForError(type)} is part of the declarations of 2 modules: ${
modules[0]
} and ${modules[1]}! ` +
`Please consider moving ${stringifyForError(type)} to a higher module that imports ${
modules[0]
} and ${modules[1]}. ` +
`You can also create a new NgModule that exports and includes ${stringifyForError(
type,
)} then import that NgModule in ${modules[0]} and ${modules[1]}.`,
);
}
} else {
// Mark type as having owner.
ownerNgModule.set(type, moduleType);
}
}
function verifyComponentIsPartOfNgModule(type: Type<any>) {
type = resolveForwardRef(type);
const existingModule = ownerNgModule.get(type);
if (!existingModule && !isStandalone(type)) {
errors.push(
`Component ${stringifyForError(
type,
)} is not part of any NgModule or the module has not been imported into your module.`,
);
}
}
function verifyCorrectBootstrapType(type: Type<any>) {
type = resolveForwardRef(type);
if (!getComponentDef(type)) {
errors.push(`${stringifyForError(type)} cannot be used as an entry component.`);
}
if (isStandalone(type)) {
// Note: this error should be the same as the
// `NGMODULE_BOOTSTRAP_IS_STANDALONE` one in AOT compiler.
errors.push(
`The \`${stringifyForError(type)}\` class is a standalone component, which can ` +
`not be used in the \`@NgModule.bootstrap\` array. Use the \`bootstrapApplication\` ` +
`function for bootstrap instead.`,
);
}
}
function verifySemanticsOfNgModuleImport(type: Type<any>, importingModule: Type<any>) {
type = resolveForwardRef(type);
const directiveDef = getComponentDef(type) || getDirectiveDef(type);
if (directiveDef !== null && !directiveDef.standalone) {
throw new Error(
`Unexpected directive '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`,
);
}
const pipeDef = getPipeDef(type);
if (pipeDef !== null && !pipeDef.standalone) {
throw new Error(
`Unexpected pipe '${type.name}' imported by the module '${importingModule.name}'. Please add an @NgModule annotation.`,
);
}
}
}
function unwrapModuleWithProvidersImports(
typeOrWithProviders: NgModuleType<any> | {ngModule: NgModuleType<any>},
): NgModuleType<any> {
typeOrWithProviders = resolveForwardRef(typeOrWithProviders);
return (typeOrWithProviders as any).ngModule || typeOrWithProviders;
}
func | {
"end_byte": 16159,
"start_byte": 8319,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/module.ts"
} |
angular/packages/core/src/render3/jit/module.ts_16161_22568 | on getAnnotation<T>(type: any, name: string): T | null {
let annotation: T | null = null;
collect(type.__annotations__);
collect(type.decorators);
return annotation;
function collect(annotations: any[] | null) {
if (annotations) {
annotations.forEach(readAnnotation);
}
}
function readAnnotation(decorator: {
type: {prototype: {ngMetadataName: string}; args: any[]};
args: any;
}): void {
if (!annotation) {
const proto = Object.getPrototypeOf(decorator);
if (proto.ngMetadataName == name) {
annotation = decorator as any;
} else if (decorator.type) {
const proto = Object.getPrototypeOf(decorator.type);
if (proto.ngMetadataName == name) {
annotation = decorator.args[0];
}
}
}
}
}
/**
* Keep track of compiled components. This is needed because in tests we often want to compile the
* same component with more than one NgModule. This would cause an error unless we reset which
* NgModule the component belongs to. We keep the list of compiled components here so that the
* TestBed can reset it later.
*/
let ownerNgModule = new WeakMap<Type<any>, NgModuleType<any>>();
let verifiedNgModule = new WeakMap<NgModuleType<any>, boolean>();
export function resetCompiledComponents(): void {
ownerNgModule = new WeakMap<Type<any>, NgModuleType<any>>();
verifiedNgModule = new WeakMap<NgModuleType<any>, boolean>();
moduleQueue.length = 0;
GENERATED_COMP_IDS.clear();
}
/**
* Computes the combined declarations of explicit declarations, as well as declarations inherited by
* traversing the exports of imported modules.
* @param type
*/
function computeCombinedExports(type: Type<any>): Type<any>[] {
type = resolveForwardRef(type);
const ngModuleDef = getNgModuleDef(type);
// a standalone component, directive or pipe
if (ngModuleDef === null) {
return [type];
}
return flatten(
maybeUnwrapFn(ngModuleDef.exports).map((type) => {
const ngModuleDef = getNgModuleDef(type);
if (ngModuleDef) {
verifySemanticsOfNgModuleDef(type as any as NgModuleType, false);
return computeCombinedExports(type);
} else {
return type;
}
}),
);
}
/**
* Some declared components may be compiled asynchronously, and thus may not have their
* ɵcmp set yet. If this is the case, then a reference to the module is written into
* the `ngSelectorScope` property of the declared type.
*/
function setScopeOnDeclaredComponents(moduleType: Type<any>, ngModule: NgModule) {
const declarations: Type<any>[] = flatten(ngModule.declarations || EMPTY_ARRAY);
const transitiveScopes = transitiveScopesFor(moduleType);
declarations.forEach((declaration) => {
declaration = resolveForwardRef(declaration);
if (declaration.hasOwnProperty(NG_COMP_DEF)) {
// A `ɵcmp` field exists - go ahead and patch the component directly.
const component = declaration as Type<any> & {ɵcmp: ComponentDef<any>};
const componentDef = getComponentDef(component)!;
patchComponentDefWithScope(componentDef, transitiveScopes);
} else if (
!declaration.hasOwnProperty(NG_DIR_DEF) &&
!declaration.hasOwnProperty(NG_PIPE_DEF)
) {
// Set `ngSelectorScope` for future reference when the component compilation finishes.
(declaration as Type<any> & {ngSelectorScope?: any}).ngSelectorScope = moduleType;
}
});
}
/**
* Patch the definition of a component with directives and pipes from the compilation scope of
* a given module.
*/
export function patchComponentDefWithScope<C>(
componentDef: ComponentDef<C>,
transitiveScopes: NgModuleTransitiveScopes,
) {
componentDef.directiveDefs = () =>
Array.from(transitiveScopes.compilation.directives)
.map((dir) =>
dir.hasOwnProperty(NG_COMP_DEF) ? getComponentDef(dir)! : getDirectiveDef(dir)!,
)
.filter((def) => !!def);
componentDef.pipeDefs = () =>
Array.from(transitiveScopes.compilation.pipes).map((pipe) => getPipeDef(pipe)!);
componentDef.schemas = transitiveScopes.schemas;
// Since we avoid Components/Directives/Pipes recompiling in case there are no overrides, we
// may face a problem where previously compiled defs available to a given Component/Directive
// are cached in TView and may become stale (in case any of these defs gets recompiled). In
// order to avoid this problem, we force fresh TView to be created.
componentDef.tView = null;
}
/**
* Compute the pair of transitive scopes (compilation scope and exported scope) for a given type
* (either a NgModule or a standalone component / directive / pipe).
*/
export function transitiveScopesFor<T>(type: Type<T>): NgModuleTransitiveScopes {
if (isNgModule(type)) {
if (USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
const scope = depsTracker.getNgModuleScope(type);
const def = getNgModuleDef(type, true);
return {
schemas: def.schemas || null,
...scope,
};
} else {
return transitiveScopesForNgModule(type);
}
} else if (isStandalone(type)) {
const directiveDef = getComponentDef(type) || getDirectiveDef(type);
if (directiveDef !== null) {
return {
schemas: null,
compilation: {
directives: new Set<any>(),
pipes: new Set<any>(),
},
exported: {
directives: new Set<any>([type]),
pipes: new Set<any>(),
},
};
}
const pipeDef = getPipeDef(type);
if (pipeDef !== null) {
return {
schemas: null,
compilation: {
directives: new Set<any>(),
pipes: new Set<any>(),
},
exported: {
directives: new Set<any>(),
pipes: new Set<any>([type]),
},
};
}
}
// TODO: change the error message to be more user-facing and take standalone into account
throw new Error(`${type.name} does not have a module def (ɵmod property)`);
}
/**
* Compute the pair of transitive scopes (compilation scope and exported scope) for a given module.
*
* This operation is memoized and the result is cached on the module's definition. This function can
* be called on modules with components that have not fully compiled yet, but the result should not
* be used until they have.
*
* @param moduleType module that transitive scope should be calculated for.
*/
export fu | {
"end_byte": 22568,
"start_byte": 16161,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/module.ts"
} |
angular/packages/core/src/render3/jit/module.ts_22569_25461 | ction transitiveScopesForNgModule<T>(moduleType: Type<T>): NgModuleTransitiveScopes {
const def = getNgModuleDef(moduleType, true);
if (def.transitiveCompileScopes !== null) {
return def.transitiveCompileScopes;
}
const scopes: NgModuleTransitiveScopes = {
schemas: def.schemas || null,
compilation: {
directives: new Set<any>(),
pipes: new Set<any>(),
},
exported: {
directives: new Set<any>(),
pipes: new Set<any>(),
},
};
maybeUnwrapFn(def.imports).forEach(<I>(imported: Type<I>) => {
// When this module imports another, the imported module's exported directives and pipes are
// added to the compilation scope of this module.
const importedScope = transitiveScopesFor(imported);
importedScope.exported.directives.forEach((entry) => scopes.compilation.directives.add(entry));
importedScope.exported.pipes.forEach((entry) => scopes.compilation.pipes.add(entry));
});
maybeUnwrapFn(def.declarations).forEach((declared) => {
const declaredWithDefs = declared as Type<any> & {
ɵpipe?: any;
};
if (getPipeDef(declaredWithDefs)) {
scopes.compilation.pipes.add(declared);
} else {
// Either declared has a ɵcmp or ɵdir, or it's a component which hasn't
// had its template compiled yet. In either case, it gets added to the compilation's
// directives.
scopes.compilation.directives.add(declared);
}
});
maybeUnwrapFn(def.exports).forEach(<E>(exported: Type<E>) => {
const exportedType = exported as Type<E> & {
// Components, Directives, NgModules, and Pipes can all be exported.
ɵcmp?: any;
ɵdir?: any;
ɵmod?: NgModuleDef<E>;
ɵpipe?: any;
};
// Either the type is a module, a pipe, or a component/directive (which may not have a
// ɵcmp as it might be compiled asynchronously).
if (isNgModule(exportedType)) {
// When this module exports another, the exported module's exported directives and pipes are
// added to both the compilation and exported scopes of this module.
const exportedScope = transitiveScopesFor(exportedType);
exportedScope.exported.directives.forEach((entry) => {
scopes.compilation.directives.add(entry);
scopes.exported.directives.add(entry);
});
exportedScope.exported.pipes.forEach((entry) => {
scopes.compilation.pipes.add(entry);
scopes.exported.pipes.add(entry);
});
} else if (getPipeDef(exportedType)) {
scopes.exported.pipes.add(exportedType);
} else {
scopes.exported.directives.add(exportedType);
}
});
def.transitiveCompileScopes = scopes;
return scopes;
}
function expandModuleWithProviders(value: Type<any> | ModuleWithProviders<{}>): Type<any> {
if (isModuleWithProviders(value)) {
return value.ngModule;
}
return value;
}
| {
"end_byte": 25461,
"start_byte": 22569,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/module.ts"
} |
angular/packages/core/src/render3/jit/directive.ts_0_3222 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
getCompilerFacade,
JitCompilerUsage,
R3DirectiveMetadataFacade,
} from '../../compiler/compiler_facade';
import {
R3ComponentMetadataFacade,
R3QueryMetadataFacade,
} from '../../compiler/compiler_facade_interface';
import {resolveForwardRef} from '../../di/forward_ref';
import {getReflect, reflectDependencies} from '../../di/jit/util';
import {Type} from '../../interface/type';
import {Query} from '../../metadata/di';
import {Component, Directive, Input} from '../../metadata/directives';
import {
componentNeedsResolution,
maybeQueueResolutionOfComponentResources,
} from '../../metadata/resource_loading';
import {ViewEncapsulation} from '../../metadata/view';
import {flatten} from '../../util/array_utils';
import {EMPTY_ARRAY, EMPTY_OBJ} from '../../util/empty';
import {initNgDevMode} from '../../util/ng_dev_mode';
import {getComponentDef, getDirectiveDef, getNgModuleDef, getPipeDef} from '../def_getters';
import {depsTracker, USE_RUNTIME_DEPS_TRACKER_FOR_JIT} from '../deps_tracker/deps_tracker';
import {NG_COMP_DEF, NG_DIR_DEF, NG_FACTORY_DEF} from '../fields';
import {ComponentDef, ComponentType, DirectiveDefList, PipeDefList} from '../interfaces/definition';
import {stringifyForError} from '../util/stringify_utils';
import {angularCoreEnv} from './environment';
import {getJitOptions} from './jit_options';
import {
flushModuleScopingQueueAsMuchAsPossible,
patchComponentDefWithScope,
transitiveScopesFor,
} from './module';
import {NG_STANDALONE_DEFAULT_VALUE} from '../standalone-default-value';
import {isComponent, verifyStandaloneImport} from './util';
/**
* Keep track of the compilation depth to avoid reentrancy issues during JIT compilation. This
* matters in the following scenario:
*
* Consider a component 'A' that extends component 'B', both declared in module 'M'. During
* the compilation of 'A' the definition of 'B' is requested to capture the inheritance chain,
* potentially triggering compilation of 'B'. If this nested compilation were to trigger
* `flushModuleScopingQueueAsMuchAsPossible` it may happen that module 'M' is still pending in the
* queue, resulting in 'A' and 'B' to be patched with the NgModule scope. As the compilation of
* 'A' is still in progress, this would introduce a circular dependency on its compilation. To avoid
* this issue, the module scope queue is only flushed for compilations at the depth 0, to ensure
* all compilations have finished.
*/
let compilationDepth = 0;
/**
* Compile an Angular component according to its decorator metadata, and patch the resulting
* component def (ɵcmp) onto the component type.
*
* Compilation may be asynchronous (due to the need to resolve URLs for the component template or
* other resources, for example). In the event that compilation is not immediate, `compileComponent`
* will enqueue resource resolution into a global queue and will fail to return the `ɵcmp`
* until the global queue has been resolved with a call to `resolveComponentResources`.
*/
e | {
"end_byte": 3222,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/directive.ts"
} |
angular/packages/core/src/render3/jit/directive.ts_3223_10359 | port function compileComponent(type: Type<any>, metadata: Component): void {
// Initialize ngDevMode. This must be the first statement in compileComponent.
// See the `initNgDevMode` docstring for more information.
(typeof ngDevMode === 'undefined' || ngDevMode) && initNgDevMode();
let ngComponentDef: ComponentDef<unknown> | null = null;
// Metadata may have resources which need to be resolved.
maybeQueueResolutionOfComponentResources(type, metadata);
// Note that we're using the same function as `Directive`, because that's only subset of metadata
// that we need to create the ngFactoryDef. We're avoiding using the component metadata
// because we'd have to resolve the asynchronous templates.
addDirectiveFactoryDef(type, metadata);
Object.defineProperty(type, NG_COMP_DEF, {
get: () => {
if (ngComponentDef === null) {
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'component',
type: type,
});
if (componentNeedsResolution(metadata)) {
const error = [`Component '${type.name}' is not resolved:`];
if (metadata.templateUrl) {
error.push(` - templateUrl: ${metadata.templateUrl}`);
}
if (metadata.styleUrls && metadata.styleUrls.length) {
error.push(` - styleUrls: ${JSON.stringify(metadata.styleUrls)}`);
}
if (metadata.styleUrl) {
error.push(` - styleUrl: ${metadata.styleUrl}`);
}
error.push(`Did you run and wait for 'resolveComponentResources()'?`);
throw new Error(error.join('\n'));
}
// This const was called `jitOptions` previously but had to be renamed to `options` because
// of a bug with Terser that caused optimized JIT builds to throw a `ReferenceError`.
// This bug was investigated in https://github.com/angular/angular-cli/issues/17264.
// We should not rename it back until https://github.com/terser/terser/issues/615 is fixed.
const options = getJitOptions();
let preserveWhitespaces = metadata.preserveWhitespaces;
if (preserveWhitespaces === undefined) {
if (options !== null && options.preserveWhitespaces !== undefined) {
preserveWhitespaces = options.preserveWhitespaces;
} else {
preserveWhitespaces = false;
}
}
let encapsulation = metadata.encapsulation;
if (encapsulation === undefined) {
if (options !== null && options.defaultEncapsulation !== undefined) {
encapsulation = options.defaultEncapsulation;
} else {
encapsulation = ViewEncapsulation.Emulated;
}
}
const templateUrl = metadata.templateUrl || `ng:///${type.name}/template.html`;
const meta: R3ComponentMetadataFacade = {
...directiveMetadata(type, metadata),
typeSourceSpan: compiler.createParseSourceSpan('Component', type.name, templateUrl),
template: metadata.template || '',
preserveWhitespaces,
styles:
typeof metadata.styles === 'string'
? [metadata.styles]
: metadata.styles || EMPTY_ARRAY,
animations: metadata.animations,
// JIT components are always compiled against an empty set of `declarations`. Instead, the
// `directiveDefs` and `pipeDefs` are updated at a later point:
// * for NgModule-based components, they're set when the NgModule which declares the
// component resolves in the module scoping queue
// * for standalone components, they're set just below, after `compileComponent`.
declarations: [],
changeDetection: metadata.changeDetection,
encapsulation,
interpolation: metadata.interpolation,
viewProviders: metadata.viewProviders || null,
};
compilationDepth++;
try {
if (meta.usesInheritance) {
addDirectiveDefToUndecoratedParents(type);
}
ngComponentDef = compiler.compileComponent(
angularCoreEnv,
templateUrl,
meta,
) as ComponentDef<unknown>;
if (meta.isStandalone) {
// Patch the component definition for standalone components with `directiveDefs` and
// `pipeDefs` functions which lazily compute the directives/pipes available in the
// standalone component. Also set `dependencies` to the lazily resolved list of imports.
const imports: Type<any>[] = flatten(metadata.imports || EMPTY_ARRAY);
const {directiveDefs, pipeDefs} = getStandaloneDefFunctions(type, imports);
ngComponentDef.directiveDefs = directiveDefs;
ngComponentDef.pipeDefs = pipeDefs;
ngComponentDef.dependencies = () => imports.map(resolveForwardRef);
}
} finally {
// Ensure that the compilation depth is decremented even when the compilation failed.
compilationDepth--;
}
if (compilationDepth === 0) {
// When NgModule decorator executed, we enqueued the module definition such that
// it would only dequeue and add itself as module scope to all of its declarations,
// but only if if all of its declarations had resolved. This call runs the check
// to see if any modules that are in the queue can be dequeued and add scope to
// their declarations.
flushModuleScopingQueueAsMuchAsPossible();
}
// If component compilation is async, then the @NgModule annotation which declares the
// component may execute and set an ngSelectorScope property on the component type. This
// allows the component to patch itself with directiveDefs from the module after it
// finishes compiling.
if (hasSelectorScope(type)) {
const scopes = transitiveScopesFor(type.ngSelectorScope);
patchComponentDefWithScope(ngComponentDef, scopes);
}
if (metadata.schemas) {
if (meta.isStandalone) {
ngComponentDef.schemas = metadata.schemas;
} else {
throw new Error(
`The 'schemas' was specified for the ${stringifyForError(
type,
)} but is only valid on a component that is standalone.`,
);
}
} else if (meta.isStandalone) {
ngComponentDef.schemas = [];
}
}
return ngComponentDef;
},
set: (def: ComponentDef<unknown> | null) => {
ngComponentDef = def;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
/**
* Build memoized `directiveDefs` and `pipeDefs` functions for the component definition of a
* standalone component, which process `imports` and filter out directives and pipes. The use of
* memoized functions here allows for the delayed resolution of any `forwardRef`s present in the
* component's `imports`.
*/
f | {
"end_byte": 10359,
"start_byte": 3223,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/directive.ts"
} |
angular/packages/core/src/render3/jit/directive.ts_10360_19009 | nction getStandaloneDefFunctions(
type: Type<any>,
imports: Type<any>[],
): {
directiveDefs: () => DirectiveDefList;
pipeDefs: () => PipeDefList;
} {
let cachedDirectiveDefs: DirectiveDefList | null = null;
let cachedPipeDefs: PipeDefList | null = null;
const directiveDefs = () => {
if (!USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
if (cachedDirectiveDefs === null) {
// Standalone components are always able to self-reference, so include the component's own
// definition in its `directiveDefs`.
cachedDirectiveDefs = [getComponentDef(type)!];
const seen = new Set<Type<unknown>>([type]);
for (const rawDep of imports) {
ngDevMode && verifyStandaloneImport(rawDep, type);
const dep = resolveForwardRef(rawDep);
if (seen.has(dep)) {
continue;
}
seen.add(dep);
if (!!getNgModuleDef(dep)) {
const scope = transitiveScopesFor(dep);
for (const dir of scope.exported.directives) {
const def = getComponentDef(dir) || getDirectiveDef(dir);
if (def && !seen.has(dir)) {
seen.add(dir);
cachedDirectiveDefs.push(def);
}
}
} else {
const def = getComponentDef(dep) || getDirectiveDef(dep);
if (def) {
cachedDirectiveDefs.push(def);
}
}
}
}
return cachedDirectiveDefs;
} else {
if (ngDevMode) {
for (const rawDep of imports) {
verifyStandaloneImport(rawDep, type);
}
}
if (!isComponent(type)) {
return [];
}
const scope = depsTracker.getStandaloneComponentScope(type, imports);
return [...scope.compilation.directives]
.map((p) => (getComponentDef(p) || getDirectiveDef(p))!)
.filter((d) => d !== null);
}
};
const pipeDefs = () => {
if (!USE_RUNTIME_DEPS_TRACKER_FOR_JIT) {
if (cachedPipeDefs === null) {
cachedPipeDefs = [];
const seen = new Set<Type<unknown>>();
for (const rawDep of imports) {
const dep = resolveForwardRef(rawDep);
if (seen.has(dep)) {
continue;
}
seen.add(dep);
if (!!getNgModuleDef(dep)) {
const scope = transitiveScopesFor(dep);
for (const pipe of scope.exported.pipes) {
const def = getPipeDef(pipe);
if (def && !seen.has(pipe)) {
seen.add(pipe);
cachedPipeDefs.push(def);
}
}
} else {
const def = getPipeDef(dep);
if (def) {
cachedPipeDefs.push(def);
}
}
}
}
return cachedPipeDefs;
} else {
if (ngDevMode) {
for (const rawDep of imports) {
verifyStandaloneImport(rawDep, type);
}
}
if (!isComponent(type)) {
return [];
}
const scope = depsTracker.getStandaloneComponentScope(type, imports);
return [...scope.compilation.pipes].map((p) => getPipeDef(p)!).filter((d) => d !== null);
}
};
return {
directiveDefs,
pipeDefs,
};
}
function hasSelectorScope<T>(
component: Type<T>,
): component is Type<T> & {ngSelectorScope: Type<any>} {
return (component as {ngSelectorScope?: any}).ngSelectorScope !== undefined;
}
/**
* Compile an Angular directive according to its decorator metadata, and patch the resulting
* directive def onto the component type.
*
* In the event that compilation is not immediate, `compileDirective` will return a `Promise` which
* will resolve when compilation completes and the directive becomes usable.
*/
export function compileDirective(type: Type<any>, directive: Directive | null): void {
let ngDirectiveDef: any = null;
addDirectiveFactoryDef(type, directive || {});
Object.defineProperty(type, NG_DIR_DEF, {
get: () => {
if (ngDirectiveDef === null) {
// `directive` can be null in the case of abstract directives as a base class
// that use `@Directive()` with no selector. In that case, pass empty object to the
// `directiveMetadata` function instead of null.
const meta = getDirectiveMetadata(type, directive || {});
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'directive',
type,
});
ngDirectiveDef = compiler.compileDirective(
angularCoreEnv,
meta.sourceMapUrl,
meta.metadata,
);
}
return ngDirectiveDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
function getDirectiveMetadata(type: Type<any>, metadata: Directive) {
const name = type && type.name;
const sourceMapUrl = `ng:///${name}/ɵdir.js`;
const compiler = getCompilerFacade({usage: JitCompilerUsage.Decorator, kind: 'directive', type});
const facade = directiveMetadata(type as ComponentType<any>, metadata);
facade.typeSourceSpan = compiler.createParseSourceSpan('Directive', name, sourceMapUrl);
if (facade.usesInheritance) {
addDirectiveDefToUndecoratedParents(type);
}
return {metadata: facade, sourceMapUrl};
}
function addDirectiveFactoryDef(type: Type<any>, metadata: Directive | Component) {
let ngFactoryDef: any = null;
Object.defineProperty(type, NG_FACTORY_DEF, {
get: () => {
if (ngFactoryDef === null) {
const meta = getDirectiveMetadata(type, metadata);
const compiler = getCompilerFacade({
usage: JitCompilerUsage.Decorator,
kind: 'directive',
type,
});
ngFactoryDef = compiler.compileFactory(angularCoreEnv, `ng:///${type.name}/ɵfac.js`, {
name: meta.metadata.name,
type: meta.metadata.type,
typeArgumentCount: 0,
deps: reflectDependencies(type),
target: compiler.FactoryTarget.Directive,
});
}
return ngFactoryDef;
},
// Make the property configurable in dev mode to allow overriding in tests
configurable: !!ngDevMode,
});
}
export function extendsDirectlyFromObject(type: Type<any>): boolean {
return Object.getPrototypeOf(type.prototype) === Object.prototype;
}
/**
* Extract the `R3DirectiveMetadata` for a particular directive (either a `Directive` or a
* `Component`).
*/
export function directiveMetadata(type: Type<any>, metadata: Directive): R3DirectiveMetadataFacade {
// Reflect inputs and outputs.
const reflect = getReflect();
const propMetadata = reflect.ownPropMetadata(type);
return {
name: type.name,
type: type,
selector: metadata.selector !== undefined ? metadata.selector : null,
host: metadata.host || EMPTY_OBJ,
propMetadata: propMetadata,
inputs: metadata.inputs || EMPTY_ARRAY,
outputs: metadata.outputs || EMPTY_ARRAY,
queries: extractQueriesMetadata(type, propMetadata, isContentQuery),
lifecycle: {usesOnChanges: reflect.hasLifecycleHook(type, 'ngOnChanges')},
typeSourceSpan: null!,
usesInheritance: !extendsDirectlyFromObject(type),
exportAs: extractExportAs(metadata.exportAs),
providers: metadata.providers || null,
viewQueries: extractQueriesMetadata(type, propMetadata, isViewQuery),
isStandalone:
metadata.standalone === undefined ? NG_STANDALONE_DEFAULT_VALUE : !!metadata.standalone,
isSignal: !!metadata.signals,
hostDirectives:
metadata.hostDirectives?.map((directive) =>
typeof directive === 'function' ? {directive} : directive,
) || null,
};
}
/**
* Adds a directive definition to all parent classes of a type that don't have an Angular decorator.
*/
function addDirectiveDefToUndecoratedParents(type: Type<any>) {
const objPrototype = Object.prototype;
let parent = Object.getPrototypeOf(type.prototype).constructor;
// Go up the prototype until we hit `Object`.
while (parent && parent !== objPrototype) {
// Since inheritance works if the class was annotated already, we only need to add
// the def if there are no annotations and the def hasn't been created already.
if (
!getDirectiveDef(parent) &&
!getComponentDef(parent) &&
shouldAddAbstractDirective(parent)
) {
compileDirective(parent, null);
}
parent = Object.getPrototypeOf(parent);
}
}
function convertToR3QueryPredicate(selector: any): any | string[] {
return typeof selector === 'string' ? splitByComma(selector) : resolveForwardRef(selector);
}
ex | {
"end_byte": 19009,
"start_byte": 10360,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/directive.ts"
} |
angular/packages/core/src/render3/jit/directive.ts_19011_21996 | rt function convertToR3QueryMetadata(propertyName: string, ann: Query): R3QueryMetadataFacade {
return {
propertyName: propertyName,
predicate: convertToR3QueryPredicate(ann.selector),
descendants: ann.descendants,
first: ann.first,
read: ann.read ? ann.read : null,
static: !!ann.static,
emitDistinctChangesOnly: !!ann.emitDistinctChangesOnly,
isSignal: !!ann.isSignal,
};
}
function extractQueriesMetadata(
type: Type<any>,
propMetadata: {[key: string]: any[]},
isQueryAnn: (ann: any) => ann is Query,
): R3QueryMetadataFacade[] {
const queriesMeta: R3QueryMetadataFacade[] = [];
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
const annotations = propMetadata[field];
annotations.forEach((ann) => {
if (isQueryAnn(ann)) {
if (!ann.selector) {
throw new Error(
`Can't construct a query for the property "${field}" of ` +
`"${stringifyForError(type)}" since the query selector wasn't defined.`,
);
}
if (annotations.some(isInputAnnotation)) {
throw new Error(`Cannot combine @Input decorators with query decorators`);
}
queriesMeta.push(convertToR3QueryMetadata(field, ann));
}
});
}
}
return queriesMeta;
}
function extractExportAs(exportAs: string | undefined): string[] | null {
return exportAs === undefined ? null : splitByComma(exportAs);
}
function isContentQuery(value: any): value is Query {
const name = value.ngMetadataName;
return name === 'ContentChild' || name === 'ContentChildren';
}
function isViewQuery(value: any): value is Query {
const name = value.ngMetadataName;
return name === 'ViewChild' || name === 'ViewChildren';
}
function isInputAnnotation(value: any): value is Input {
return value.ngMetadataName === 'Input';
}
function splitByComma(value: string): string[] {
return value.split(',').map((piece) => piece.trim());
}
const LIFECYCLE_HOOKS = [
'ngOnChanges',
'ngOnInit',
'ngOnDestroy',
'ngDoCheck',
'ngAfterViewInit',
'ngAfterViewChecked',
'ngAfterContentInit',
'ngAfterContentChecked',
];
function shouldAddAbstractDirective(type: Type<any>): boolean {
const reflect = getReflect();
if (LIFECYCLE_HOOKS.some((hookName) => reflect.hasLifecycleHook(type, hookName))) {
return true;
}
const propMetadata = reflect.propMetadata(type);
for (const field in propMetadata) {
const annotations = propMetadata[field];
for (let i = 0; i < annotations.length; i++) {
const current = annotations[i];
const metadataName = current.ngMetadataName;
if (
isInputAnnotation(current) ||
isContentQuery(current) ||
isViewQuery(current) ||
metadataName === 'Output' ||
metadataName === 'HostBinding' ||
metadataName === 'HostListener'
) {
return true;
}
}
}
return false;
}
| {
"end_byte": 21996,
"start_byte": 19011,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/directive.ts"
} |
angular/packages/core/src/render3/jit/environment.ts_0_938 | /**
* @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 {forwardRef, resolveForwardRef} from '../../di/forward_ref';
import {ɵɵinject, ɵɵinvalidFactoryDep} from '../../di/injector_compatibility';
import {ɵɵdefineInjectable, ɵɵdefineInjector} from '../../di/interface/defs';
import {registerNgModuleType} from '../../linker/ng_module_registration';
import * as iframe_attrs_validation from '../../sanitization/iframe_attrs_validation';
import * as sanitization from '../../sanitization/sanitization';
import * as r3 from '../index';
/**
* A mapping of the @angular/core API surface used in generated expressions to the actual symbols.
*
* This should be kept up to date with the public exports of @angular/core.
*/
export const angularCoreEnv: {[name: string]: unknown} = (() => | {
"end_byte": 938,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/environment.ts"
} |
angular/packages/core/src/render3/jit/environment.ts_939_6237 | {
'ɵɵattribute': r3.ɵɵattribute,
'ɵɵattributeInterpolate1': r3.ɵɵattributeInterpolate1,
'ɵɵ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': r3.ɵɵdefineComponent,
'ɵɵdefineDirective': r3.ɵɵdefineDirective,
'ɵɵdefineInjectable': ɵɵdefineInjectable,
'ɵɵdefineInjector': ɵɵdefineInjector,
'ɵɵdefineNgModule': r3.ɵɵdefineNgModule,
'ɵɵdefinePipe': r3.ɵɵdefinePipe,
'ɵɵdirectiveInject': r3.ɵɵdirectiveInject,
'ɵɵgetInheritedFactory': r3.ɵɵgetInheritedFactory,
'ɵɵinject': ɵɵinject,
'ɵɵinjectAttribute': r3.ɵɵinjectAttribute,
'ɵɵinvalidFactory': r3.ɵɵinvalidFactory,
'ɵɵinvalidFactoryDep': ɵɵinvalidFactoryDep,
'ɵɵtemplateRefExtractor': r3.ɵɵtemplateRefExtractor,
'ɵɵresetView': r3.ɵɵresetView,
'ɵɵHostDirectivesFeature': r3.ɵɵHostDirectivesFeature,
'ɵɵNgOnChangesFeature': r3.ɵɵNgOnChangesFeature,
'ɵɵProvidersFeature': r3.ɵɵProvidersFeature,
'ɵɵCopyDefinitionFeature': r3.ɵɵCopyDefinitionFeature,
'ɵɵInheritDefinitionFeature': r3.ɵɵInheritDefinitionFeature,
'ɵɵInputTransformsFeature': r3.ɵɵInputTransformsFeature,
'ɵɵExternalStylesFeature': r3.ɵɵExternalStylesFeature,
'ɵɵnextContext': r3.ɵɵnextContext,
'ɵɵnamespaceHTML': r3.ɵɵnamespaceHTML,
'ɵɵnamespaceMathML': r3.ɵɵnamespaceMathML,
'ɵɵnamespaceSVG': r3.ɵɵnamespaceSVG,
'ɵɵenableBindings': r3.ɵɵenableBindings,
'ɵɵdisableBindings': r3.ɵɵdisableBindings,
'ɵɵelementStart': r3.ɵɵelementStart,
'ɵɵelementEnd': r3.ɵɵelementEnd,
'ɵɵelement': r3.ɵɵelement,
'ɵɵelementContainerStart': r3.ɵɵelementContainerStart,
'ɵɵelementContainerEnd': r3.ɵɵelementContainerEnd,
'ɵɵelementContainer': r3.ɵɵelementContainer,
'ɵɵpureFunction0': r3.ɵɵpureFunction0,
'ɵɵpureFunction1': r3.ɵɵpureFunction1,
'ɵɵpureFunction2': r3.ɵɵpureFunction2,
'ɵɵpureFunction3': r3.ɵɵpureFunction3,
'ɵɵpureFunction4': r3.ɵɵpureFunction4,
'ɵɵpureFunction5': r3.ɵɵpureFunction5,
'ɵɵpureFunction6': r3.ɵɵpureFunction6,
'ɵɵpureFunction7': r3.ɵɵpureFunction7,
'ɵɵpureFunction8': r3.ɵɵpureFunction8,
'ɵɵpureFunctionV': r3.ɵɵpureFunctionV,
'ɵɵgetCurrentView': r3.ɵɵgetCurrentView,
'ɵɵrestoreView': r3.ɵɵrestoreView,
'ɵɵlistener': r3.ɵɵlistener,
'ɵɵprojection': r3.ɵɵprojection,
'ɵɵsyntheticHostProperty': r3.ɵɵsyntheticHostProperty,
'ɵɵsyntheticHostListener': r3.ɵɵsyntheticHostListener,
'ɵɵpipeBind1': r3.ɵɵpipeBind1,
'ɵɵpipeBind2': r3.ɵɵpipeBind2,
'ɵɵpipeBind3': r3.ɵɵpipeBind3,
'ɵɵpipeBind4': r3.ɵɵpipeBind4,
'ɵɵpipeBindV': r3.ɵɵ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': r3.ɵɵ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.ɵɵstylePropInterpolate | {
"end_byte": 6237,
"start_byte": 939,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/environment.ts"
} |
angular/packages/core/src/render3/jit/environment.ts_6240_10792 | 'ɵɵstylePropInterpolate7': r3.ɵɵstylePropInterpolate7,
'ɵɵstylePropInterpolate8': r3.ɵɵstylePropInterpolate8,
'ɵɵstylePropInterpolateV': r3.ɵɵstylePropInterpolateV,
'ɵɵclassProp': r3.ɵɵclassProp,
'ɵɵadvance': r3.ɵɵ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': r3.ɵɵresolveWindow,
'ɵɵresolveDocument': r3.ɵɵresolveDocument,
'ɵɵresolveBody': r3.ɵɵresolveBody,
'ɵɵsetComponentScope': r3.ɵɵsetComponentScope,
'ɵɵsetNgModuleScope': r3.ɵɵsetNgModuleScope,
'ɵɵregisterNgModuleType': registerNgModuleType,
'ɵɵgetComponentDepsFactory': r3.ɵɵgetComponentDepsFactory,
'ɵsetClassDebugInfo': r3.ɵ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,
'ɵɵreplaceMetadata': r3.ɵɵreplaceMetadata,
}))();
| {
"end_byte": 10792,
"start_byte": 6240,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/environment.ts"
} |
angular/packages/core/src/render3/jit/util.ts_0_3265 | /**
* @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 {ModuleWithProviders} from '../../di/interface/provider';
import {Type} from '../../interface/type';
import {NgModuleDef} from '../../metadata/ng_module_def';
import {getComponentDef, getDirectiveDef, getPipeDef, getNgModuleDef} from '../def_getters';
import type {ComponentType, DirectiveType, PipeType} from '../interfaces/definition';
import {stringifyForError} from '../util/stringify_utils';
export function isModuleWithProviders(value: any): value is ModuleWithProviders<{}> {
return (value as {ngModule?: any}).ngModule !== undefined;
}
export function isNgModule<T>(value: Type<T>): value is Type<T> & {ɵmod: NgModuleDef<T>} {
return !!getNgModuleDef(value);
}
export function isPipe<T>(value: Type<T>): value is PipeType<T> {
return !!getPipeDef(value);
}
export function isDirective<T>(value: Type<T>): value is DirectiveType<T> {
return !!getDirectiveDef(value);
}
export function isComponent<T>(value: Type<T>): value is ComponentType<T> {
return !!getComponentDef(value);
}
function getDependencyTypeForError(type: Type<any>) {
if (getComponentDef(type)) return 'component';
if (getDirectiveDef(type)) return 'directive';
if (getPipeDef(type)) return 'pipe';
return 'type';
}
export function verifyStandaloneImport(depType: Type<unknown>, importingType: Type<unknown>) {
if (isForwardRef(depType)) {
depType = resolveForwardRef(depType);
if (!depType) {
throw new Error(
`Expected forwardRef function, imported from "${stringifyForError(
importingType,
)}", to return a standalone entity or NgModule but got "${
stringifyForError(depType) || depType
}".`,
);
}
}
if (getNgModuleDef(depType) == null) {
const def = getComponentDef(depType) || getDirectiveDef(depType) || getPipeDef(depType);
if (def != null) {
// if a component, directive or pipe is imported make sure that it is standalone
if (!def.standalone) {
throw new Error(
`The "${stringifyForError(depType)}" ${getDependencyTypeForError(
depType,
)}, imported from "${stringifyForError(
importingType,
)}", is not standalone. Did you forget to add the standalone: true flag?`,
);
}
} else {
// it can be either a module with provider or an unknown (not annotated) type
if (isModuleWithProviders(depType)) {
throw new Error(
`A module with providers was imported from "${stringifyForError(
importingType,
)}". Modules with providers are not supported in standalone components imports.`,
);
} else {
throw new Error(
`The "${stringifyForError(depType)}" type, imported from "${stringifyForError(
importingType,
)}", must be a standalone component / directive / pipe or an NgModule. Did you forget to add the required @Component / @Directive / @Pipe or @NgModule annotation?`,
);
}
}
}
}
| {
"end_byte": 3265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/util.ts"
} |
angular/packages/core/src/render3/jit/module_patch.ts_0_311 | /**
* @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 function patchModuleCompilation(): void {
// Does nothing, but exists as a target for patching.
}
| {
"end_byte": 311,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/jit/module_patch.ts"
} |
angular/packages/core/src/render3/reactivity/effect.ts_0_7655 | /**
* @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,
SIGNAL,
consumerAfterComputation,
consumerBeforeComputation,
consumerDestroy,
consumerPollProducersForChange,
isInNotificationPhase,
} from '@angular/core/primitives/signals';
import {FLAGS, LViewFlags, LView, EFFECTS} from '../interfaces/view';
import {markAncestorsForTraversal} from '../util/view_utils';
import {InjectionToken} from '../../di/injection_token';
import {inject} from '../../di/injector_compatibility';
import {performanceMarkFeature} from '../../util/performance';
import {Injector} from '../../di/injector';
import {assertNotInReactiveContext} from './asserts';
import {assertInInjectionContext} from '../../di/contextual';
import {DestroyRef, NodeInjectorDestroyRef} from '../../linker/destroy_ref';
import {ViewContext} from '../view_context';
import {noop} from '../../util/noop';
import {ErrorHandler} from '../../error_handler';
import {
ChangeDetectionScheduler,
NotificationSource,
} from '../../change_detection/scheduling/zoneless_scheduling';
import {setIsRefreshingViews} from '../state';
import {EffectScheduler, SchedulableEffect} from './root_effect_scheduler';
import {USE_MICROTASK_EFFECT_BY_DEFAULT} from './patch';
import {microtaskEffect} from './microtask_effect';
let useMicrotaskEffectsByDefault = USE_MICROTASK_EFFECT_BY_DEFAULT;
/**
* Toggle the flag on whether to use microtask effects (for testing).
*/
export function setUseMicrotaskEffectsByDefault(value: boolean): boolean {
const prev = useMicrotaskEffectsByDefault;
useMicrotaskEffectsByDefault = value;
return prev;
}
/**
* A global reactive effect, which can be manually destroyed.
*
* @developerPreview
*/
export interface EffectRef {
/**
* Shut down the effect, removing it from any upcoming scheduled executions.
*/
destroy(): void;
}
class EffectRefImpl implements EffectRef {
[SIGNAL]: EffectNode;
constructor(node: EffectNode) {
this[SIGNAL] = node;
}
destroy(): void {
this[SIGNAL].destroy();
}
}
/**
* Options passed to the `effect` function.
*
* @developerPreview
*/
export interface CreateEffectOptions {
/**
* The `Injector` in which to create the effect.
*
* If this is not provided, the current [injection context](guide/di/dependency-injection-context)
* will be used instead (via `inject`).
*/
injector?: Injector;
/**
* Whether the `effect` should require manual cleanup.
*
* If this is `false` (the default) the effect will automatically register itself to be cleaned up
* with the current `DestroyRef`.
*/
manualCleanup?: boolean;
/**
* Always create a root effect (which is scheduled as a microtask) regardless of whether `effect`
* is called within a component.
*/
forceRoot?: true;
/**
* @deprecated no longer required, signal writes are allowed by default.
*/
allowSignalWrites?: boolean;
/**
* A debug name for the effect. Used in Angular DevTools to identify the effect.
*/
debugName?: string;
}
/**
* An effect can, optionally, register a cleanup function. If registered, the cleanup is executed
* before the next effect run. The cleanup function makes it possible to "cancel" any work that the
* previous effect run might have started.
*
* @developerPreview
*/
export type EffectCleanupFn = () => void;
/**
* A callback passed to the effect function that makes it possible to register cleanup logic.
*
* @developerPreview
*/
export type EffectCleanupRegisterFn = (cleanupFn: EffectCleanupFn) => void;
/**
* Registers an "effect" that will be scheduled & executed whenever the signals that it reads
* changes.
*
* Angular has two different kinds of effect: component effects and root effects. Component effects
* are created when `effect()` is called from a component, directive, or within a service of a
* component/directive. Root effects are created when `effect()` is called from outside the
* component tree, such as in a root service, or when the `forceRoot` option is provided.
*
* The two effect types differ in their timing. Component effects run as a component lifecycle
* event during Angular's synchronization (change detection) process, and can safely read input
* signals or create/destroy views that depend on component state. Root effects run as microtasks
* and have no connection to the component tree or change detection.
*
* `effect()` must be run in injection context, unless the `injector` option is manually specified.
*
* @developerPreview
*/
export function effect(
effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
options?: CreateEffectOptions,
): EffectRef {
if (useMicrotaskEffectsByDefault) {
if (ngDevMode && options?.forceRoot) {
throw new Error(`Cannot use 'forceRoot' option with microtask effects on`);
}
return microtaskEffect(effectFn, options);
}
performanceMarkFeature('NgSignals');
ngDevMode &&
assertNotInReactiveContext(
effect,
'Call `effect` outside of a reactive context. For example, schedule the ' +
'effect inside the component constructor.',
);
!options?.injector && assertInInjectionContext(effect);
if (ngDevMode && options?.allowSignalWrites !== undefined) {
console.warn(
`The 'allowSignalWrites' flag is deprecated & longer required for effect() (writes are allowed by default)`,
);
}
const injector = options?.injector ?? inject(Injector);
let destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
let node: EffectNode;
const viewContext = injector.get(ViewContext, null, {optional: true});
const notifier = injector.get(ChangeDetectionScheduler);
if (viewContext !== null && !options?.forceRoot) {
// This effect was created in the context of a view, and will be associated with the view.
node = createViewEffect(viewContext.view, notifier, effectFn);
if (destroyRef instanceof NodeInjectorDestroyRef && destroyRef._lView === viewContext.view) {
// The effect is being created in the same view as the `DestroyRef` references, so it will be
// automatically destroyed without the need for an explicit `DestroyRef` registration.
destroyRef = null;
}
} else {
// This effect was created outside the context of a view, and will be scheduled independently.
node = createRootEffect(effectFn, injector.get(EffectScheduler), notifier);
}
node.injector = injector;
if (destroyRef !== null) {
// If we need to register for cleanup, do that here.
node.onDestroyFn = destroyRef.onDestroy(() => node.destroy());
}
if (ngDevMode) {
node.debugName = options?.debugName ?? '';
}
return new EffectRefImpl(node);
}
export interface EffectNode extends ReactiveNode, SchedulableEffect {
hasRun: boolean;
cleanupFns: EffectCleanupFn[] | undefined;
injector: Injector;
notifier: ChangeDetectionScheduler;
onDestroyFn: () => void;
fn: (cleanupFn: EffectCleanupRegisterFn) => void;
run(): void;
destroy(): void;
maybeCleanup(): void;
}
export interface ViewEffectNode extends EffectNode {
view: LView;
}
export interface RootEffectNode extends EffectNode {
scheduler: EffectScheduler;
}
/**
* Not public API, which guarantees `EffectScheduler` only ever comes from the application root
* injector.
*/
export const APP_EFFECT_SCHEDULER = /* @__PURE__ */ new InjectionToken('', {
providedIn: 'root',
factory: () => inject(EffectScheduler),
}); | {
"end_byte": 7655,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/effect.ts"
} |
angular/packages/core/src/render3/reactivity/effect.ts_7657_11412 | export const BASE_EFFECT_NODE: Omit<EffectNode, 'fn' | 'destroy' | 'injector' | 'notifier'> =
/* @__PURE__ */ (() => ({
...REACTIVE_NODE,
consumerIsAlwaysLive: true,
consumerAllowSignalWrites: true,
dirty: true,
hasRun: false,
cleanupFns: undefined,
zone: null,
onDestroyFn: noop,
run(this: EffectNode): void {
this.dirty = false;
if (ngDevMode && isInNotificationPhase()) {
throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
}
if (this.hasRun && !consumerPollProducersForChange(this)) {
return;
}
this.hasRun = true;
const registerCleanupFn: EffectCleanupRegisterFn = (cleanupFn) =>
(this.cleanupFns ??= []).push(cleanupFn);
const prevNode = consumerBeforeComputation(this);
// We clear `setIsRefreshingViews` so that `markForCheck()` within the body of an effect will
// cause CD to reach the component in question.
const prevRefreshingViews = setIsRefreshingViews(false);
try {
this.maybeCleanup();
this.fn(registerCleanupFn);
} finally {
setIsRefreshingViews(prevRefreshingViews);
consumerAfterComputation(this, prevNode);
}
},
maybeCleanup(this: EffectNode): void {
if (!this.cleanupFns?.length) {
return;
}
try {
// Attempt to run the cleanup functions. Regardless of failure or success, we consider
// cleanup "completed" and clear the list for the next run of the effect. Note that an error
// from the cleanup function will still crash the current run of the effect.
while (this.cleanupFns.length) {
this.cleanupFns.pop()!();
}
} finally {
this.cleanupFns = [];
}
},
}))();
export const ROOT_EFFECT_NODE: Omit<RootEffectNode, 'fn' | 'scheduler' | 'notifier' | 'injector'> =
/* @__PURE__ */ (() => ({
...BASE_EFFECT_NODE,
consumerMarkedDirty(this: RootEffectNode) {
this.scheduler.schedule(this);
this.notifier.notify(NotificationSource.RootEffect);
},
destroy(this: RootEffectNode) {
consumerDestroy(this);
this.onDestroyFn();
this.maybeCleanup();
},
}))();
export const VIEW_EFFECT_NODE: Omit<ViewEffectNode, 'fn' | 'view' | 'injector' | 'notifier'> =
/* @__PURE__ */ (() => ({
...BASE_EFFECT_NODE,
consumerMarkedDirty(this: ViewEffectNode): void {
this.view[FLAGS] |= LViewFlags.HasChildViewsToRefresh;
markAncestorsForTraversal(this.view);
this.notifier.notify(NotificationSource.ViewEffect);
},
destroy(this: ViewEffectNode): void {
consumerDestroy(this);
this.onDestroyFn();
this.maybeCleanup();
this.view[EFFECTS]?.delete(this);
},
}))();
export function createViewEffect(
view: LView,
notifier: ChangeDetectionScheduler,
fn: (onCleanup: EffectCleanupRegisterFn) => void,
): ViewEffectNode {
const node = Object.create(VIEW_EFFECT_NODE) as ViewEffectNode;
node.view = view;
node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
node.notifier = notifier;
node.fn = fn;
view[EFFECTS] ??= new Set();
view[EFFECTS].add(node);
node.consumerMarkedDirty(node);
return node;
}
export function createRootEffect(
fn: (onCleanup: EffectCleanupRegisterFn) => void,
scheduler: EffectScheduler,
notifier: ChangeDetectionScheduler,
): RootEffectNode {
const node = Object.create(ROOT_EFFECT_NODE) as RootEffectNode;
node.fn = fn;
node.scheduler = scheduler;
node.notifier = notifier;
node.zone = typeof Zone !== 'undefined' ? Zone.current : null;
node.scheduler.schedule(node);
node.notifier.notify(NotificationSource.RootEffect);
return node;
} | {
"end_byte": 11412,
"start_byte": 7657,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/effect.ts"
} |
angular/packages/core/src/render3/reactivity/asserts.ts_0_1192 | /**
* @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 {getActiveConsumer} from '@angular/core/primitives/signals';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
/**
* Asserts that the current stack frame is not within a reactive context. Useful
* to disallow certain code from running inside a reactive context (see {@link toSignal}).
*
* @param debugFn a reference to the function making the assertion (used for the error message).
*
* @publicApi
*/
export function assertNotInReactiveContext(debugFn: Function, extraContext?: string): void {
// Taking a `Function` instead of a string name here prevents the un-minified name of the function
// from being retained in the bundle regardless of minification.
if (getActiveConsumer() !== null) {
throw new RuntimeError(
RuntimeErrorCode.ASSERTION_NOT_INSIDE_REACTIVE_CONTEXT,
ngDevMode &&
`${debugFn.name}() cannot be called from within a reactive context.${
extraContext ? ` ${extraContext}` : ''
}`,
);
}
}
| {
"end_byte": 1192,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/asserts.ts"
} |
angular/packages/core/src/render3/reactivity/after_render_effect.ts_0_8199 | /**
* @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 {
consumerAfterComputation,
consumerBeforeComputation,
consumerPollProducersForChange,
producerAccessed,
SIGNAL,
SIGNAL_NODE,
type SignalNode,
} from '@angular/core/primitives/signals';
import {type Signal} from '../reactivity/api';
import {type EffectCleanupFn, type EffectCleanupRegisterFn} from './effect';
import {
ChangeDetectionScheduler,
NotificationSource,
} from '../../change_detection/scheduling/zoneless_scheduling';
import {Injector} from '../../di/injector';
import {inject} from '../../di/injector_compatibility';
import {AfterRenderImpl, AfterRenderManager, AfterRenderSequence} from '../after_render/manager';
import {AfterRenderPhase, type AfterRenderRef} from '../after_render/api';
import {NOOP_AFTER_RENDER_REF, type AfterRenderOptions} from '../after_render/hooks';
import {DestroyRef} from '../../linker/destroy_ref';
import {assertNotInReactiveContext} from './asserts';
import {assertInInjectionContext} from '../../di/contextual';
import {isPlatformBrowser} from '../util/misc_utils';
const NOT_SET = Symbol('NOT_SET');
const EMPTY_CLEANUP_SET = new Set<() => void>();
/** Callback type for an `afterRenderEffect` phase effect */
type AfterRenderPhaseEffectHook = (
// Either a cleanup function or a pipelined value and a cleanup function
...args:
| [onCleanup: EffectCleanupRegisterFn]
| [previousPhaseValue: unknown, onCleanup: EffectCleanupRegisterFn]
) => unknown;
/**
* Reactive node in the graph for this `afterRenderEffect` phase effect.
*
* This node type extends `SignalNode` because `afterRenderEffect` phases effects produce a value
* which is consumed as a `Signal` by subsequent phases.
*/
interface AfterRenderPhaseEffectNode extends SignalNode<unknown> {
/** The phase of the effect implemented by this node */
phase: AfterRenderPhase;
/** The sequence of phases to which this node belongs, used for state of the whole sequence */
sequence: AfterRenderEffectSequence;
/** The user's callback function */
userFn: AfterRenderPhaseEffectHook;
/** Signal function that retrieves the value of this node, used as the value for the next phase */
signal: Signal<unknown>;
/** Registered cleanup functions, or `null` if none have ever been registered */
cleanup: Set<() => void> | null;
/** Pre-bound helper function passed to the user's callback which writes to `this.cleanup` */
registerCleanupFn: EffectCleanupRegisterFn;
/** Entrypoint to running this effect that's given to the `afterRender` machinery */
phaseFn(previousValue?: unknown): unknown;
}
const AFTER_RENDER_PHASE_EFFECT_NODE = /* @__PURE__ */ (() => ({
...SIGNAL_NODE,
consumerIsAlwaysLive: true,
consumerAllowSignalWrites: true,
value: NOT_SET,
cleanup: null,
/** Called when the effect becomes dirty */
consumerMarkedDirty(this: AfterRenderPhaseEffectNode): void {
if (this.sequence.impl.executing) {
// If hooks are in the middle of executing, then it matters whether this node has yet been
// executed within its sequence. If not, then we don't want to notify the scheduler since
// this node will be reached naturally.
if (this.sequence.lastPhase === null || this.sequence.lastPhase < this.phase) {
return;
}
// If during the execution of a later phase an earlier phase became dirty, then we should not
// run any further phases until the earlier one reruns.
this.sequence.erroredOrDestroyed = true;
}
// Either hooks are not running, or we're marking a node dirty that has already run within its
// sequence.
this.sequence.scheduler.notify(NotificationSource.RenderHook);
},
phaseFn(this: AfterRenderPhaseEffectNode, previousValue?: unknown): unknown {
this.sequence.lastPhase = this.phase;
if (!this.dirty) {
return this.signal;
}
this.dirty = false;
if (this.value !== NOT_SET && !consumerPollProducersForChange(this)) {
// None of our producers report a change since the last time they were read, so no
// recomputation of our value is necessary.
return this.signal;
}
// Run any needed cleanup functions.
try {
for (const cleanupFn of this.cleanup ?? EMPTY_CLEANUP_SET) {
cleanupFn();
}
} finally {
// Even if a cleanup function errors, ensure it's cleared.
this.cleanup?.clear();
}
// Prepare to call the user's effect callback. If there was a previous phase, then it gave us
// its value as a `Signal`, otherwise `previousValue` will be `undefined`.
const args: unknown[] = [];
if (previousValue !== undefined) {
args.push(previousValue);
}
args.push(this.registerCleanupFn);
// Call the user's callback in our reactive context.
const prevConsumer = consumerBeforeComputation(this);
let newValue;
try {
newValue = this.userFn.apply(null, args as any);
} finally {
consumerAfterComputation(this, prevConsumer);
}
if (this.value === NOT_SET || !this.equal(this.value, newValue)) {
this.value = newValue;
this.version++;
}
return this.signal;
},
}))();
/**
* An `AfterRenderSequence` that manages an `afterRenderEffect`'s phase effects.
*/
class AfterRenderEffectSequence extends AfterRenderSequence {
/**
* While this sequence is executing, this tracks the last phase which was called by the
* `afterRender` machinery.
*
* When a phase effect is marked dirty, this is used to determine whether it's already run or not.
*/
lastPhase: AfterRenderPhase | null = null;
/**
* The reactive nodes for each phase, if a phase effect is defined for that phase.
*
* These are initialized to `undefined` but set in the constructor.
*/
private readonly nodes: [
AfterRenderPhaseEffectNode | undefined,
AfterRenderPhaseEffectNode | undefined,
AfterRenderPhaseEffectNode | undefined,
AfterRenderPhaseEffectNode | undefined,
] = [undefined, undefined, undefined, undefined];
constructor(
impl: AfterRenderImpl,
effectHooks: Array<AfterRenderPhaseEffectHook | undefined>,
readonly scheduler: ChangeDetectionScheduler,
destroyRef: DestroyRef,
) {
// Note that we also initialize the underlying `AfterRenderSequence` hooks to `undefined` and
// populate them as we create reactive nodes below.
super(impl, [undefined, undefined, undefined, undefined], false, destroyRef);
// Setup a reactive node for each phase.
for (const phase of AfterRenderImpl.PHASES) {
const effectHook = effectHooks[phase];
if (effectHook === undefined) {
continue;
}
const node = Object.create(AFTER_RENDER_PHASE_EFFECT_NODE) as AfterRenderPhaseEffectNode;
node.sequence = this;
node.phase = phase;
node.userFn = effectHook;
node.dirty = true;
node.signal = (() => {
producerAccessed(node);
return node.value;
}) as Signal<unknown>;
node.signal[SIGNAL] = node;
node.registerCleanupFn = (fn: EffectCleanupFn) =>
(node.cleanup ??= new Set<() => void>()).add(fn);
this.nodes[phase] = node;
// Install the upstream hook which runs the `phaseFn` for this phase.
this.hooks[phase] = (value) => node.phaseFn(value);
}
}
override afterRun(): void {
super.afterRun();
// We're done running this sequence, so reset `lastPhase`.
this.lastPhase = null;
}
override destroy(): void {
super.destroy();
// Run the cleanup functions for each node.
for (const node of this.nodes) {
for (const fn of node?.cleanup ?? EMPTY_CLEANUP_SET) {
fn();
}
}
}
}
/**
* An argument list containing the first non-never type in the given type array, or an empty
* argument list if there are no non-never types in the type array.
*/
export type ɵFirstAvailableSignal<T extends unknown[]> = T extends [infer H, ...infer R]
? [H] extends [never]
? ɵFirstAvailableSignal<R>
: [Signal<H>]
: [];
| {
"end_byte": 8199,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/after_render_effect.ts"
} |
angular/packages/core/src/render3/reactivity/after_render_effect.ts_8201_14067 | *
* Register an effect that, when triggered, is invoked when the application finishes rendering, during the
* `mixedReadWrite` phase.
*
* <div class="alert is-critical">
*
* You should prefer specifying an explicit phase for the effect instead, or you risk significant
* performance degradation.
*
* </div>
*
* Note that callback-based `afterRenderEffect`s will run
* - in the order it they are registered
* - only when dirty
* - on browser platforms only
* - during the `mixedReadWrite` phase
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param callback An effect callback function to register
* @param options Options to control the behavior of the callback
*
* @experimental
*/
export function afterRenderEffect(
callback: (onCleanup: EffectCleanupRegisterFn) => void,
options?: Omit<AfterRenderOptions, 'phase'>,
): AfterRenderRef;
/**
* Register effects that, when triggered, are invoked when the application finishes rendering,
* during the specified phases. The available phases are:
* - `earlyRead`
* Use this phase to **read** from the DOM before a subsequent `write` callback, for example to
* perform custom layout that the browser doesn't natively support. Prefer the `read` phase if
* reading can wait until after the write phase. **Never** write to the DOM in this phase.
* - `write`
* Use this phase to **write** to the DOM. **Never** read from the DOM in this phase.
* - `mixedReadWrite`
* Use this phase to read from and write to the DOM simultaneously. **Never** use this phase if
* it is possible to divide the work among the other phases instead.
* - `read`
* Use this phase to **read** from the DOM. **Never** write to the DOM in this phase.
*
* <div class="alert is-critical">
*
* You should prefer using the `read` and `write` phases over the `earlyRead` and `mixedReadWrite`
* phases when possible, to avoid performance degradation.
*
* </div>
*
* Note that:
* - Effects run in the following phase order, only when dirty through signal dependencies:
* 1. `earlyRead`
* 2. `write`
* 3. `mixedReadWrite`
* 4. `read`
* - `afterRenderEffect`s in the same phase run in the order they are registered.
* - `afterRenderEffect`s run on browser platforms only, they will not run on the server.
* - `afterRenderEffect`s will run at least once.
*
* The first phase callback to run as part of this spec will receive no parameters. Each
* subsequent phase callback in this spec will receive the return value of the previously run
* phase callback as a `Signal`. This can be used to coordinate work across multiple phases.
*
* Angular is unable to verify or enforce that phases are used correctly, and instead
* relies on each developer to follow the guidelines documented for each value and
* carefully choose the appropriate one, refactoring their code if necessary. By doing
* so, Angular is better able to minimize the performance degradation associated with
* manual DOM access, ensuring the best experience for the end users of your application
* or library.
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param spec The effect functions to register
* @param options Options to control the behavior of the effects
*
* @usageNotes
*
* Use `afterRenderEffect` to create effects that will read or write from the DOM and thus should
* run after rendering.
*
* @experimental
*/
export function afterRenderEffect<E = never, W = never, M = never>(
spec: {
earlyRead?: (onCleanup: EffectCleanupRegisterFn) => E;
write?: (...args: [...ɵFirstAvailableSignal<[E]>, EffectCleanupRegisterFn]) => W;
mixedReadWrite?: (...args: [...ɵFirstAvailableSignal<[W, E]>, EffectCleanupRegisterFn]) => M;
read?: (...args: [...ɵFirstAvailableSignal<[M, W, E]>, EffectCleanupRegisterFn]) => void;
},
options?: Omit<AfterRenderOptions, 'phase'>,
): AfterRenderRef;
/**
* @experimental
*/
export function afterRenderEffect<E = never, W = never, M = never>(
callbackOrSpec:
| ((onCleanup: EffectCleanupRegisterFn) => void)
| {
earlyRead?: (onCleanup: EffectCleanupRegisterFn) => E;
write?: (...args: [...ɵFirstAvailableSignal<[E]>, EffectCleanupRegisterFn]) => W;
mixedReadWrite?: (
...args: [...ɵFirstAvailableSignal<[W, E]>, EffectCleanupRegisterFn]
) => M;
read?: (...args: [...ɵFirstAvailableSignal<[M, W, E]>, EffectCleanupRegisterFn]) => void;
},
options?: Omit<AfterRenderOptions, 'phase'>,
): AfterRenderRef {
ngDevMode &&
assertNotInReactiveContext(
afterRenderEffect,
'Call `afterRenderEffect` outside of a reactive context. For example, create the render ' +
'effect inside the component constructor`.',
);
!options?.injector && assertInInjectionContext(afterRenderEffect);
const injector = options?.injector ?? inject(Injector);
if (!isPlatformBrowser(injector)) {
return NOOP_AFTER_RENDER_REF;
}
const scheduler = injector.get(ChangeDetectionScheduler);
const manager = injector.get(AfterRenderManager);
manager.impl ??= injector.get(AfterRenderImpl);
let spec = callbackOrSpec;
if (typeof spec === 'function') {
spec = {mixedReadWrite: callbackOrSpec as any};
}
const sequence = new AfterRenderEffectSequence(
manager.impl,
[spec.earlyRead, spec.write, spec.mixedReadWrite, spec.read] as AfterRenderPhaseEffectHook[],
scheduler,
injector.get(DestroyRef),
);
manager.impl.register(sequence);
return sequence;
}
| {
"end_byte": 14067,
"start_byte": 8201,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/after_render_effect.ts"
} |
angular/packages/core/src/render3/reactivity/linked_signal.ts_0_6781 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {signalAsReadonlyFn, WritableSignal} from './signal';
import {Signal, ValueEqualityFn} from './api';
import {
producerMarkClean,
ReactiveNode,
SIGNAL,
signalSetFn,
signalUpdateFn,
producerUpdateValueVersion,
REACTIVE_NODE,
defaultEquals,
consumerBeforeComputation,
consumerAfterComputation,
producerAccessed,
} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
type ComputationFn<S, D> = (source: S, previous?: {source: S; value: D}) => D;
interface LinkedSignalNode<S, D> extends ReactiveNode {
/**
* Value of the source signal that was used to derive the computed value.
*/
sourceValue: S;
/**
* Current state value, or one of the sentinel values (`UNSET`, `COMPUTING`,
* `ERROR`).
*/
value: D;
/**
* If `value` is `ERRORED`, the error caught from the last computation attempt which will
* be re-thrown.
*/
error: unknown;
/**
* The source function represents reactive dependency based on which the linked state is reset.
*/
source: () => S;
/**
* The computation function which will produce a new value based on the source and, optionally - previous values.
*/
computation: ComputationFn<S, D>;
equal: ValueEqualityFn<D>;
}
export type LinkedSignalGetter<S, D> = (() => D) & {
[SIGNAL]: LinkedSignalNode<S, D>;
};
const identityFn = <T>(v: T) => v;
/**
* Create a linked signal which represents state that is (re)set from a linked reactive expression.
*/
function createLinkedSignal<S, D>(node: LinkedSignalNode<S, D>): WritableSignal<D> {
const linkedSignalGetter = () => {
// Check if the value needs updating before returning it.
producerUpdateValueVersion(node);
// Record that someone looked at this signal.
producerAccessed(node);
if (node.value === ERRORED) {
throw node.error;
}
return node.value;
};
const getter = linkedSignalGetter as LinkedSignalGetter<S, D> & WritableSignal<D>;
getter[SIGNAL] = node;
if (ngDevMode) {
getter.toString = () => `[LinkedSignal: ${getter()}]`;
}
getter.set = (newValue: D) => {
producerUpdateValueVersion(node);
signalSetFn(node, newValue);
producerMarkClean(node);
};
getter.update = (updateFn: (value: D) => D) => {
producerUpdateValueVersion(node);
signalUpdateFn(node, updateFn);
producerMarkClean(node);
};
getter.asReadonly = signalAsReadonlyFn.bind(getter as any) as () => Signal<D>;
return getter;
}
/**
* @experimental
*/
export function linkedSignal<D>(
computation: () => D,
options?: {equal?: ValueEqualityFn<NoInfer<D>>},
): WritableSignal<D>;
export function linkedSignal<S, D>(options: {
source: () => S;
computation: (source: NoInfer<S>, previous?: {source: NoInfer<S>; value: NoInfer<D>}) => D;
equal?: ValueEqualityFn<NoInfer<D>>;
}): WritableSignal<D>;
export function linkedSignal<S, D>(
optionsOrComputation:
| {
source: () => S;
computation: ComputationFn<S, D>;
equal?: ValueEqualityFn<D>;
}
| (() => D),
options?: {equal?: ValueEqualityFn<D>},
): WritableSignal<D> {
performanceMarkFeature('NgSignals');
const isShorthand = typeof optionsOrComputation === 'function';
const node: LinkedSignalNode<unknown, unknown> = Object.create(LINKED_SIGNAL_NODE);
node.source = isShorthand ? optionsOrComputation : optionsOrComputation.source;
if (!isShorthand) {
node.computation = optionsOrComputation.computation as ComputationFn<unknown, unknown>;
}
const equal = isShorthand ? options?.equal : optionsOrComputation.equal;
if (equal) {
node.equal = equal as ValueEqualityFn<unknown>;
}
return createLinkedSignal(node as LinkedSignalNode<S, D>);
}
/**
* A dedicated symbol used before a state value has been set / calculated for the first time.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const UNSET: any = /* @__PURE__ */ Symbol('UNSET');
/**
* A dedicated symbol used in place of a linked signal value to indicate that a given computation
* is in progress. Used to detect cycles in computation chains.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const COMPUTING: any = /* @__PURE__ */ Symbol('COMPUTING');
/**
* A dedicated symbol used in place of a linked signal value to indicate that a given computation
* failed. The thrown error is cached until the computation gets dirty again or the state is set.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const ERRORED: any = /* @__PURE__ */ Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `LINKED_SIGNAL_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const LINKED_SIGNAL_NODE = /* @__PURE__ */ (() => {
return {
...REACTIVE_NODE,
value: UNSET,
dirty: true,
error: null,
equal: defaultEquals,
computation: identityFn,
producerMustRecompute(node: LinkedSignalNode<unknown, unknown>): boolean {
// Force a recomputation if there's no current value, or if the current value is in the
// process of being calculated (which should throw an error).
return node.value === UNSET || node.value === COMPUTING;
},
producerRecomputeValue(node: LinkedSignalNode<unknown, unknown>): void {
if (node.value === COMPUTING) {
// Our computation somehow led to a cyclic read of itself.
throw new Error('Detected cycle in computations.');
}
const oldValue = node.value;
node.value = COMPUTING;
const prevConsumer = consumerBeforeComputation(node);
let newValue: unknown;
try {
const newSourceValue = node.source();
const prev =
oldValue === UNSET || oldValue === ERRORED
? undefined
: {
source: node.sourceValue,
value: oldValue,
};
newValue = node.computation(newSourceValue, prev);
node.sourceValue = newSourceValue;
} catch (err) {
newValue = ERRORED;
node.error = err;
} finally {
consumerAfterComputation(node, prevConsumer);
}
if (oldValue !== UNSET && newValue !== ERRORED && node.equal(oldValue, newValue)) {
// No change to `valueVersion` - old and new values are
// semantically equivalent.
node.value = oldValue;
return;
}
node.value = newValue;
node.version++;
},
};
})();
| {
"end_byte": 6781,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/linked_signal.ts"
} |
angular/packages/core/src/render3/reactivity/view_effect_runner.ts_0_1413 | /**
* @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 {EFFECTS, FLAGS, type LView, LViewFlags} from '../interfaces/view';
export function runEffectsInView(view: LView): void {
if (view[EFFECTS] === null) {
return;
}
// Since effects can make other effects dirty, we flush them in a loop until there are no more to
// flush.
let tryFlushEffects = true;
while (tryFlushEffects) {
let foundDirtyEffect = false;
for (const effect of view[EFFECTS]) {
if (!effect.dirty) {
continue;
}
foundDirtyEffect = true;
// `runEffectsInView` is called during change detection, and therefore runs
// in the Angular zone if it's available.
if (effect.zone === null || Zone.current === effect.zone) {
effect.run();
} else {
effect.zone.run(() => effect.run());
}
}
// Check if we need to continue flushing. If we didn't find any dirty effects, then there's
// no need to loop back. Otherwise, check the view to see if it was marked for traversal
// again. If so, there's a chance that one of the effects we ran caused another effect to
// become dirty.
tryFlushEffects = foundDirtyEffect && !!(view[FLAGS] & LViewFlags.HasChildViewsToRefresh);
}
}
| {
"end_byte": 1413,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/view_effect_runner.ts"
} |
angular/packages/core/src/render3/reactivity/microtask_effect.ts_0_5889 | /**
* @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 {createWatch, Watch, WatchCleanupRegisterFn} from '@angular/core/primitives/signals';
import {ChangeDetectorRef} from '../../change_detection/change_detector_ref';
import {Injector} from '../../di/injector';
import {inject} from '../../di/injector_compatibility';
import {ɵɵdefineInjectable} from '../../di/interface/defs';
import {ErrorHandler} from '../../error_handler';
import type {ViewRef} from '../view_ref';
import {DestroyRef} from '../../linker/destroy_ref';
import {FLAGS, LViewFlags, EFFECTS_TO_SCHEDULE} from '../interfaces/view';
import type {CreateEffectOptions, EffectCleanupRegisterFn, EffectRef} from './effect';
import {type SchedulableEffect, ZoneAwareEffectScheduler} from './root_effect_scheduler';
import {performanceMarkFeature} from '../../util/performance';
import {assertNotInReactiveContext} from './asserts';
import {assertInInjectionContext} from '../../di';
import {PendingTasksInternal} from '../../pending_tasks';
export class MicrotaskEffectScheduler extends ZoneAwareEffectScheduler {
private readonly pendingTasks = inject(PendingTasksInternal);
private taskId: number | null = null;
override schedule(effect: SchedulableEffect): void {
// Check whether there are any pending effects _before_ queueing in the base class.
super.schedule(effect);
if (this.taskId === null) {
this.taskId = this.pendingTasks.add();
queueMicrotask(() => this.flush());
}
}
override flush(): void {
try {
super.flush();
} finally {
if (this.taskId !== null) {
this.pendingTasks.remove(this.taskId);
this.taskId = null;
}
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: MicrotaskEffectScheduler,
providedIn: 'root',
factory: () => new MicrotaskEffectScheduler(),
});
}
/**
* Core reactive node for an Angular effect.
*
* `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
* scheduling abstraction (`MicrotaskEffectScheduler`) as well as automatic cleanup via `DestroyRef`
* if available/requested.
*/
class EffectHandle implements EffectRef, SchedulableEffect {
unregisterOnDestroy: (() => void) | undefined;
readonly watcher: Watch;
constructor(
private scheduler: MicrotaskEffectScheduler,
private effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
public zone: Zone | null,
destroyRef: DestroyRef | null,
private injector: Injector,
allowSignalWrites: boolean,
) {
this.watcher = createWatch(
(onCleanup) => this.runEffect(onCleanup),
() => this.schedule(),
allowSignalWrites,
);
this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
}
private runEffect(onCleanup: WatchCleanupRegisterFn): void {
try {
this.effectFn(onCleanup);
} catch (err) {
// Inject the `ErrorHandler` here in order to avoid circular DI error
// if the effect is used inside of a custom `ErrorHandler`.
const errorHandler = this.injector.get(ErrorHandler, null, {optional: true});
errorHandler?.handleError(err);
}
}
run(): void {
this.watcher.run();
}
private schedule(): void {
this.scheduler.schedule(this);
}
destroy(): void {
this.watcher.destroy();
this.unregisterOnDestroy?.();
// Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
// retain a reference to it. Attempting to execute it will be a no-op.
}
}
// Just used for the name for the debug error below.
function effect() {}
/**
* Create a global `Effect` for the given reactive function.
*/
export function microtaskEffect(
effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
options?: CreateEffectOptions,
): EffectRef {
performanceMarkFeature('NgSignals');
ngDevMode &&
assertNotInReactiveContext(
effect,
'Call `effect` outside of a reactive context. For example, schedule the ' +
'effect inside the component constructor.',
);
!options?.injector && assertInInjectionContext(effect);
const injector = options?.injector ?? inject(Injector);
const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
const handle = new EffectHandle(
injector.get(MicrotaskEffectScheduler),
effectFn,
typeof Zone === 'undefined' ? null : Zone.current,
destroyRef,
injector,
options?.allowSignalWrites ?? false,
);
// Effects need to be marked dirty manually to trigger their initial run. The timing of this
// marking matters, because the effects may read signals that track component inputs, which are
// only available after those components have had their first update pass.
//
// We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
// the context of a component or not. If it is, then we check whether the component has already
// run its update pass, and defer the effect's initial scheduling until the update pass if it
// hasn't already run.
const cdr = injector.get(ChangeDetectorRef, null, {optional: true}) as ViewRef<unknown> | null;
if (!cdr || !(cdr._lView[FLAGS] & LViewFlags.FirstLViewPass)) {
// This effect is either not running in a view injector, or the view has already
// undergone its first change detection pass, which is necessary for any required inputs to be
// set.
handle.watcher.notify();
} else {
// Delay the initialization of the effect until the view is fully initialized.
(cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
}
return handle;
}
| {
"end_byte": 5889,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/microtask_effect.ts"
} |
angular/packages/core/src/render3/reactivity/api.ts_0_950 | /**
* @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 {SIGNAL} from '@angular/core/primitives/signals';
/**
* A reactive value which notifies consumers of any changes.
*
* Signals are functions which returns their current value. To access the current value of a signal,
* call it.
*
* Ordinary values can be turned into `Signal`s with the `signal` function.
*/
export type Signal<T> = (() => T) & {
[SIGNAL]: unknown;
};
/**
* Checks if the given `value` is a reactive `Signal`.
*/
export function isSignal(value: unknown): value is Signal<unknown> {
return typeof value === 'function' && (value as Signal<unknown>)[SIGNAL] !== undefined;
}
/**
* A comparison function which can determine if two values are equal.
*/
export type ValueEqualityFn<T> = (a: T, b: T) => boolean;
| {
"end_byte": 950,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/api.ts"
} |
angular/packages/core/src/render3/reactivity/untracked.ts_0_761 | /**
* @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';
/**
* Execute an arbitrary function in a non-reactive (non-tracking) context. The executed function
* can, optionally, return a value.
*/
export function untracked<T>(nonReactiveReadsFn: () => T): T {
const prevConsumer = setActiveConsumer(null);
// We are not trying to catch any particular errors here, just making sure that the consumers
// stack is restored in case of errors.
try {
return nonReactiveReadsFn();
} finally {
setActiveConsumer(prevConsumer);
}
}
| {
"end_byte": 761,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/untracked.ts"
} |
angular/packages/core/src/render3/reactivity/signal.ts_0_3438 | /**
* @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 {
createSignal,
SIGNAL,
SignalGetter,
SignalNode,
signalSetFn,
signalUpdateFn,
} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
import {isSignal, Signal, ValueEqualityFn} from './api';
/** Symbol used distinguish `WritableSignal` from other non-writable signals and functions. */
export const ɵWRITABLE_SIGNAL = /* @__PURE__ */ Symbol('WRITABLE_SIGNAL');
/**
* A `Signal` with a value that can be mutated via a setter interface.
*/
export interface WritableSignal<T> extends Signal<T> {
[ɵWRITABLE_SIGNAL]: T;
/**
* Directly set the signal to a new value, and notify any dependents.
*/
set(value: T): void;
/**
* Update the value of the signal based on its current value, and
* notify any dependents.
*/
update(updateFn: (value: T) => T): void;
/**
* Returns a readonly version of this signal. Readonly signals can be accessed to read their value
* but can't be changed using set or update methods. The readonly signals do _not_ have
* any built-in mechanism that would prevent deep-mutation of their value.
*/
asReadonly(): Signal<T>;
}
/**
* Utility function used during template type checking to extract the value from a `WritableSignal`.
* @codeGenApi
*/
export function ɵunwrapWritableSignal<T>(value: T | {[ɵWRITABLE_SIGNAL]: T}): T {
// Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`,
// because the latter incorrectly unwraps non-signal getter functions.
return null!;
}
/**
* Options passed to the `signal` creation function.
*/
export interface CreateSignalOptions<T> {
/**
* A comparison function which defines equality for signal values.
*/
equal?: ValueEqualityFn<T>;
/**
* A debug name for the signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* Create a `Signal` that can be set or updated directly.
*/
export function signal<T>(initialValue: T, options?: CreateSignalOptions<T>): WritableSignal<T> {
performanceMarkFeature('NgSignals');
const signalFn = createSignal(initialValue) as SignalGetter<T> & WritableSignal<T>;
const node = signalFn[SIGNAL];
if (options?.equal) {
node.equal = options.equal;
}
signalFn.set = (newValue: T) => signalSetFn(node, newValue);
signalFn.update = (updateFn: (value: T) => T) => signalUpdateFn(node, updateFn);
signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn as any) as () => Signal<T>;
if (ngDevMode) {
signalFn.toString = () => `[Signal: ${signalFn()}]`;
node.debugName = options?.debugName;
}
return signalFn as WritableSignal<T>;
}
export function signalAsReadonlyFn<T>(this: SignalGetter<T>): Signal<T> {
const node = this[SIGNAL] as SignalNode<T> & {readonlyFn?: Signal<T>};
if (node.readonlyFn === undefined) {
const readonlyFn = () => this();
(readonlyFn as any)[SIGNAL] = node;
node.readonlyFn = readonlyFn as Signal<T>;
}
return node.readonlyFn;
}
/**
* Checks if the given `value` is a writeable signal.
*/
export function isWritableSignal(value: unknown): value is WritableSignal<unknown> {
return isSignal(value) && typeof (value as any).set === 'function';
}
| {
"end_byte": 3438,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/signal.ts"
} |
angular/packages/core/src/render3/reactivity/computed.ts_0_1233 | /**
* @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 {createComputed, SIGNAL} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
import {Signal, ValueEqualityFn} from './api';
/**
* Options passed to the `computed` creation function.
*/
export interface CreateComputedOptions<T> {
/**
* A comparison function which defines equality for computed values.
*/
equal?: ValueEqualityFn<T>;
/**
* A debug name for the computed signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* Create a computed `Signal` which derives a reactive value from an expression.
*/
export function computed<T>(computation: () => T, options?: CreateComputedOptions<T>): Signal<T> {
performanceMarkFeature('NgSignals');
const getter = createComputed(computation);
if (options?.equal) {
getter[SIGNAL].equal = options.equal;
}
if (ngDevMode) {
getter.toString = () => `[Computed: ${getter()}]`;
getter[SIGNAL].debugName = options?.debugName;
}
return getter;
}
| {
"end_byte": 1233,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/computed.ts"
} |
angular/packages/core/src/render3/reactivity/root_effect_scheduler.ts_0_2635 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ɵɵdefineInjectable} from '../../di/interface/defs';
import {PendingTasksInternal} from '../../pending_tasks';
import {inject} from '../../di/injector_compatibility';
/**
* Abstraction that encompasses any kind of effect that can be scheduled.
*/
export interface SchedulableEffect {
run(): void;
zone: {
run<T>(fn: () => T): T;
} | null;
}
/**
* A scheduler which manages the execution of effects.
*/
export abstract class EffectScheduler {
/**
* Schedule the given effect to be executed at a later time.
*
* It is an error to attempt to execute any effects synchronously during a scheduling operation.
*/
abstract schedule(e: SchedulableEffect): void;
/**
* Run any scheduled effects.
*/
abstract flush(): void;
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: EffectScheduler,
providedIn: 'root',
factory: () => new ZoneAwareEffectScheduler(),
});
}
/**
* A wrapper around `ZoneAwareQueueingScheduler` that schedules flushing via the microtask queue
* when.
*/
export class ZoneAwareEffectScheduler implements EffectScheduler {
private queuedEffectCount = 0;
private queues = new Map<Zone | null, Set<SchedulableEffect>>();
schedule(handle: SchedulableEffect): void {
this.enqueue(handle);
}
private enqueue(handle: SchedulableEffect): void {
const zone = handle.zone as Zone | null;
if (!this.queues.has(zone)) {
this.queues.set(zone, new Set());
}
const queue = this.queues.get(zone)!;
if (queue.has(handle)) {
return;
}
this.queuedEffectCount++;
queue.add(handle);
}
/**
* Run all scheduled effects.
*
* Execution order of effects within the same zone is guaranteed to be FIFO, but there is no
* ordering guarantee between effects scheduled in different zones.
*/
flush(): void {
while (this.queuedEffectCount > 0) {
for (const [zone, queue] of this.queues) {
// `zone` here must be defined.
if (zone === null) {
this.flushQueue(queue);
} else {
zone.run(() => this.flushQueue(queue));
}
}
}
}
private flushQueue(queue: Set<SchedulableEffect>): void {
for (const handle of queue) {
queue.delete(handle);
this.queuedEffectCount--;
// TODO: what happens if this throws an error?
handle.run();
}
}
}
| {
"end_byte": 2635,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/root_effect_scheduler.ts"
} |
angular/packages/core/src/render3/reactivity/patch.ts_0_339 | /**
* @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
*/
/**
* Controls whether effects use the legacy `microtaskEffect` by default.
*/
export const USE_MICROTASK_EFFECT_BY_DEFAULT = false;
| {
"end_byte": 339,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/reactivity/patch.ts"
} |
angular/packages/core/src/render3/styling/static_styling.ts_0_2044 | /**
* @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 {concatStringsWithSpace} from '../../util/stringify';
import {assertFirstCreatePass} from '../assert';
import {AttributeMarker} from '../interfaces/attribute_marker';
import {TAttributes, TNode} from '../interfaces/node';
import {getTView} from '../state';
/**
* Compute the static styling (class/style) from `TAttributes`.
*
* This function should be called during `firstCreatePass` only.
*
* @param tNode The `TNode` into which the styling information should be loaded.
* @param attrs `TAttributes` containing the styling information.
* @param writeToHost Where should the resulting static styles be written?
* - `false` Write to `TNode.stylesWithoutHost` / `TNode.classesWithoutHost`
* - `true` Write to `TNode.styles` / `TNode.classes`
*/
export function computeStaticStyling(
tNode: TNode,
attrs: TAttributes | null,
writeToHost: boolean,
): void {
ngDevMode &&
assertFirstCreatePass(getTView(), 'Expecting to be called in first template pass only');
let styles: string | null = writeToHost ? tNode.styles : null;
let classes: string | null = writeToHost ? tNode.classes : null;
let mode: AttributeMarker | 0 = 0;
if (attrs !== null) {
for (let i = 0; i < attrs.length; i++) {
const value = attrs[i];
if (typeof value === 'number') {
mode = value;
} else if (mode == AttributeMarker.Classes) {
classes = concatStringsWithSpace(classes, value as string);
} else if (mode == AttributeMarker.Styles) {
const style = value as string;
const styleValue = attrs[++i] as string;
styles = concatStringsWithSpace(styles, style + ': ' + styleValue + ';');
}
}
}
writeToHost ? (tNode.styles = styles) : (tNode.stylesWithoutHost = styles);
writeToHost ? (tNode.classes = classes) : (tNode.classesWithoutHost = classes);
}
| {
"end_byte": 2044,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/static_styling.ts"
} |
angular/packages/core/src/render3/styling/class_differ.ts_0_1566 | /**
* @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 {assertNotEqual} from '../../util/assert';
import {CharCode} from '../../util/char_code';
/**
* Returns an index of `classToSearch` in `className` taking token boundaries into account.
*
* `classIndexOf('AB A', 'A', 0)` will be 3 (not 0 since `AB!==A`)
*
* @param className A string containing classes (whitespace separated)
* @param classToSearch A class name to locate
* @param startingIndex Starting location of search
* @returns an index of the located class (or -1 if not found)
*/
export function classIndexOf(
className: string,
classToSearch: string,
startingIndex: number,
): number {
ngDevMode && assertNotEqual(classToSearch, '', 'can not look for "" string.');
let end = className.length;
while (true) {
const foundIndex = className.indexOf(classToSearch, startingIndex);
if (foundIndex === -1) return foundIndex;
if (foundIndex === 0 || className.charCodeAt(foundIndex - 1) <= CharCode.SPACE) {
// Ensure that it has leading whitespace
const length = classToSearch.length;
if (
foundIndex + length === end ||
className.charCodeAt(foundIndex + length) <= CharCode.SPACE
) {
// Ensure that it has trailing whitespace
return foundIndex;
}
}
// False positive, keep searching from where we left off.
startingIndex = foundIndex + 1;
}
}
| {
"end_byte": 1566,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/class_differ.ts"
} |
angular/packages/core/src/render3/styling/styling_parser.ts_0_8031 | /**
* @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 {assertEqual, throwError} from '../../util/assert';
import {CharCode} from '../../util/char_code';
/**
* Stores the locations of key/value indexes while parsing styling.
*
* In case of `cssText` parsing the indexes are like so:
* ```
* "key1: value1; key2: value2; key3: value3"
* ^ ^ ^ ^ ^
* | | | | +-- textEnd
* | | | +---------------- valueEnd
* | | +---------------------- value
* | +------------------------ keyEnd
* +---------------------------- key
* ```
*
* In case of `className` parsing the indexes are like so:
* ```
* "key1 key2 key3"
* ^ ^ ^
* | | +-- textEnd
* | +------------------------ keyEnd
* +---------------------------- key
* ```
* NOTE: `value` and `valueEnd` are used only for styles, not classes.
*/
interface ParserState {
textEnd: number;
key: number;
keyEnd: number;
value: number;
valueEnd: number;
}
// Global state of the parser. (This makes parser non-reentrant, but that is not an issue)
const parserState: ParserState = {
textEnd: 0,
key: 0,
keyEnd: 0,
value: 0,
valueEnd: 0,
};
/**
* Retrieves the last parsed `key` of style.
* @param text the text to substring the key from.
*/
export function getLastParsedKey(text: string): string {
return text.substring(parserState.key, parserState.keyEnd);
}
/**
* Retrieves the last parsed `value` of style.
* @param text the text to substring the key from.
*/
export function getLastParsedValue(text: string): string {
return text.substring(parserState.value, parserState.valueEnd);
}
/**
* Initializes `className` string for parsing and parses the first token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
* @param text `className` to parse
* @returns index where the next invocation of `parseClassNameNext` should resume.
*/
export function parseClassName(text: string): number {
resetParserState(text);
return parseClassNameNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses next `className` token.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseClassName(text); i >= 0; i = parseClassNameNext(text, i)) {
* const key = getLastParsedKey();
* ...
* }
* ```
*
* @param text `className` to parse
* @param index where the parsing should resume.
* @returns index where the next invocation of `parseClassNameNext` should resume.
*/
export function parseClassNameNext(text: string, index: number): number {
const end = parserState.textEnd;
if (end === index) {
return -1;
}
index = parserState.keyEnd = consumeClassToken(text, (parserState.key = index), end);
return consumeWhitespace(text, index, end);
}
/**
* Initializes `cssText` string for parsing and parses the first key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
* ```
* @param text `cssText` to parse
* @returns index where the next invocation of `parseStyleNext` should resume.
*/
export function parseStyle(text: string): number {
resetParserState(text);
return parseStyleNext(text, consumeWhitespace(text, 0, parserState.textEnd));
}
/**
* Parses the next `cssText` key/values.
*
* This function is intended to be used in this format:
* ```
* for (let i = parseStyle(text); i >= 0; i = parseStyleNext(text, i))) {
* const key = getLastParsedKey();
* const value = getLastParsedValue();
* ...
* }
*
* @param text `cssText` to parse
* @param index where the parsing should resume.
* @returns index where the next invocation of `parseStyleNext` should resume.
*/
export function parseStyleNext(text: string, startIndex: number): number {
const end = parserState.textEnd;
let index = (parserState.key = consumeWhitespace(text, startIndex, end));
if (end === index) {
// we reached an end so just quit
return -1;
}
index = parserState.keyEnd = consumeStyleKey(text, index, end);
index = consumeSeparator(text, index, end, CharCode.COLON);
index = parserState.value = consumeWhitespace(text, index, end);
index = parserState.valueEnd = consumeStyleValue(text, index, end);
return consumeSeparator(text, index, end, CharCode.SEMI_COLON);
}
/**
* Reset the global state of the styling parser.
* @param text The styling text to parse.
*/
export function resetParserState(text: string): void {
parserState.key = 0;
parserState.keyEnd = 0;
parserState.value = 0;
parserState.valueEnd = 0;
parserState.textEnd = text.length;
}
/**
* Returns index of next non-whitespace character.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index of next non-whitespace character (May be the same as `start` if no whitespace at
* that location.)
*/
export function consumeWhitespace(text: string, startIndex: number, endIndex: number): number {
while (startIndex < endIndex && text.charCodeAt(startIndex) <= CharCode.SPACE) {
startIndex++;
}
return startIndex;
}
/**
* Returns index of last char in class token.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last char in class token.
*/
export function consumeClassToken(text: string, startIndex: number, endIndex: number): number {
while (startIndex < endIndex && text.charCodeAt(startIndex) > CharCode.SPACE) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all of the characters belonging to style key and token.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last style key character.
*/
export function consumeStyleKey(text: string, startIndex: number, endIndex: number): number {
let ch: number;
while (
startIndex < endIndex &&
((ch = text.charCodeAt(startIndex)) === CharCode.DASH ||
ch === CharCode.UNDERSCORE ||
((ch & CharCode.UPPER_CASE) >= CharCode.A && (ch & CharCode.UPPER_CASE) <= CharCode.Z) ||
(ch >= CharCode.ZERO && ch <= CharCode.NINE))
) {
startIndex++;
}
return startIndex;
}
/**
* Consumes all whitespace and the separator `:` after the style key.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after separator and surrounding whitespace.
*/
export function consumeSeparator(
text: string,
startIndex: number,
endIndex: number,
separator: number,
): number {
startIndex = consumeWhitespace(text, startIndex, endIndex);
if (startIndex < endIndex) {
if (ngDevMode && text.charCodeAt(startIndex) !== separator) {
malformedStyleError(text, String.fromCharCode(separator), startIndex);
}
startIndex++;
}
return startIndex;
}
/**
* Consumes style value honoring `url()` and `""` text.
*
* @param text Text to scan
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after last style value character.
*/ | {
"end_byte": 8031,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/styling_parser.ts"
} |
angular/packages/core/src/render3/styling/styling_parser.ts_8032_10678 | export function consumeStyleValue(text: string, startIndex: number, endIndex: number): number {
let ch1 = -1; // 1st previous character
let ch2 = -1; // 2nd previous character
let ch3 = -1; // 3rd previous character
let i = startIndex;
let lastChIndex = i;
while (i < endIndex) {
const ch: number = text.charCodeAt(i++);
if (ch === CharCode.SEMI_COLON) {
return lastChIndex;
} else if (ch === CharCode.DOUBLE_QUOTE || ch === CharCode.SINGLE_QUOTE) {
lastChIndex = i = consumeQuotedText(text, ch, i, endIndex);
} else if (
startIndex === i - 4 && // We have seen only 4 characters so far "URL(" (Ignore "foo_URL()")
ch3 === CharCode.U &&
ch2 === CharCode.R &&
ch1 === CharCode.L &&
ch === CharCode.OPEN_PAREN
) {
lastChIndex = i = consumeQuotedText(text, CharCode.CLOSE_PAREN, i, endIndex);
} else if (ch > CharCode.SPACE) {
// if we have a non-whitespace character then capture its location
lastChIndex = i;
}
ch3 = ch2;
ch2 = ch1;
ch1 = ch & CharCode.UPPER_CASE;
}
return lastChIndex;
}
/**
* Consumes all of the quoted characters.
*
* @param text Text to scan
* @param quoteCharCode CharCode of either `"` or `'` quote or `)` for `url(...)`.
* @param startIndex Starting index of character where the scan should start.
* @param endIndex Ending index of character where the scan should end.
* @returns Index after quoted characters.
*/
export function consumeQuotedText(
text: string,
quoteCharCode: number,
startIndex: number,
endIndex: number,
): number {
let ch1 = -1; // 1st previous character
let index = startIndex;
while (index < endIndex) {
const ch = text.charCodeAt(index++);
if (ch == quoteCharCode && ch1 !== CharCode.BACK_SLASH) {
return index;
}
if (ch == CharCode.BACK_SLASH && ch1 === CharCode.BACK_SLASH) {
// two back slashes cancel each other out. For example `"\\"` should properly end the
// quotation. (It should not assume that the last `"` is escaped.)
ch1 = 0;
} else {
ch1 = ch;
}
}
throw ngDevMode
? malformedStyleError(text, String.fromCharCode(quoteCharCode), endIndex)
: new Error();
}
function malformedStyleError(text: string, expecting: string, index: number): never {
ngDevMode && assertEqual(typeof text === 'string', true, 'String expected here');
throw throwError(
`Malformed style at location ${index} in string '` +
text.substring(0, index) +
'[>>' +
text.substring(index, index + 1) +
'<<]' +
text.slice(index + 1) +
`'. Expecting '${expecting}'.`,
);
} | {
"end_byte": 10678,
"start_byte": 8032,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/styling_parser.ts"
} |
angular/packages/core/src/render3/styling/style_binding_list.ts_0_6555 | /**
* @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 {KeyValueArray, keyValueArrayIndexOf} from '../../util/array_utils';
import {assertEqual, assertIndexInRange, assertNotEqual} from '../../util/assert';
import {assertFirstUpdatePass} from '../assert';
import {TNode} from '../interfaces/node';
import {
getTStylingRangeNext,
getTStylingRangePrev,
setTStylingRangeNext,
setTStylingRangeNextDuplicate,
setTStylingRangePrev,
setTStylingRangePrevDuplicate,
toTStylingRange,
TStylingKey,
TStylingKeyPrimitive,
TStylingRange,
} from '../interfaces/styling';
import {TData} from '../interfaces/view';
import {getTView} from '../state';
/**
* NOTE: The word `styling` is used interchangeably as style or class styling.
*
* This file contains code to link styling instructions together so that they can be replayed in
* priority order. The file exists because Ivy styling instruction execution order does not match
* that of the priority order. The purpose of this code is to create a linked list so that the
* instructions can be traversed in priority order when computing the styles.
*
* Assume we are dealing with the following code:
* ```
* @Component({
* template: `
* <my-cmp [style]=" {color: '#001'} "
* [style.color]=" #002 "
* dir-style-color-1
* dir-style-color-2> `
* })
* class ExampleComponent {
* static ngComp = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#001'});
* ɵɵstyleProp('color', '#002');
* ...
* }
* }
*
* @Directive({
* selector: `[dir-style-color-1]',
* })
* class Style1Directive {
* @HostBinding('style') style = {color: '#005'};
* @HostBinding('style.color') color = '#006';
*
* static ngDir = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#005'});
* ɵɵstyleProp('color', '#006');
* ...
* }
* }
*
* @Directive({
* selector: `[dir-style-color-2]',
* })
* class Style2Directive {
* @HostBinding('style') style = {color: '#007'};
* @HostBinding('style.color') color = '#008';
*
* static ngDir = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#007'});
* ɵɵstyleProp('color', '#008');
* ...
* }
* }
*
* @Directive({
* selector: `my-cmp',
* })
* class MyComponent {
* @HostBinding('style') style = {color: '#003'};
* @HostBinding('style.color') color = '#004';
*
* static ngComp = ... {
* ...
* // Compiler ensures that `ɵɵstyleProp` is after `ɵɵstyleMap`
* ɵɵstyleMap({color: '#003'});
* ɵɵstyleProp('color', '#004');
* ...
* }
* }
* ```
*
* The Order of instruction execution is:
*
* NOTE: the comment binding location is for illustrative purposes only.
*
* ```
* // Template: (ExampleComponent)
* ɵɵstyleMap({color: '#001'}); // Binding index: 10
* ɵɵstyleProp('color', '#002'); // Binding index: 12
* // MyComponent
* ɵɵstyleMap({color: '#003'}); // Binding index: 20
* ɵɵstyleProp('color', '#004'); // Binding index: 22
* // Style1Directive
* ɵɵstyleMap({color: '#005'}); // Binding index: 24
* ɵɵstyleProp('color', '#006'); // Binding index: 26
* // Style2Directive
* ɵɵstyleMap({color: '#007'}); // Binding index: 28
* ɵɵstyleProp('color', '#008'); // Binding index: 30
* ```
*
* The correct priority order of concatenation is:
*
* ```
* // MyComponent
* ɵɵstyleMap({color: '#003'}); // Binding index: 20
* ɵɵstyleProp('color', '#004'); // Binding index: 22
* // Style1Directive
* ɵɵstyleMap({color: '#005'}); // Binding index: 24
* ɵɵstyleProp('color', '#006'); // Binding index: 26
* // Style2Directive
* ɵɵstyleMap({color: '#007'}); // Binding index: 28
* ɵɵstyleProp('color', '#008'); // Binding index: 30
* // Template: (ExampleComponent)
* ɵɵstyleMap({color: '#001'}); // Binding index: 10
* ɵɵstyleProp('color', '#002'); // Binding index: 12
* ```
*
* What color should be rendered?
*
* Once the items are correctly sorted in the list, the answer is simply the last item in the
* concatenation list which is `#002`.
*
* To do so we keep a linked list of all of the bindings which pertain to this element.
* Notice that the bindings are inserted in the order of execution, but the `TView.data` allows
* us to traverse them in the order of priority.
*
* |Idx|`TView.data`|`LView` | Notes
* |---|------------|-----------------|--------------
* |...| | |
* |10 |`null` |`{color: '#001'}`| `ɵɵstyleMap('color', {color: '#001'})`
* |11 |`30 | 12` | ... |
* |12 |`color` |`'#002'` | `ɵɵstyleProp('color', '#002')`
* |13 |`10 | 0` | ... |
* |...| | |
* |20 |`null` |`{color: '#003'}`| `ɵɵstyleMap('color', {color: '#003'})`
* |21 |`0 | 22` | ... |
* |22 |`color` |`'#004'` | `ɵɵstyleProp('color', '#004')`
* |23 |`20 | 24` | ... |
* |24 |`null` |`{color: '#005'}`| `ɵɵstyleMap('color', {color: '#005'})`
* |25 |`22 | 26` | ... |
* |26 |`color` |`'#006'` | `ɵɵstyleProp('color', '#006')`
* |27 |`24 | 28` | ... |
* |28 |`null` |`{color: '#007'}`| `ɵɵstyleMap('color', {color: '#007'})`
* |29 |`26 | 30` | ... |
* |30 |`color` |`'#008'` | `ɵɵstyleProp('color', '#008')`
* |31 |`28 | 10` | ... |
*
* The above data structure allows us to re-concatenate the styling no matter which data binding
* changes.
*
* NOTE: in addition to keeping track of next/previous index the `TView.data` also stores prev/next
* duplicate bit. The duplicate bit if true says there either is a binding with the same name or
* there is a map (which may contain the name). This information is useful in knowing if other
* styles with higher priority need to be searched for overwrites.
*
* NOTE: See `should support example in 'tnode_linked_list.ts' documentation` in
* `tnode_linked_list_spec.ts` for working example.
*/
let __unused_const_as_closure_does_not_like_standalone_comment_blocks__: undefined;
/**
* Insert new `tStyleValue` at `TData` and link existing style bindings su | {
"end_byte": 6555,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/style_binding_list.ts"
} |
angular/packages/core/src/render3/styling/style_binding_list.ts_6557_12933 | that we maintain linked
* list of styles and compute the duplicate flag.
*
* Note: this function is executed during `firstUpdatePass` only to populate the `TView.data`.
*
* The function works by keeping track of `tStylingRange` which contains two pointers pointing to
* the head/tail of the template portion of the styles.
* - if `isHost === false` (we are template) then insertion is at tail of `TStylingRange`
* - if `isHost === true` (we are host binding) then insertion is at head of `TStylingRange`
*
* @param tData The `TData` to insert into.
* @param tNode `TNode` associated with the styling element.
* @param tStylingKey See `TStylingKey`.
* @param index location of where `tStyleValue` should be stored (and linked into list.)
* @param isHostBinding `true` if the insertion is for a `hostBinding`. (insertion is in front of
* template.)
* @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
* `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
*/
export function insertTStylingBinding(
tData: TData,
tNode: TNode,
tStylingKeyWithStatic: TStylingKey,
index: number,
isHostBinding: boolean,
isClassBinding: boolean,
): void {
ngDevMode && assertFirstUpdatePass(getTView());
let tBindings = isClassBinding ? tNode.classBindings : tNode.styleBindings;
let tmplHead = getTStylingRangePrev(tBindings);
let tmplTail = getTStylingRangeNext(tBindings);
tData[index] = tStylingKeyWithStatic;
let isKeyDuplicateOfStatic = false;
let tStylingKey: TStylingKeyPrimitive;
if (Array.isArray(tStylingKeyWithStatic)) {
// We are case when the `TStylingKey` contains static fields as well.
const staticKeyValueArray = tStylingKeyWithStatic as KeyValueArray<any>;
tStylingKey = staticKeyValueArray[1]; // unwrap.
// We need to check if our key is present in the static so that we can mark it as duplicate.
if (
tStylingKey === null ||
keyValueArrayIndexOf(staticKeyValueArray, tStylingKey as string) > 0
) {
// tStylingKey is present in the statics, need to mark it as duplicate.
isKeyDuplicateOfStatic = true;
}
} else {
tStylingKey = tStylingKeyWithStatic;
}
if (isHostBinding) {
// We are inserting host bindings
// If we don't have template bindings then `tail` is 0.
const hasTemplateBindings = tmplTail !== 0;
// This is important to know because that means that the `head` can't point to the first
// template bindings (there are none.) Instead the head points to the tail of the template.
if (hasTemplateBindings) {
// template head's "prev" will point to last host binding or to 0 if no host bindings yet
const previousNode = getTStylingRangePrev(tData[tmplHead + 1] as TStylingRange);
tData[index + 1] = toTStylingRange(previousNode, tmplHead);
// if a host binding has already been registered, we need to update the next of that host
// binding to point to this one
if (previousNode !== 0) {
// We need to update the template-tail value to point to us.
tData[previousNode + 1] = setTStylingRangeNext(
tData[previousNode + 1] as TStylingRange,
index,
);
}
// The "previous" of the template binding head should point to this host binding
tData[tmplHead + 1] = setTStylingRangePrev(tData[tmplHead + 1] as TStylingRange, index);
} else {
tData[index + 1] = toTStylingRange(tmplHead, 0);
// if a host binding has already been registered, we need to update the next of that host
// binding to point to this one
if (tmplHead !== 0) {
// We need to update the template-tail value to point to us.
tData[tmplHead + 1] = setTStylingRangeNext(tData[tmplHead + 1] as TStylingRange, index);
}
// if we don't have template, the head points to template-tail, and needs to be advanced.
tmplHead = index;
}
} else {
// We are inserting in template section.
// We need to set this binding's "previous" to the current template tail
tData[index + 1] = toTStylingRange(tmplTail, 0);
ngDevMode &&
assertEqual(
tmplHead !== 0 && tmplTail === 0,
false,
'Adding template bindings after hostBindings is not allowed.',
);
if (tmplHead === 0) {
tmplHead = index;
} else {
// We need to update the previous value "next" to point to this binding
tData[tmplTail + 1] = setTStylingRangeNext(tData[tmplTail + 1] as TStylingRange, index);
}
tmplTail = index;
}
// Now we need to update / compute the duplicates.
// Starting with our location search towards head (least priority)
if (isKeyDuplicateOfStatic) {
tData[index + 1] = setTStylingRangePrevDuplicate(tData[index + 1] as TStylingRange);
}
markDuplicates(tData, tStylingKey, index, true);
markDuplicates(tData, tStylingKey, index, false);
markDuplicateOfResidualStyling(tNode, tStylingKey, tData, index, isClassBinding);
tBindings = toTStylingRange(tmplHead, tmplTail);
if (isClassBinding) {
tNode.classBindings = tBindings;
} else {
tNode.styleBindings = tBindings;
}
}
/**
* Look into the residual styling to see if the current `tStylingKey` is duplicate of residual.
*
* @param tNode `TNode` where the residual is stored.
* @param tStylingKey `TStylingKey` to store.
* @param tData `TData` associated with the current `LView`.
* @param index location of where `tStyleValue` should be stored (and linked into list.)
* @param isClassBinding True if the associated `tStylingKey` as a `class` styling.
* `tNode.classBindings` should be used (or `tNode.styleBindings` otherwise.)
*/
function markDuplicateOfResidualStyling(
tNode: TNode,
tStylingKey: TStylingKey,
tData: TData,
index: number,
isClassBinding: boolean,
) {
const residual = isClassBinding ? tNode.residualClasses : tNode.residualStyles;
if (
residual != null /* or undefined */ &&
typeof tStylingKey == 'string' &&
keyValueArrayIndexOf(residual, tStylingKey) >= 0
) {
// We have duplicate in the residual so mark ourselves as duplicate.
tData[index + 1] = setTStylingRangeNextDuplicate(tData[index + 1] as TStylingRange);
}
}
/**
* Marks `TStyleValue`s as duplicates if another style binding in the list | {
"end_byte": 12933,
"start_byte": 6557,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/style_binding_list.ts"
} |
angular/packages/core/src/render3/styling/style_binding_list.ts_12935_18287 | as the same
* `TStyleValue`.
*
* NOTE: this function is intended to be called twice once with `isPrevDir` set to `true` and once
* with it set to `false` to search both the previous as well as next items in the list.
*
* No duplicate case
* ```
* [style.color]
* [style.width.px] <<- index
* [style.height.px]
* ```
*
* In the above case adding `[style.width.px]` to the existing `[style.color]` produces no
* duplicates because `width` is not found in any other part of the linked list.
*
* Duplicate case
* ```
* [style.color]
* [style.width.em]
* [style.width.px] <<- index
* ```
* In the above case adding `[style.width.px]` will produce a duplicate with `[style.width.em]`
* because `width` is found in the chain.
*
* Map case 1
* ```
* [style.width.px]
* [style.color]
* [style] <<- index
* ```
* In the above case adding `[style]` will produce a duplicate with any other bindings because
* `[style]` is a Map and as such is fully dynamic and could produce `color` or `width`.
*
* Map case 2
* ```
* [style]
* [style.width.px]
* [style.color] <<- index
* ```
* In the above case adding `[style.color]` will produce a duplicate because there is already a
* `[style]` binding which is a Map and as such is fully dynamic and could produce `color` or
* `width`.
*
* NOTE: Once `[style]` (Map) is added into the system all things are mapped as duplicates.
* NOTE: We use `style` as example, but same logic is applied to `class`es as well.
*
* @param tData `TData` where the linked list is stored.
* @param tStylingKey `TStylingKeyPrimitive` which contains the value to compare to other keys in
* the linked list.
* @param index Starting location in the linked list to search from
* @param isPrevDir Direction.
* - `true` for previous (lower priority);
* - `false` for next (higher priority).
*/
function markDuplicates(
tData: TData,
tStylingKey: TStylingKeyPrimitive,
index: number,
isPrevDir: boolean,
) {
const tStylingAtIndex = tData[index + 1] as TStylingRange;
const isMap = tStylingKey === null;
let cursor = isPrevDir
? getTStylingRangePrev(tStylingAtIndex)
: getTStylingRangeNext(tStylingAtIndex);
let foundDuplicate = false;
// We keep iterating as long as we have a cursor
// AND either:
// - we found what we are looking for, OR
// - we are a map in which case we have to continue searching even after we find what we were
// looking for since we are a wild card and everything needs to be flipped to duplicate.
while (cursor !== 0 && (foundDuplicate === false || isMap)) {
ngDevMode && assertIndexInRange(tData, cursor);
const tStylingValueAtCursor = tData[cursor] as TStylingKey;
const tStyleRangeAtCursor = tData[cursor + 1] as TStylingRange;
if (isStylingMatch(tStylingValueAtCursor, tStylingKey)) {
foundDuplicate = true;
tData[cursor + 1] = isPrevDir
? setTStylingRangeNextDuplicate(tStyleRangeAtCursor)
: setTStylingRangePrevDuplicate(tStyleRangeAtCursor);
}
cursor = isPrevDir
? getTStylingRangePrev(tStyleRangeAtCursor)
: getTStylingRangeNext(tStyleRangeAtCursor);
}
if (foundDuplicate) {
// if we found a duplicate, than mark ourselves.
tData[index + 1] = isPrevDir
? setTStylingRangePrevDuplicate(tStylingAtIndex)
: setTStylingRangeNextDuplicate(tStylingAtIndex);
}
}
/**
* Determines if two `TStylingKey`s are a match.
*
* When computing whether a binding contains a duplicate, we need to compare if the instruction
* `TStylingKey` has a match.
*
* Here are examples of `TStylingKey`s which match given `tStylingKeyCursor` is:
* - `color`
* - `color` // Match another color
* - `null` // That means that `tStylingKey` is a `classMap`/`styleMap` instruction
* - `['', 'color', 'other', true]` // wrapped `color` so match
* - `['', null, 'other', true]` // wrapped `null` so match
* - `['', 'width', 'color', 'value']` // wrapped static value contains a match on `'color'`
* - `null` // `tStylingKeyCursor` always match as it is `classMap`/`styleMap` instruction
*
* @param tStylingKeyCursor
* @param tStylingKey
*/
function isStylingMatch(tStylingKeyCursor: TStylingKey, tStylingKey: TStylingKeyPrimitive) {
ngDevMode &&
assertNotEqual(
Array.isArray(tStylingKey),
true,
"Expected that 'tStylingKey' has been unwrapped",
);
if (
tStylingKeyCursor === null || // If the cursor is `null` it means that we have map at that
// location so we must assume that we have a match.
tStylingKey == null || // If `tStylingKey` is `null` then it is a map therefor assume that it
// contains a match.
(Array.isArray(tStylingKeyCursor) ? tStylingKeyCursor[1] : tStylingKeyCursor) === tStylingKey // If the keys match explicitly than we are a match.
) {
return true;
} else if (Array.isArray(tStylingKeyCursor) && typeof tStylingKey === 'string') {
// if we did not find a match, but `tStylingKeyCursor` is `KeyValueArray` that means cursor has
// statics and we need to check those as well.
return keyValueArrayIndexOf(tStylingKeyCursor, tStylingKey) >= 0; // see if we are matching the key
}
return false;
}
| {
"end_byte": 18287,
"start_byte": 12935,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/styling/style_binding_list.ts"
} |
angular/packages/core/src/render3/i18n/i18n.md_0_1401 | # I18N translation support
Templates can be marked as requiring translation support via `i18n` and `i18n-...` attributes on elements.
Translation support involves mapping component template contents to **i18n messages**, which may contain interpolations, DOM elements and sub-templates.
This document describes how this support is implemented in Angular templates.
## Example of i18n message
The following component definition illustrates how i18n works in Angular:
```typescript
@Component({
template: `
<div i18n-title title="Hello {{name}}!" i18n>
{{count}} is rendered as:
<b *ngIf="exp">
{ count, plural,
=0 {no <b title="none">emails</b>!}
=1 {one <i>email</i>}
other {{{count}} <span title="{{count}}">emails</span>}
}
</b>.
</div>
`
})
class MyComponent {
}
```
NOTE:
- There are only two kinds of i18n messages:
1. In the text of an attribute (e.g. `title` of `<div i18n-title title="Hello {{name}}!">`, indicated by the presence of the `i18n-title` attribute).
2. In the body of an element (e.g. `<div i18n>` indicated by the presence of the `i18n` attribute).
- The body of an element marked with `i18n` can contain internal DOM structure (e.g. other DOM elements).
- The internal structure of such an element may even contain Angular sub-templates (e.g. `ng-container` or `*ngFor` directives).
| {
"end_byte": 1401,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md"
} |
angular/packages/core/src/render3/i18n/i18n.md_1401_8136 | ## Implementation overview
- i18n messages must preserve the DOM structure in elements marked with `i18n` because those DOM structures may have components and directives.
- **Parsed i18n messages** must live in `TView.data`. This is because in case of SSR we need to be able to execute multiple locales in the same VM.
(If parsed i18n messages are only at the top level we could not have more than one locale.)
The plan is to cache `TView.data` per locale, hence different instructions would get cached into different `TView.data` associated with a given locale.
- NOTE: in SSR `goog.getMsg` will return an object literal of all of the locale translations.
### Generated code
Given the example component above, the Angular template compiler generates the following Ivy rendering instructions.
```typescript
// These i18n messages need to be retrieved from a "localization service", described later.
const MSG_title = 'Hello �0�!';
const MSG_div_attr = ['title', MSG_title];
const MSG_div = `�0� is rendered as: �*3:1��#1:1�{�0:1�, plural,
=0 {no <b title="none">emails</b>!}
=1 {one <i>email</i>}
other {�0:1� <span title="�0:1�">emails</span>}
}�/#1:1��/*3:1�.`;
function MyComponent_NgIf_Template_0(rf: RenderFlags, ctx: any) {
if (rf & RenderFlags.Create) {
i18nStart(0, MSG_div, 1);
element(1, 'b');
i18nEnd();
}
if (rf & RenderFlags.Update) {
i18nExp(ctx.count); // referenced by `�0:1�`
i18nApply(0);
}
}
class MyComponent {
static ɵcmp = defineComponent({
...,
template: function(rf: RenderFlags, ctx: MyComponent) {
if (rf & RenderFlags.Create) {
elementStart(0, 'div');
i18nAttributes(1, MSG_div_attr);
i18nStart(2, MSG_div);
template(3, MyComponent_NgIf_Template_0, ...);
i18nEnd();
elementEnd();
}
if (rf & RenderFlags.Update) {
i18nExp(ctx.name); // referenced by `�0�` in `MSG_title`
i18nApply(1); // Updates the `i18n-title` binding
i18nExp(ctx.count); // referenced by `�0�` in `MSG_div`
i18nApply(2); // Updates the `<div i18n>...</div>`
}
}
});
}
```
### i18n markers (�...�)
Each i18n message contains **i18n markers** (denoted by `�...�`) which tell the renderer how to map the translated text onto the renderer instructions.
The [�](https://www.fileformat.info/info/unicode/char/fffd/index.htm) character was chosen because it is extremely unlikely to collide with existing text, and because it is generated, the developer should never encounter it.
Each i18n marker contains an `index` (and optionally a `block`) which provide binding information for the marker.
The i18n markers are:
- `�{index}(:{block})�`: *Binding placeholder*: Marks a location where an interpolated expression will be rendered.
- `index`: the index of the binding within this i18n message block.
- `block` (*optional*): the index of the sub-template block, in which this placeholder was declared.
- `�#{index}(:{block})� ... �/#{index}(:{block})�`: *Element block*: Marks the beginning and end of a DOM element that is embedded in the original translation string.
- `index`: the index of the element, as defined in the template instructions (e.g. `elementStart(index, ...)`).
- `block` (*optional*): the index of the sub-template block, in which this element was declared.
- `�*{index}:{block}�`/`�/*{index}:{block}�`: *Sub-template block*: Marks a sub-template block that is translated separately in its own angular template function.
- `index`: the index of the `template` instruction, as defined in the template instructions (e.g. `template(index, ...)`).
- `block`: the index of the parent sub-template block, in which this child sub-template block was declared.
No other i18n marker format is supported.
The i18n markers in the example above can be interpreted as follows:
```typescript
const MSG_title = 'Hello �0�!';
const MSG_div_attr = ['title', MSG_title];
const MSG_div = `�0� is rendered as: �*3:1��#1:1�{�0:1�, plural,
=0 {no <b title="none">emails</b>!}
=1 {one <i>email</i>}
other {�0:1� <span title="�0:1�">emails</span>}
}�/#1:1��/*3:1�.`;
```
- `�0�`: the `{{name}}` interpolated expression with index 0.
- `�*3:1�`: the start of the `*ngIf` template with index 3, effectively defining sub-template block 1.
- `�/*3:1�`: the end of the `*ngIf` template with index 3 (sub-template block 1).
- `�#1:1�`: the start of the `<b>` element with index 1, found inside sub-template block 1.
- `�/#1:1�`: the end of the `</b>` element with index 1, found inside sub-template block 1.
- `�0:1�`: the binding expression `count` (both as the parameter `count` for the `plural` ICU and as the `{{count}}` interpolation) with index 0, found inside sub-template block 1.
NOTE:
- Each closing i18n marker has the same information as its opening i18n marker.
This is so that the parser can verify that opening and closing i18n markers are properly nested.
Failure to properly nest the i18n markers implies that the translator changed the order of translation incorrectly and should be a runtime error.
- The optional `block` index is added to i18n markers contained within sub-template blocks.
This is because blocks must be properly nested and it is an error for the translator to move an i18n marker outside of its block. This will result in runtime error.
- i18n markers are unique within the translation string in which they are found.
### Rendering i18n messages
i18n messages are rendered by concatenating each piece of the string using an accumulator.
The pieces to be concatenated may be a substring from the i18n message or an index to a binding.
This is best explained through pseudo code:
```typescript
function render18nString(i18nStringParts: string|number) {
const accumulator:string[] = [];
i18nStringParts.forEach(part => accumulate(part));
return accumulatorFlush(sanitizer);
/**
* Collect intermediate interpolation values.
*/
function accumulate(value: string|number): void {
if (typeof value == 'number') {
// if the value is a number then look it up in previous `i18nBind` location.
value = lviewData[bindIndex + value];
}
accumulator.push(stringify(value));
}
/**
* Flush final interpolation value.
*/
function accumulatorFlush(sanitizer: null|((text: string)=>string) = null): string {
let interpolation = accumulator.join('');
if (sanitizer != null) {
interpolation = sanitizer(interpolation);
}
accumulator.length = 0;
return interpolation;
}
}
```
## i18n Attributes
Rendering i18n attributes is straightforward:
```html
<div i18n-title title="Hello {{name}}!">
```
The template compi | {
"end_byte": 8136,
"start_byte": 1401,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md"
} |
angular/packages/core/src/render3/i18n/i18n.md_8136_9717 | ler will generate the following statements inside the `RenderFlags.Create` block.
```typescript
const MSG_title = 'Hello �0�!';
const MSG_div_attr = ['title', MSG_title];
elementStart(0, 'div');
i18nAttributes(1, MSG_div_attr);
```
The `i18nAttributes()` instruction checks the `TView.data` cache at position `1` and if empty will create `I18nUpdateOpCodes` like so:
```typescript
const i18nUpdateOpCodes = <I18nUpdateOpCodes>[
// The following OpCodes represent: `<div i18n-title title="Hello �0�!">`
// If `changeMask & 0b1`
// has changed then execute update OpCodes.
// has NOT changed then skip `7` values and start processing next OpCodes.
0b1, 7,
// Concatenate `newValue = 'Hello ' + lView[bindIndex-1] + '!';`.
'Hello ', // accumulate('Hello ');
-1, // accumulate(-1);
'!', // accumulate('!');
// Update attribute: `elementAttribute(0, 'title', accumulatorFlush(null));`
// NOTE: `null` means don't sanitize
0 << SHIFT_REF | Attr, 'title', null,
]
```
NOTE:
- The `i18nAttributes()` instruction updates the attributes of the "previous" element.
- Each attribute to be translated is provided as a pair of elements in the array passed to the `i18nAttributes()` instruction (e.g. `['title', MSG_title, 'src', MSG_src, ...]`).
- Even attributes that don't have bindings must go through `i18nAttributes()` so that they correctly work with i18n in a server environment.
## i18n Elements
Rendering i18n elements is more complicated but follows the same philosophy as attributes, with additional i18n markers.
```html | {
"end_byte": 9717,
"start_byte": 8136,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.