_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/core/src/render3/i18n/i18n.md_9717_15555
<div 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> ``` The template compiler generates the following i18n message: ```typescript // This message is retrieved from a "localization service" described later 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�.`; ``` ### Sub-template blocks Most i18n translated elements do not have sub-templates (e.g. `*ngIf`), but where they do the i18n message describes a **sub-template block** defined by `�*{index}:{block}�` and `�/*{index}:{block}�` markers. The sub-template block is extracted from the translation so it is as if there are two separate translated strings for parent and sub-template. Consider the following nested template: ```html <div i18n> List: <ul *ngIf="..."> <li *ngFor="...">item</li> </ul> Summary: <span *ngIf=""></span> </div> ``` The template compiler will generate the following translated string and instructions: ```typescript // The string split across lines to allow addition of comments. The generated code does not have comments. const MSG_div = 'List: ' + '�*2:1�' + // template(2, MyComponent_NgIf_Template_0, ...); '�#1:1�' + // elementStart(1, 'ul'); '�*2:2�' + // template(2, MyComponent_NgIf_NgFor_Template_1, ...); '�#1:2�' + // element(1, 'li'); 'item' + '�/#1:2�' + '�/*2:2�' + '�/#1:1�' + '�/*2:1�' + 'Summary: ' + '�*3:3�' + // template(3, MyComponent_NgIf_Template_2, ...); '�#1:3�' + // element(1, 'span'); '�/#1:3�' + '�/*3:3�'; // �*2:2� ... �/*2:2� (`*ngFor` template, instruction index 2, inside the `*ngIf` template, sub-template block 1) function MyComponent_NgIf_NgFor_Template_1(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { i18nStart(0, MSG_div, 2); // 2nd `*` content: `�#1:2�item�/#1:2�` element(1, 'li'); i18nEnd(); } ... } // �*2:1� ... �/*2:1� function MyComponent_NgIf_Template_0(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { i18nStart(0, MSG_div, 1); // 1st `*` content: `�#1:1��*2:2��/*2:2��/#1:1�` elementStart(1, 'ul'); template(2, MyComponent_NgIf_NgFor_Template_1, ...); elementEnd(); i18nEnd(); } ... } // �*3:3� ... �/*3:3� function MyComponent_NgIf_Template_2(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { i18nStart(0, MSG_div, 3); // 3rd `*` content: `�#1:3��/#1:3�` element(1, 'span'); i18nEnd(); } ... } class MyComponent { static ɵcmp = defineComponent({ ..., template: function(rf: RenderFlags, ctx: MyComponent) { if (rf & RenderFlags.Create) { elementStart(0, 'div'); // Outer content: `List : �*2:1��/*2:1�Summary: �*3:3��/*3:3�` i18nStart(1, MSG_div); template(2, MyComponent_NgIf_Template_0, ...); template(3, MyComponent_NgIf_Template_2, ...); i18nEnd(); elementEnd(); } ... } }); } ``` ### `i18nStart` It is the job of the instruction `i18nStart` to parse the i18n message and to provide the appropriate text to each of the following instructions. Note: - Inside a block that is marked with `i18n` the DOM element instructions are retained, but the text instructions have been stripped. ```typescript i18nStart( 2, // storage of the parsed message instructions MSG_div, // The i18n message to parse which has been translated // Optional sub-template block index. Empty implies `0` (most common) ); ... i18nEnd(); // The instruction which is responsible for inserting text nodes into // the render tree based on translation. ``` The `i18nStart` generates these instructions which are cached in the `TView` and then processed by `i18nEnd`. ```typescript const tI18n = <TI18n>{ vars: 2, // Number of slots to allocate in EXPANDO. expandoStartIndex: 100, // Assume in this example EXPANDO starts at 100 create: <I18nMutateOpCodes>[ // Processed by `i18nEnd` // Equivalent to: // // Assume expandoIndex = 100; // const node = lView[expandoIndex++] = document.createTextNode(''); // lView[2].insertBefore(node, lView[3]); "", 2 << SHIFT_PARENT | 3 << SHIFT_REF | InsertBefore, // Equivalent to: // // Assume expandoIndex = 101; // const node = lView[expandoIndex++] = document.createTextNode('.'); // lView[0].appendChild(node); '.', 2 << SHIFT_PARENT | AppendChild, ], update: <I18nUpdateOpCodes>[ // Processed by `i18nApply` // Header which consists of change mask and block size. // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `3` values and start processing next OpCodes. 0b1, 3, -1, // accumulate(-1); 'is rendered as: ', // accumulate('is rendered as: '); // Flush the concatenated string to text node at position 100. 100 << SHIFT_REF | Text, // lView[100].textContent = accumulatorFlush(); ], icus: null, } ``` NOTE: - position `2` has `i18nStart` and so it is not a real DOM element, but it should act as if it was a DOM element. ### `i18nStart` in sub-template blocks ```typescript i18nStart( 0, // storage of the parsed message instructions MSG_div, // The message to parse which has been translated 1 // Optional sub-template (block) index. ); ``` Notice that in sub-template the `i18nStart` inst
{ "end_byte": 15555, "start_byte": 9717, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_15555_16626
ruction takes `1` as the last argument. This means that the instruction has to extract out 1st sub-block from the root-template translation. Starting with ```typescript 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�.`; ``` The `i18nStart` instruction traverses `MSG_div` and looks for 1st sub-template block marked with `�*3:1�`. Notice that the `�*3:1�` contains index to the DOM element `3`. The rest of the code should work same as described above. This case is more complex because it contains an ICU. ICUs are pre-parsed and then stored in the `TVIEW.data` as follows. ```typescript const tI18n = <TI18n>{ vars: 3 + Math.max(4, 3, 3), // Number of slots to allocate in EXPANDO. (Max of all ICUs + fixed) expandoStartIndex: 200, // Assume in this example EXPANDO starts at 200 create: <I18nMutateOpCodes>[ // Equivalent to: // // Assume expandoIndex = 200; // const node
{ "end_byte": 16626, "start_byte": 15555, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_16627_23807
= lView[expandoIndex++] = document.createComment(''); // lView[1].appendChild(node); ICU_MARKER, '', 1 << SHIFT_PARENT | AppendChild, ], update: <I18nUpdateOpCodes>[ // The following OpCodes represent: `<b>{count, plural, ... }</b>">` // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `2` values and start processing next OpCodes. 0b1, 2, -1, // accumulate(-1); // Switch ICU: `icuSwitchCase(lView[200 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/, accumulatorFlush());` 200 << SHIFT_REF | 0 << SHIFT_ICU | IcuSwitch, // NOTE: the bit mask here is the logical OR of all of the masks in the ICU. 0b1, 1, // Update ICU: `icuUpdateCase(lView[200 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/);` // SHIFT_REF: points to: `i18nStart(0, MSG_div, 1);` // SHIFT_ICU: is an index into which ICU is being updated. In our example we only have // one ICU so it is 0-th ICU to update. 200 << SHIFT_REF | 0 << SHIFT_ICU | IcuUpdate, ], icus: [ <TIcu>{ cases: [0, 1, 'other'], vars: [4, 3, 3], expandoStartIndex: 203, // Assume in this example EXPANDO starts at 203 childIcus: [], create: [ // Case: `0`: `{no <b title="none">emails</b>!}` <I18nMutateOpCodes>[ // // assume expandoIndex == 203 // const node = lView[expandoIndex++] = document.createTextNode('no '); // lView[1].appendChild(node); 'no ', 1 << SHIFT_PARENT | AppendChild, // Equivalent to: // // assume expandoIndex == 204 // const node = lView[expandoIndex++] = document.createElement('b'); // lView[1].appendChild(node); ELEMENT_MARKER, 'b', 1 << SHIFT_PARENT | AppendChild, // const node = lView[204]; // node.setAttribute('title', 'none'); 204 << SHIFT_REF | Select, 'title', 'none' // // assume expandoIndex == 205 // const node = lView[expandoIndex++] = document.createTextNode('email'); // lView[1].appendChild(node); 'email', 204 << SHIFT_PARENT | AppendChild, ] // Case: `1`: `{one <i>email</i>}` <I18nMutateOpCodes>[ // // assume expandoIndex == 203 // const node = lView[expandoIndex++] = document.createTextNode('no '); // lView[1].appendChild(node, lView[2]); 'one ', 1 << SHIFT_PARENT | AppendChild, // Equivalent to: // // assume expandoIndex == 204 // const node = lView[expandoIndex++] = document.createElement('b'); // lView[1].appendChild(node); ELEMENT_MARKER, 'i', 1 << SHIFT_PARENT | AppendChild, // // assume expandoIndex == 205 // const node = lView[expandoIndex++] = document.createTextNode('email'); // lView[1].appendChild(node); 'email', 204 << SHIFT_PARENT | AppendChild, ] // Case: `"other"`: `{�0� <span title="�0�">emails</span>}` <I18nMutateOpCodes>[ // // assume expandoIndex == 203 // const node = lView[expandoIndex++] = document.createTextNode(''); // lView[1].appendChild(node); '', 1 << SHIFT_PARENT | AppendChild, // Equivalent to: // // assume expandoIndex == 204 // const node = lView[expandoIndex++] = document.createComment('span'); // lView[1].appendChild(node); ELEMENT_MARKER, 'span', 1 << SHIFT_PARENT | AppendChild, // // assume expandoIndex == 205 // const node = lView[expandoIndex++] = document.createTextNode('emails'); // lView[1].appendChild(node); 'emails', 204 << SHIFT_PARENT | AppendChild, ] ], remove: [ // Case: `0`: `{no <b title="none">emails</b>!}` <I18nMutateOpCodes>[ // lView[1].remove(lView[203]); 1 << SHIFT_PARENT | 203 << SHIFT_REF | Remove, // lView[1].remove(lView[204]); 1 << SHIFT_PARENT | 204 << SHIFT_REF | Remove, ] // Case: `1`: `{one <i>email</i>}` <I18nMutateOpCodes>[ // lView[1].remove(lView[203]); 1 << SHIFT_PARENT | 203 << SHIFT_REF | Remove, // lView[1].remove(lView[204]); 1 << SHIFT_PARENT | 204 << SHIFT_REF | Remove, ] // Case: `"other"`: `{�0� <span title="�0�">emails</span>}` <I18nMutateOpCodes>[ // lView[1].remove(lView[203]); 1 << SHIFT_PARENT | 203 << SHIFT_REF | Remove, // lView[1].remove(lView[204]); 1 << SHIFT_PARENT | 204 << SHIFT_REF | Remove, ] ], update: [ // Case: `0`: `{no <b title="none">emails</b>!}` <I18nUpdateOpCodes>[ // no bindings ] // Case: `1`: `{one <i>email</i>}` <I18nUpdateOpCodes>[ // no bindings ] // Case: `"other"`: `{�0� <span title="�0�">emails</span>}` <I18nUpdateOpCodes>[ // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `5` values and start processing next OpCodes. 0b1, 5, -1, // accumulate(-1); ' ', // accumulate(' '); // Update attribute: `lviewData[203].textValue = accumulatorFlush();` 203 << SHIFT_REF | Text, // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `4` values and start processing next OpCodes. 0b1, 4, // Concatenate `newValue = '' + lView[bindIndex -1];`. -1, // accumulate(-1); // Update attribute: `lView[204].setAttribute(204, 'title', 0b1, 2,(null));` // NOTE: `null` implies no sanitization. 204 << SHIFT_REF | Attr, 'title', null ] ] } ] } ``` ## Sanitization Any text coming from translators is considered safe and has no sanitization applied to it. (This is why create blocks don't need sanitization) Any text coming from user (interpolation of bindings to attributes) are consider unsafe and may need to be passed through sanitizer if the attribute is considered dangerous. For this reason the update OpCodes of attributes take sanitization function as part of the attribute update. If the sanitization function is present then we pass the interpolated value to the sanitization function before assigning the result to the attribute. During the parsing of the translated text the parser determines if the attribute is potentially dangerous and if it contains user interpolation, if so it adds an appropriate sanitization function. ## Computing the expando positions Assume we have translation like so: `<div i18n>Hello {{name}}!</div>`. The above calls generates the following template instruction code: ```typescript // This message will be retrieved from some localization service described later const MSG_div = 'Hello �0�!'; template: function(rf: RenderFlags, ctx: MyComponent) { if (rf & Rend
{ "end_byte": 23807, "start_byte": 16627, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_23807_30019
erFlags.Create) { elementStart(0, 'div'); i18nStart(1, MSG_div); i18nEnd(); elementEnd(); } if (rf & RenderFlags.Update) { i18nExp(ctx.count); i18nApply(1); } } ``` This requires that the `i18nStart` instruction generates the OpCodes for creation as well as update. The OpCodes require that offsets for the EXPANDO index for the reference. The question is how do we compute this: ```typescript const tI18n = <TI18n>{ vars: 1, expandoStartIndex: 100, // Retrieved from `tView.blueprint.length` at i18nStart invocation. create: <I18nMutateOpCodes>[ // let expandoIndex = this.expandoStartIndex; // Initialize // const node = document.createTextNode(''); // if (first_execution_for_tview) { // ngDevMode && assertEquals(tView.blueprint.length, expandoIndex); // tView.blueprint.push(null); // ngDevMode && assertEquals(lView.length, expandoIndex); // lView.push(node); // } else { // lView[expandoIndex] = node; // save expandoIndex == 100; // } // lView[0].appendChild(node); // expandoIndex++; "", 0 << SHIFT_PARENT | AppendChild, ], update: <I18nUpdateOpCodes>[ 0b1, 3, 'Hello ', -1, '!', // The `100` position refers to empty text node created above. 100 << SHIFT_REF | Text, ], } ``` ## ICU in attributes bindings Given an i18n component: ```typescript @Component({ template: ` <div i18n-title title="You have { count, plural, =0 {no emails} =1 {one email} other {{{count}} emails} }."> </div> ` }) class MyComponent { } ``` The compiler generates: ```typescript // These messages need to be retrieved from some localization service described later const MSG_title = `You have {�0�, plural, =0 {no emails} =1 {one email} other {�0� emails} }.`; const MSG_div_attr = ['title', MSG_title, optionalSanitizerFn]; class MyComponent { static ɵcmp = defineComponent({ ..., template: function(rf: RenderFlags, ctx: MyComponent) { if (rf & RenderFlags.Create) { elementStart(0, 'div'); i18nAttributes(1, MSG_div_attr); elementEnd(); } if (rf & RenderFlags.Update) { i18nExp(ctx.count); // referenced by `�0�` i18nApply(1); // Updates the `i18n-title` binding } } }); } ``` The rules for attribute ICUs should be the same as for normal ICUs. For this reason we would like to reuse as much code as possible for parsing and processing of the ICU for simplicity and consistency. ```typescript const tI18n = <TI18n>{ vars: 0, // Number of slots to allocate in EXPANDO. (Max of all ICUs + fixed) expandoStartIndex: 200, // Assume in this example EXPANDO starts at 200 create: <I18nMutateOpCodes>[ // attributes have no create block ], update: <I18nUpdateOpCodes>[ // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `2` values and start processing next OpCodes. 0b1, 2, -1, // accumulate(-1) // Switch ICU: `icuSwitchCase(lView[200 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/, accumulatorFlush());` 200 << SHIFT_REF | 0 << SHIFT_ICU | IcuSwitch, // NOTE: the bit mask here is the logical OR of all of the masks in the ICU. 0b1, 4, 'You have ', // accumulate('You have '); // Update ICU: `icuUpdateCase(lView[200 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/);` // SHIFT_REF: points to: `i18nStart(0, MSG_div, 1);` // SHIFT_ICU: is an index into which ICU is being updated. In our example we only have // one ICU so it is 0-th ICU to update. 200 << SHIFT_REF | 0 << SHIFT_ICU | IcuUpdate, '.', // accumulate('.'); // Update attribute: `elementAttribute(1, 'title', accumulatorFlush(null));` // NOTE: `null` means don't sanitize 1 << SHIFT_REF | Attr, 'title', null, ], icus: [ <TIcu>{ cases: [0, 1, 'other'], vars: [0, 0, 0], expandoStartIndex: 200, // Assume in this example EXPANDO starts at 200 childIcus: [], create: [ // Case: `0`: `{no emails}` <I18nMutateOpCodes>[ ] // Case: `1`: `{one email}` <I18nMutateOpCodes>[ ] // Case: `"other"`: `{�0� emails}` <I18nMutateOpCodes>[ ] ], remove: [ // Case: `0`: `{no emails}` <I18nMutateOpCodes>[ ] // Case: `1`: `{one email}` <I18nMutateOpCodes>[ ] // Case: `"other"`: `{�0� emails}` <I18nMutateOpCodes>[ ] ], update: [ // Case: `0`: `{no emails}` <I18nMutateOpCodes>[ // If `changeMask & -1` // always true // has changed then execute update OpCodes. // has NOT changed then skip `1` values and start processing next OpCodes. -1, 1, 'no emails', // accumulate('no emails'); ] // Case: `1`: `{one email}` <I18nMutateOpCodes>[ // If `changeMask & -1` // always true // has changed then execute update OpCodes. // has NOT changed then skip `1` values and start processing next OpCodes. -1, 1, 'one email', // accumulate('no emails'); ] // Case: `"other"`: `{�0� emails}` <I18nMutateOpCodes>[ // If `changeMask & -1` // always true // has changed then execute update OpCodes. // has NOT changed then skip `1` values and start processing next OpCodes. -1, 2, -1, // accumulate(lView[bindIndex-1]); 'emails', // accumulate('no emails'); ] ] } ] } ``` ## ICU Parsing ICUs need to be parsed, and they may contain HTML. First part of ICU parsing is breaking down the ICU into cases. Given ``` {�0�, plural, =0 {no <b title="none">emails</b>!} =1 {one <i>email</i>} other {�0� <span title="�0�">emails</span>} } ``` The above needs to be parsed into: ```TypeScript const icu = { type: 'plural', // or 'select' expressionBindingIndex
{ "end_byte": 30019, "start_byte": 23807, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_30019_33508
: 0, // from �0�, cases: [ 'no <b title="none">emails</b>!', 'one <i>email</i>', '�0� <span title="�0�">emails</span>', ] } ``` Once the ICU is parsed into its components it needs to be translated into OpCodes. The translation from the `case` to OpCode depends on whether the ICU is located in DOM or in attribute. Attributes OpCode generation is simple since it only requires breaking the string at placeholder boundaries and generating a single attribute update OpCode with interpolation. (See ICUs and Attributes for discussion of how ICUs get updated with attributes) The DOM mode is more complicated as it may involve creation of new DOM elements. 1. Create a temporary `<div>` element. 2. `innerHTML` the `case` into the `<div>` element. 3. Walk the `<div>`: 1. If Text node create OpCode to create/destroy the text node. - If Text node with placeholders then also create update OpCode for updating the interpolation. 2. If Element node create OpCode to create/destroy the element node. 3. If Element has attributes create OpCode to create the attributes. - If attribute has placeholders than create update instructions for the attribute. The above should generate create, remove, and update OpCodes for each of the case. NOTE: The updates to attributes with placeholders require that we go through sanitization. ## Translation without top level element Placing `i18n` attribute on an existing elements is easy because the element defines parent and the translated element can be inserted synchronously. For virtual elements such as `<ng-container>` or `<ng-template>` this is more complicated because there is no common root element to insert into. In such a case the `i18nStart` acts as the element to insert into. This is similar to `<ng-container>` behavior. Example: ```html <ng-template i18n>Translated text</ng-template> ``` Would generate: ```typescript const MSG_text = 'Translated text'; function MyComponent_Template_0(rf: RenderFlags, ctx: any) { if (rf & RenderFlags.Create) { i18nStart(0, MSG_text, 1); i18nEnd(); } ... } ``` Which would get parsed into: ```typescript const tI18n = <TI18n>{ vars: 2, // Number of slots to allocate in EXPANDO. expandoStartIndex: 100, // Assume in this example EXPANDO starts at 100 create: <I18nMutateOpCodes>[ // Processed by `i18nEnd` // Equivalent to: // const node = lView[expandoIndex++] = document.createTextNode(''); // lView[0].insertBefore(node, lView[3]); "Translated text", 0 << SHIFT_PARENT | AppendChild, ], update: <I18nUpdateOpCodes>[ ], icus: null, } ``` RESOLVE: - One way we could solve it is by `i18nStart` would store an object in `LView` at its position which would implement `RNode` but which would handle the corner case of inserting into a synthetic parent. - Another way this could be implemented is for `i18nStore` to leave a marker in the `LView` which would tell the OpCode processor that it is dealing with a synthetic parent. ## Nested ICUs ICU can have other ICUs embedded in them. Given: ```typescript @Component({ template: ` {count, plural, =0 {zero} other {{{count}} {animal, select, cat {cats} dog {dogs} other {animals} }! } } ` }) class MyComponent { count: number; animal: string; } ``` Will generate: ```typesc
{ "end_byte": 33508, "start_byte": 30019, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_33508_40057
ript const MSG_nested = ` {�0�, plural, =0 {zero} other {�0� {�1�, select, cat {cats} dog {dogs} other {animals} }! } } `; class MyComponent { count: number; animal: string; static ɵcmp = defineComponent({ ..., template: function(rf: RenderFlags, ctx: MyComponent) { if (rf & RenderFlags.Create) { i18nStart(0, MSG_nested); i18nEnd(); } if (rf & RenderFlags.Update) { i18nExp(ctx.count); // referenced by `�0�` i18nExp(ctx.animal); // referenced by `�1�` i18nApply(0); } } }); } ``` The way to think about is that the sub-ICU is replaced with comment node and then the rest of the system works as normal. The main ICU writes out the comment node which acts like an anchor for the sub-ICU. The sub-ICU uses the comment node as a parent and writes its data there. NOTE: - Because more than one ICU is active at the time the system needs to take that into account when allocating the expando instructions. The internal data structure will be: ```typescript const tI18n = <TI18n>{ vars: 2, // Number of slots to allocate in EXPANDO. expandoStartIndex: 100, // Assume in this example EXPANDO starts at 100 create: <I18nMutateOpCodes>[ // Processed by `i18nEnd` ], update: <I18nUpdateOpCodes>[ // Processed by `i18nApply` // The following OpCodes represent: `<b>{count, plural, ... }</b>">` // If `changeMask & 0b1` // has changed then execute update OpCodes. // has NOT changed then skip `2` values and start processing next OpCodes. 0b1, 2, -1, // accumulate(-1); // Switch ICU: `icuSwitchCase(lView[100 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/, accumulatorFlush());` 100 << SHIFT_REF | 0 << SHIFT_ICU | IcuSwitch, // NOTE: the bit mask here is the logical OR of all of the masks in the ICU. 0b1, 1, // Update ICU: `icuUpdateCase(lView[100 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/);` // SHIFT_REF: points to: `i18nStart(0, MSG_div, 1);` // SHIFT_ICU: is an index into which ICU is being updated. In our example we only have // one ICU so it is 0-th ICU to update. 100 << SHIFT_REF | 0 << SHIFT_ICU | IcuUpdate, ], icus: [ <TIcu>{ // {�0�, plural, =0 {zero} other {�0� <!--subICU-->}} cases: [0, 'other'], childIcus: [[1]], // pointer to child ICUs. Needed to properly clean up. vars: [1, 2], expandoStartIndex: 100, // Assume in this example EXPANDO starts at 100 create: [ <I18nMutateOpCodes>[ // Case: `0`: `{zero}` 'zero ', 1 << SHIFT_PARENT | AppendChild, // Expando location: 100 ], <I18nMutateOpCodes>[ // Case: `other`: `{�0� <!--subICU-->}` '', 1 << SHIFT_PARENT | AppendChild, // Expando location: 100 ICU_MARKER, '', 0 << SHIFT_PARENT | AppendChild, // Expando location: 101 ], ], remove: [ <I18nMutateOpCodes>[ // Case: `0`: `{zero}` 1 << SHIFT_PARENT | 100 << SHIFT_REF | Remove, ], <I18nMutateOpCodes>[ // Case: `other`: `{�0� <!--subICU-->}` 1 << SHIFT_PARENT | 100 << SHIFT_REF | Remove, 1 << SHIFT_PARENT | 101 << SHIFT_REF | Remove, ], ], update: [ <I18nMutateOpCodes>[ // Case: `0`: `{zero}` ], <I18nMutateOpCodes>[ // Case: `other`: `{�0� <!--subICU-->}` 0b1, 3, -2, ' ', 100 << SHIFT_REF | Text, // Case: `�0� ` 0b10, 5, -1, // Switch ICU: `icuSwitchCase(lView[101 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/, accumulatorFlush());` 101 << SHIFT_REF | 0 << SHIFT_ICU | IcuSwitch, // NOTE: the bit mask here is the logical OR of all of the masks int the ICU. 0b10, 1, // Update ICU: `icuUpdateCase(lView[101 /*SHIFT_REF*/], 0 /*SHIFT_ICU*/);` 101 << SHIFT_REF | 0 << SHIFT_ICU | IcuUpdate, ], ] }, <TIcu>{ // {�1�, select, cat {cats} dog {dogs} other {animals} } cases: ['cat', 'dog', 'other'], vars: [1, 1, 1], expandoStartIndex: 102, // Assume in this example EXPANDO starts at 102. (parent ICU 100 + max(1, 2)) childIcus: [], create: [ <I18nMutateOpCodes>[ // Case: `cat`: `{cats}` 'cats', 101 << SHIFT_PARENT | AppendChild, // Expando location: 102; 101 is location of comment/anchor ], <I18nMutateOpCodes>[ // Case: `doc`: `docs` 'cats', 101 << SHIFT_PARENT | AppendChild, // Expando location: 102; 101 is location of comment/anchor ], <I18nMutateOpCodes>[ // Case: `other`: `animals` 'animals', 101 << SHIFT_PARENT | AppendChild, // Expando location: 102; 101 is location of comment/anchor ], ] remove: [ <I18nMutateOpCodes>[ // Case: `cat`: `{cats}` 101 << SHIFT_PARENT | 102 << SHIFT_REF | Remove, ], <I18nMutateOpCodes>[ // Case: `doc`: `docs` 101 << SHIFT_PARENT | 102 << SHIFT_REF | Remove, ], <I18nMutateOpCodes>[ // Case: `other`: `animals` 101 << SHIFT_PARENT | 102 << SHIFT_REF | Remove, ], ], update: [ <I18nMutateOpCodes>[ // Case: `cat`: `{cats}` ], <I18nMutateOpCodes>[ // Case: `doc`: `docs` ], <I18nMutateOpCodes>[ // Case: `other`: `animals` ], ] } ], } ``` # Translation Message Retrieval The generated code needs work with: - Closure: This requires that the translation string is retrieved using `goog.getMsg`. - Non-closure: This requires the use of Angular service to retrieve the translation string. - Server Side: All translations need to be retrieved so that one server VM can respond to all locales. The solution is to take advantage of compile time constants (e.g. `CLOSURE`) like so: ```typescript import '@angular/loca
{ "end_byte": 40057, "start_byte": 33508, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_40057_41495
lize/init'; let MSG_hello; if (CLOSURE) { /** * @desc extracted description goes here. */ const MSG_hello_ = goog.getMsg('Hello World!'); MSG_hello = MSG_hello_; } else { // This would work in non-closure mode, and can work for both browser and SSR use case. MSG_hello = $localize`Hello World!`; } const MSG_div_attr = ['title', MSG_hello]; class MyComponent { static ɵcmp = defineComponent({ ..., template: function(rf: RenderFlags, ctx: MyComponent) { if (rf & RenderFlags.Create) { i18nAttributes(1, MSG_hello); i18nEnd(); } } }); } ``` NOTE: - The compile time constant (`CLOSURE`) is important because when the generated code is shipped to NPM it must contain all formats, because at the time of packaging it is not known how the final application will be bundled. - Alternatively because we already ship different source code for closure we could generated different code for closure folder. ## `goog.getMsg()` An important goal is to interpolate seamlessly with [`goog.getMsg()`](https://github.com/google/closure-library/blob/db35cf1524b36a50d021fb6cf47271687cc2ea33/closure/goog/base.js#L1970-L1998). When `goog.getMsg` gets a translation it treats `{$some_text}` special by generating `<ph>..</ph>` tags in `.xmb` file. ```typescript /** * @desc Greeting. */ const MSG = goog.getMsg('Hello {$name}!', { name: 'world' }); ``` This will result in: ```xml <msg
{ "end_byte": 41495, "start_byte": 40057, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_41495_47694
id="1234567890" desc="Greeting.">Hello <ph name="NAME"><ex>-</ex>-</ph>!</msg> ``` Notice the `<ph>` placeholders. `<ph>` is useful for translators because it can contain an example as well as description. In case of `goog.getMsg` there is no way to encode the example, and the description defaults to capitalized version of the `{$}`. In the example above `{$name}` is encoded in `<ph>` as `NAME`. What is necessary is to generate `goog.getMsg` which uses `{$placeholder}` but is mapped to Angular's `�0�` placeholder. This is achieved as follows. ```typescript /** * @desc Greeting. */ const MSG = goog.getMsg('Hello {$name}!', { name: '�0�' }); ``` The resulting string will be `"Hello �0�!"` which can be used by Angular's runtime. Here is a more complete example. Given this Angular's template: ```HTML <div i18n-title title="Hello {{name}}!" i18n="Some description."> {{count}} is rendered as: <b *ngIf="true"> { count, plural, =0 {no <b title="none">emails</b>!} =1 {one <i>email</i>} other {{{count}} <span title="{{count}}">emails</span>} } </b>. </div> ``` The compiler will generate: ```typescript /** * @desc Some description. */ let MSG_div = goog.getMsg(`{$COUNT} is rendered as: {$START_BOLD_TEXT_1}{{$COUNT}, plural, =0 {no {$START_BOLD_TEXT}emails{$CLOSE_BOLD_TEXT}!} =1 {one {$START_ITALIC_TEXT}email{$CLOSE_ITALIC_TEXT}} other {{$COUNT} {$START_TAG_SPAN}emails{$CLOSE_TAG_SPAN}} }{$END_BOLD_TEXT_1}`, { COUNT: '�0�', START_BOLD_TEXT_1: '�*3:1��#1:1�', END_BOLD_TEXT_1: '�/#1:1��/*3:1�', START_BOLD_TEXT: '<b title="none">', CLOSE_BOLD_TEXT: '</b>', START_ITALIC_TEXT: '<i>', CLOSE_ITALIC_TEXT: '</i>', START_TAG_SPAN: '<span title="�0:1�">', CLOSE_TAG_SPAN: '</span>' }); ``` The result of the above will be a string which `i18nStart` can process: ``` �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�. ``` ### Backwards compatibility with ViewEngine In order to upgrade from ViewEngine to Ivy runtime it is necessary to make sure that the translation IDs match between the two systems. There are two issues which need to be solved: 1. The ViewEngine implementation splits a single `i18n` block into multiple messages when ICUs are embedded in the translation. 2. The ViewEngine does its own message extraction and uses a different hashing algorithm from `goog.getMsg`. To generate code where the extracted i18n messages have the same ids, the `ngtsc` can be placed into a special compatibility mode which will generate `goog.getMsg` in a special altered format as described next. Given this Angular's template: ```HTML <div i18n-title title="Hello {{name}}!" i18n="Some description."> {{count}} is rendered as: <b *ngIf="true"> { count, plural, =0 {no <b title="none">emails</b>!} =1 {one <i>email</i>} other {{{count}} <span title="{{count}}">emails</span>} } </b>. </div> ``` The ViewEngine implementation will generate following XMB file. ```XML <msg id="2919330615509803611"><source>app/app.component.html:1,10</source> <ph name="INTERPOLATION"><ex>-</ex>-</ph> is rendered as: <ph name="START_BOLD_TEXT_1"><ex>-</ex>-</ph> <ph name="ICU"><ex>-</ex>-</ph> <ph name="CLOSE_BOLD_TEXT"><ex>-</ex>-</ph> . </msg> <msg id="3639715378617754400"><source>app/app.component.html:4,8</source> {VAR_PLURAL, plural, =0 {no <ph name="START_BOLD_TEXT"><ex>-</ex>-</ph> emails <ph name="CLOSE_BOLD_TEXT"><ex>-</ex>-</ph> ! } =1 {one <ph name="START_ITALIC_TEXT"><ex>-</ex>-</ph> email <ph name="CLOSE_ITALIC_TEXT"><ex>-</ex>-</ph> } other {<ph name="INTERPOLATION"><ex>-</ex>-</ph> <ph name="START_TAG_SPAN"><ex>-</ex>-</ph> emails <ph name="CLOSE_TAG_SPAN"><ex>-</ex>-</ph> } } </msg> ``` With the compatibility mode the compiler will generate following code which will match the IDs and structure of the ViewEngine: ```typescript /** * @desc [BACKUP_MESSAGE_ID:3639715378617754400] ICU extracted form: Some description. */ const MSG_div_icu = goog.getMsg(`{VAR_PLURAL, plural, =0 {no {$START_BOLD_TEXT}emails{$CLOSE_BOLD_TEXT}!} =1 {one {$START_ITALIC_TEXT}email{$CLOSE_ITALIC_TEXT}} other {{$count} {$START_TAG_SPAN}emails{$CLOSE_TAG_SPAN}} }`, { START_BOLD_TEXT: '<b title="none">', CLOSE_BOLD_TEXT: '</b>', START_ITALIC_TEXT: '<i>', CLOSE_ITALIC_TEXT: '</i>', COUNT: '�0:1�', START_TAG_SPAN: '<span title="�0:1�">', CLOSE_TAG_SPAN: '</span>' } ); /** * @desc [BACKUP_MESSAGE_ID:2919330615509803611] Some description. */ const MSG_div_raw = goog.getMsg('{$COUNT_1} is rendered as: {$START_BOLD_TEXT_1}{$ICU}{$END_BOLD_TEXT_1}', { ICU: MSG_div_icu, COUNT: '�0:1�', START_BOLD_TEXT_1: '�*3:1��#1�', END_BOLD_TEXT_1: '�/#1:1��/*3:1�', }); const MSG_div = i18nPostprocess(MSG_div_raw, {VAR_PLURAL: '�0:1�'}); ``` NOTE: - The compiler generates `[BACKUP_MESSAGE_ID:2919330615509803611]` which forces the `goog.getMsg` to use a specific message ID. - The compiler splits a single translation on ICU boundaries so that same number of messages are generated as with ViewEngine. - The two messages are reassembled into a single message. Resulting in same string which Angular can process: ``` �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�. ``` ### Placeholders with multiple values While extracting messages via `ng extract-i18n`, the tool performs an optimization and reuses the same placeholders for elements/interpolations in case placeholder content is identical. For example the following template: ```html <b>My text 1</b><b>My text 2</b> ``` is transformed into: ```html {$START_TAG_BOLD}My text 1{$CLOSE_TAG_BOLD}{$START_TAG_BOLD}My text 2{$CLOSE_TAG_BOLD} ``` In IVY we need to have specific element instruction indices for open and close tags, so the result string (that can be consumed by `i18nStart`) produced, should look like this: ```h
{ "end_byte": 47694, "start_byte": 41495, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n.md_47694_49813
tml �#1�My text 1�/#1��#2�My text 1�/#2� ``` In order to resolve this, we need to supply all values that a given placeholder represents and invoke post processing function to transform intermediate string into its final version. In this case the `goog.getMsg` invocation will look like this: ```typescript /** * @desc [BACKUP_MESSAGE_ID:2919330615509803611] Some description. */ const MSG_div_raw = goog.getMsg('{$START_TAG_BOLD}My text 1{$CLOSE_TAG_BOLD}{$START_TAG_BOLD}My text 2{$CLOSE_TAG_BOLD}', { START_TAG_BOLD: '[�#1�|�#2�]', CLOSE_TAG_BOLD: '[�/#2�|�/#1�]' }); const MSG_div = i18nPostprocess(MSG_div_raw); ``` ### `i18nPostprocess` function Due to backwards-compatibility requirements and some limitations of `goog.getMsg`, in some cases we need to run post process to convert intermediate string into its final version that can be consumed by Ivy runtime code (something that `i18nStart` can understand), specifically: - we replace all `VAR_PLURAL` and `VAR_SELECT` with respective values. This is required because the ICU format does not allow placeholders in the ICU header location, a variable such as `VAR_PLURAL` must be used. - in some cases, ICUs may share the same placeholder name (like `ICU_1`). For this scenario we inject a special markers (`�I18N_EXP_ICU�) into a string and resolve this within the post processing function - this function also resolves the case when one placeholder is used to represent multiple elements (see example above)
{ "end_byte": 49813, "start_byte": 47694, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n.md" }
angular/packages/core/src/render3/i18n/i18n_debug.ts_0_7517
/** * @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 {assertNumber, assertString} from '../../util/assert'; import { ELEMENT_MARKER, I18nCreateOpCode, I18nCreateOpCodes, I18nRemoveOpCodes, I18nUpdateOpCode, I18nUpdateOpCodes, ICU_MARKER, IcuCreateOpCode, IcuCreateOpCodes, } from '../interfaces/i18n'; import { getInstructionFromIcuCreateOpCode, getParentFromIcuCreateOpCode, getRefFromIcuCreateOpCode, } from './i18n_util'; /** * Converts `I18nCreateOpCodes` array into a human readable format. * * This function is attached to the `I18nCreateOpCodes.debug` property if `ngDevMode` is enabled. * This function provides a human readable view of the opcodes. This is useful when debugging the * application as well as writing more readable tests. * * @param this `I18nCreateOpCodes` if attached as a method. * @param opcodes `I18nCreateOpCodes` if invoked as a function. */ export function i18nCreateOpCodesToString( this: I18nCreateOpCodes | void, opcodes?: I18nCreateOpCodes, ): string[] { const createOpCodes: I18nCreateOpCodes = opcodes || (Array.isArray(this) ? this : ([] as any)); let lines: string[] = []; for (let i = 0; i < createOpCodes.length; i++) { const opCode = createOpCodes[i++] as any; const text = createOpCodes[i] as string; const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT; const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY; const index = opCode >>> I18nCreateOpCode.SHIFT; lines.push( `lView[${index}] = document.${isComment ? 'createComment' : 'createText'}(${JSON.stringify( text, )});`, ); if (appendNow) { lines.push(`parent.appendChild(lView[${index}]);`); } } return lines; } /** * Converts `I18nUpdateOpCodes` array into a human readable format. * * This function is attached to the `I18nUpdateOpCodes.debug` property if `ngDevMode` is enabled. * This function provides a human readable view of the opcodes. This is useful when debugging the * application as well as writing more readable tests. * * @param this `I18nUpdateOpCodes` if attached as a method. * @param opcodes `I18nUpdateOpCodes` if invoked as a function. */ export function i18nUpdateOpCodesToString( this: I18nUpdateOpCodes | void, opcodes?: I18nUpdateOpCodes, ): string[] { const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : [])); let lines: string[] = []; function consumeOpCode(value: number): string { const ref = value >>> I18nUpdateOpCode.SHIFT_REF; const opCode = value & I18nUpdateOpCode.MASK_OPCODE; switch (opCode) { case I18nUpdateOpCode.Text: return `(lView[${ref}] as Text).textContent = $$$`; case I18nUpdateOpCode.Attr: const attrName = parser.consumeString(); const sanitizationFn = parser.consumeFunction(); const value = sanitizationFn ? `(${sanitizationFn})($$$)` : '$$$'; return `(lView[${ref}] as Element).setAttribute('${attrName}', ${value})`; case I18nUpdateOpCode.IcuSwitch: return `icuSwitchCase(${ref}, $$$)`; case I18nUpdateOpCode.IcuUpdate: return `icuUpdateCase(${ref})`; } throw new Error('unexpected OpCode'); } while (parser.hasMore()) { let mask = parser.consumeNumber(); let size = parser.consumeNumber(); const end = parser.i + size; const statements: string[] = []; let statement = ''; while (parser.i < end) { let value = parser.consumeNumberOrString(); if (typeof value === 'string') { statement += value; } else if (value < 0) { // Negative numbers are ref indexes // Here `i` refers to current binding index. It is to signify that the value is relative, // rather than absolute. statement += '${lView[i' + value + ']}'; } else { // Positive numbers are operations. const opCodeText = consumeOpCode(value); statements.push(opCodeText.replace('$$$', '`' + statement + '`') + ';'); statement = ''; } } lines.push(`if (mask & 0b${mask.toString(2)}) { ${statements.join(' ')} }`); } return lines; } /** * Converts `I18nCreateOpCodes` array into a human readable format. * * This function is attached to the `I18nCreateOpCodes.debug` if `ngDevMode` is enabled. This * function provides a human readable view of the opcodes. This is useful when debugging the * application as well as writing more readable tests. * * @param this `I18nCreateOpCodes` if attached as a method. * @param opcodes `I18nCreateOpCodes` if invoked as a function. */ export function icuCreateOpCodesToString( this: IcuCreateOpCodes | void, opcodes?: IcuCreateOpCodes, ): string[] { const parser = new OpCodeParser(opcodes || (Array.isArray(this) ? this : [])); let lines: string[] = []; function consumeOpCode(opCode: number): string { const parent = getParentFromIcuCreateOpCode(opCode); const ref = getRefFromIcuCreateOpCode(opCode); switch (getInstructionFromIcuCreateOpCode(opCode)) { case IcuCreateOpCode.AppendChild: return `(lView[${parent}] as Element).appendChild(lView[${lastRef}])`; case IcuCreateOpCode.Attr: return `(lView[${ref}] as Element).setAttribute("${parser.consumeString()}", "${parser.consumeString()}")`; } throw new Error('Unexpected OpCode: ' + getInstructionFromIcuCreateOpCode(opCode)); } let lastRef = -1; while (parser.hasMore()) { let value = parser.consumeNumberStringOrMarker(); if (value === ICU_MARKER) { const text = parser.consumeString(); lastRef = parser.consumeNumber(); lines.push(`lView[${lastRef}] = document.createComment("${text}")`); } else if (value === ELEMENT_MARKER) { const text = parser.consumeString(); lastRef = parser.consumeNumber(); lines.push(`lView[${lastRef}] = document.createElement("${text}")`); } else if (typeof value === 'string') { lastRef = parser.consumeNumber(); lines.push(`lView[${lastRef}] = document.createTextNode("${value}")`); } else if (typeof value === 'number') { const line = consumeOpCode(value); line && lines.push(line); } else { throw new Error('Unexpected value'); } } return lines; } /** * Converts `I18nRemoveOpCodes` array into a human readable format. * * This function is attached to the `I18nRemoveOpCodes.debug` if `ngDevMode` is enabled. This * function provides a human readable view of the opcodes. This is useful when debugging the * application as well as writing more readable tests. * * @param this `I18nRemoveOpCodes` if attached as a method. * @param opcodes `I18nRemoveOpCodes` if invoked as a function. */ export function i18nRemoveOpCodesToString( this: I18nRemoveOpCodes | void, opcodes?: I18nRemoveOpCodes, ): string[] { const removeCodes = opcodes || (Array.isArray(this) ? this : []); let lines: string[] = []; for (let i = 0; i < removeCodes.length; i++) { const nodeOrIcuIndex = removeCodes[i] as number; if (nodeOrIcuIndex > 0) { // Positive numbers are `RNode`s. lines.push(`remove(lView[${nodeOrIcuIndex}])`); } else { // Negative numbers are ICUs lines.push(`removeNestedICU(${~nodeOrIcuIndex})`); } } return lines; }
{ "end_byte": 7517, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_debug.ts" }
angular/packages/core/src/render3/i18n/i18n_debug.ts_7519_8838
class OpCodeParser { i: number = 0; codes: any[]; constructor(codes: any[]) { this.codes = codes; } hasMore() { return this.i < this.codes.length; } consumeNumber(): number { let value = this.codes[this.i++]; assertNumber(value, 'expecting number in OpCode'); return value; } consumeString(): string { let value = this.codes[this.i++]; assertString(value, 'expecting string in OpCode'); return value; } consumeFunction(): Function | null { let value = this.codes[this.i++]; if (value === null || typeof value === 'function') { return value; } throw new Error('expecting function in OpCode'); } consumeNumberOrString(): number | string { let value = this.codes[this.i++]; if (typeof value === 'string') { return value; } assertNumber(value, 'expecting number or string in OpCode'); return value; } consumeNumberStringOrMarker(): number | string | ICU_MARKER | ELEMENT_MARKER { let value = this.codes[this.i++]; if ( typeof value === 'string' || typeof value === 'number' || value == ICU_MARKER || value == ELEMENT_MARKER ) { return value; } assertNumber(value, 'expecting number, string, ICU_MARKER or ELEMENT_MARKER in OpCode'); return value; } }
{ "end_byte": 8838, "start_byte": 7519, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_debug.ts" }
angular/packages/core/src/render3/i18n/i18n_util.ts_0_6054
/** * @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, assertGreaterThan, assertGreaterThanOrEqual, throwError, } from '../../util/assert'; import {assertTIcu, assertTNode} from '../assert'; import {createTNodeAtIndex} from '../instructions/shared'; import {IcuCreateOpCode, TIcu} from '../interfaces/i18n'; import {TIcuContainerNode, TNode, TNodeType} from '../interfaces/node'; import {LView, TView} from '../interfaces/view'; import {assertTNodeType} from '../node_assert'; import {setI18nHandling} from '../node_manipulation'; import {getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore} from '../node_manipulation_i18n'; import {addTNodeAndUpdateInsertBeforeIndex} from './i18n_insert_before_index'; /** * Retrieve `TIcu` at a given `index`. * * The `TIcu` can be stored either directly (if it is nested ICU) OR * it is stored inside tho `TIcuContainer` if it is top level ICU. * * The reason for this is that the top level ICU need a `TNode` so that they are part of the render * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is * expressed (parent ICU may have selected a case which does not contain it.) * * @param tView Current `TView`. * @param index Index where the value should be read from. */ export function getTIcu(tView: TView, index: number): TIcu | null { const value = tView.data[index] as null | TIcu | TIcuContainerNode | string; if (value === null || typeof value === 'string') return null; if ( ngDevMode && !(value.hasOwnProperty('tView') || value.hasOwnProperty('currentCaseLViewIndex')) ) { throwError("We expect to get 'null'|'TIcu'|'TIcuContainer', but got: " + value); } // Here the `value.hasOwnProperty('currentCaseLViewIndex')` is a polymorphic read as it can be // either TIcu or TIcuContainerNode. This is not ideal, but we still think it is OK because it // will be just two cases which fits into the browser inline cache (inline cache can take up to // 4) const tIcu = value.hasOwnProperty('currentCaseLViewIndex') ? (value as TIcu) : (value as TIcuContainerNode).value; ngDevMode && assertTIcu(tIcu); return tIcu; } /** * Store `TIcu` at a give `index`. * * The `TIcu` can be stored either directly (if it is nested ICU) OR * it is stored inside tho `TIcuContainer` if it is top level ICU. * * The reason for this is that the top level ICU need a `TNode` so that they are part of the render * tree, but nested ICU's have no TNode, because we don't know ahead of time if the nested ICU is * expressed (parent ICU may have selected a case which does not contain it.) * * @param tView Current `TView`. * @param index Index where the value should be stored at in `Tview.data` * @param tIcu The TIcu to store. */ export function setTIcu(tView: TView, index: number, tIcu: TIcu): void { const tNode = tView.data[index] as null | TIcuContainerNode; ngDevMode && assertEqual( tNode === null || tNode.hasOwnProperty('tView'), true, "We expect to get 'null'|'TIcuContainer'", ); if (tNode === null) { tView.data[index] = tIcu; } else { ngDevMode && assertTNodeType(tNode, TNodeType.Icu); tNode.value = tIcu; } } /** * Set `TNode.insertBeforeIndex` taking the `Array` into account. * * See `TNode.insertBeforeIndex` */ export function setTNodeInsertBeforeIndex(tNode: TNode, index: number) { ngDevMode && assertTNode(tNode); let insertBeforeIndex = tNode.insertBeforeIndex; if (insertBeforeIndex === null) { setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore); insertBeforeIndex = tNode.insertBeforeIndex = [ null! /* may be updated to number later */, index, ]; } else { assertEqual(Array.isArray(insertBeforeIndex), true, 'Expecting array here'); (insertBeforeIndex as number[]).push(index); } } /** * Create `TNode.type=TNodeType.Placeholder` node. * * See `TNodeType.Placeholder` for more information. */ export function createTNodePlaceholder( tView: TView, previousTNodes: TNode[], index: number, ): TNode { const tNode = createTNodeAtIndex(tView, index, TNodeType.Placeholder, null, null); addTNodeAndUpdateInsertBeforeIndex(previousTNodes, tNode); return tNode; } /** * Returns current ICU case. * * ICU cases are stored as index into the `TIcu.cases`. * At times it is necessary to communicate that the ICU case just switched and that next ICU update * should update all bindings regardless of the mask. In such a case the we store negative numbers * for cases which have just been switched. This function removes the negative flag. */ export function getCurrentICUCaseIndex(tIcu: TIcu, lView: LView) { const currentCase: number | null = lView[tIcu.currentCaseLViewIndex]; return currentCase === null ? currentCase : currentCase < 0 ? ~currentCase : currentCase; } export function getParentFromIcuCreateOpCode(mergedCode: number): number { return mergedCode >>> IcuCreateOpCode.SHIFT_PARENT; } export function getRefFromIcuCreateOpCode(mergedCode: number): number { return (mergedCode & IcuCreateOpCode.MASK_REF) >>> IcuCreateOpCode.SHIFT_REF; } export function getInstructionFromIcuCreateOpCode(mergedCode: number): number { return mergedCode & IcuCreateOpCode.MASK_INSTRUCTION; } export function icuCreateOpCode(opCode: IcuCreateOpCode, parentIdx: number, refIdx: number) { ngDevMode && assertGreaterThanOrEqual(parentIdx, 0, 'Missing parent index'); ngDevMode && assertGreaterThan(refIdx, 0, 'Missing ref index'); return ( opCode | (parentIdx << IcuCreateOpCode.SHIFT_PARENT) | (refIdx << IcuCreateOpCode.SHIFT_REF) ); } // Returns whether the given value corresponds to a root template message, // or a sub-template. export function isRootTemplateMessage(subTemplateIndex: number): subTemplateIndex is -1 { return subTemplateIndex === -1; }
{ "end_byte": 6054, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_util.ts" }
angular/packages/core/src/render3/i18n/i18n_tree_shaking.ts_0_1530
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @fileoverview * * This file provides mechanism by which code relevant to the `TIcuContainerNode` is only loaded if * ICU is present in the template. */ import {TIcuContainerNode} from '../interfaces/node'; import {RNode} from '../interfaces/renderer_dom'; import {LView} from '../interfaces/view'; let _icuContainerIterate: ( tIcuContainerNode: TIcuContainerNode, lView: LView, ) => () => RNode | null; /** * Iterator which provides ability to visit all of the `TIcuContainerNode` root `RNode`s. */ export function icuContainerIterate( tIcuContainerNode: TIcuContainerNode, lView: LView, ): () => RNode | null { return _icuContainerIterate(tIcuContainerNode, lView); } /** * Ensures that `IcuContainerVisitor`'s implementation is present. * * This function is invoked when i18n instruction comes across an ICU. The purpose is to allow the * bundler to tree shake ICU logic and only load it if ICU instruction is executed. */ export function ensureIcuContainerVisitorLoaded( loader: () => (tIcuContainerNode: TIcuContainerNode, lView: LView) => () => RNode | null, ) { if (_icuContainerIterate === undefined) { // Do not inline this function. We want to keep `ensureIcuContainerVisitorLoaded` light, so it // can be inlined into call-site. _icuContainerIterate = loader(); } }
{ "end_byte": 1530, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_tree_shaking.ts" }
angular/packages/core/src/render3/i18n/i18n_apply.ts_0_6553
/** * @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 {claimDehydratedIcuCase, isI18nHydrationSupportEnabled} from '../../hydration/i18n'; import {locateI18nRNodeByIndex} from '../../hydration/node_lookup_utils'; import {isDisconnectedNode, markRNodeAsClaimedByHydration} from '../../hydration/utils'; import {getPluralCase} from '../../i18n/localization'; import { assertDefined, assertDomNode, assertEqual, assertGreaterThan, assertIndexInRange, throwError, } from '../../util/assert'; import {assertIndexInExpandoRange, assertTIcu} from '../assert'; import {attachPatchData} from '../context_discovery'; import {elementPropertyInternal, setElementAttribute} from '../instructions/shared'; import { ELEMENT_MARKER, I18nCreateOpCode, I18nCreateOpCodes, I18nUpdateOpCode, I18nUpdateOpCodes, ICU_MARKER, IcuCreateOpCode, IcuCreateOpCodes, IcuType, TI18n, TIcu, } from '../interfaces/i18n'; import {TNode} from '../interfaces/node'; import {RElement, RNode, RText} from '../interfaces/renderer_dom'; import {SanitizerFn} from '../interfaces/sanitization'; import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view'; import { createCommentNode, createElementNode, createTextNode, nativeInsertBefore, nativeParentNode, nativeRemoveNode, updateTextNode, } from '../node_manipulation'; import { getBindingIndex, isInSkipHydrationBlock, lastNodeWasCreated, wasLastNodeCreated, } from '../state'; import {renderStringify} from '../util/stringify_utils'; import {getNativeByIndex, unwrapRNode} from '../util/view_utils'; import {getLocaleId} from './i18n_locale_id'; import { getCurrentICUCaseIndex, getParentFromIcuCreateOpCode, getRefFromIcuCreateOpCode, getTIcu, } from './i18n_util'; /** * Keep track of which input bindings in `ɵɵi18nExp` have changed. * * This is used to efficiently update expressions in i18n only when the corresponding input has * changed. * * 1) Each bit represents which of the `ɵɵi18nExp` has changed. * 2) There are 32 bits allowed in JS. * 3) Bit 32 is special as it is shared for all changes past 32. (In other words if you have more * than 32 `ɵɵi18nExp` then all changes past 32nd `ɵɵi18nExp` will be mapped to same bit. This means * that we may end up changing more than we need to. But i18n expressions with 32 bindings is rare * so in practice it should not be an issue.) */ let changeMask = 0b0; /** * Keeps track of which bit needs to be updated in `changeMask` * * This value gets incremented on every call to `ɵɵi18nExp` */ let changeMaskCounter = 0; /** * Keep track of which input bindings in `ɵɵi18nExp` have changed. * * `setMaskBit` gets invoked by each call to `ɵɵi18nExp`. * * @param hasChange did `ɵɵi18nExp` detect a change. */ export function setMaskBit(hasChange: boolean) { if (hasChange) { changeMask = changeMask | (1 << Math.min(changeMaskCounter, 31)); } changeMaskCounter++; } export function applyI18n(tView: TView, lView: LView, index: number) { if (changeMaskCounter > 0) { ngDevMode && assertDefined(tView, `tView should be defined`); const tI18n = tView.data[index] as TI18n | I18nUpdateOpCodes; // When `index` points to an `ɵɵi18nAttributes` then we have an array otherwise `TI18n` const updateOpCodes: I18nUpdateOpCodes = Array.isArray(tI18n) ? (tI18n as I18nUpdateOpCodes) : (tI18n as TI18n).update; const bindingsStartIndex = getBindingIndex() - changeMaskCounter - 1; applyUpdateOpCodes(tView, lView, updateOpCodes, bindingsStartIndex, changeMask); } // Reset changeMask & maskBit to default for the next update cycle changeMask = 0b0; changeMaskCounter = 0; } function createNodeWithoutHydration( lView: LView, textOrName: string, nodeType: typeof Node.COMMENT_NODE | typeof Node.TEXT_NODE | typeof Node.ELEMENT_NODE, ) { const renderer = lView[RENDERER]; switch (nodeType) { case Node.COMMENT_NODE: return createCommentNode(renderer, textOrName); case Node.TEXT_NODE: return createTextNode(renderer, textOrName); case Node.ELEMENT_NODE: return createElementNode(renderer, textOrName, null); } } let _locateOrCreateNode: typeof locateOrCreateNodeImpl = (lView, index, textOrName, nodeType) => { lastNodeWasCreated(true); return createNodeWithoutHydration(lView, textOrName, nodeType); }; function locateOrCreateNodeImpl( lView: LView, index: number, textOrName: string, nodeType: typeof Node.COMMENT_NODE | typeof Node.TEXT_NODE | typeof Node.ELEMENT_NODE, ) { const hydrationInfo = lView[HYDRATION]; const noOffsetIndex = index - HEADER_OFFSET; const isNodeCreationMode = !isI18nHydrationSupportEnabled() || !hydrationInfo || isInSkipHydrationBlock() || isDisconnectedNode(hydrationInfo, noOffsetIndex); lastNodeWasCreated(isNodeCreationMode); if (isNodeCreationMode) { return createNodeWithoutHydration(lView, textOrName, nodeType); } const native = locateI18nRNodeByIndex(hydrationInfo!, noOffsetIndex) as RNode; // TODO: Improve error handling // // Other hydration paths use validateMatchingNode() in order to provide // detailed information in development mode about the expected DOM. // However, not every node in an i18n block has a TNode. Instead, we // need to be able to use the AST to generate a similar message. ngDevMode && assertDefined(native, 'expected native element'); ngDevMode && assertEqual((native as Node).nodeType, nodeType, 'expected matching nodeType'); ngDevMode && nodeType === Node.ELEMENT_NODE && assertEqual( (native as HTMLElement).tagName.toLowerCase(), textOrName.toLowerCase(), 'expecting matching tagName', ); ngDevMode && markRNodeAsClaimedByHydration(native); return native; } export function enableLocateOrCreateI18nNodeImpl() { _locateOrCreateNode = locateOrCreateNodeImpl; } /** * Apply `I18nCreateOpCodes` op-codes as stored in `TI18n.create`. * * Creates text (and comment) nodes which are internationalized. * * @param lView Current lView * @param createOpCodes Set of op-codes to apply * @param parentRNode Parent node (so that direct children can be added eagerly) or `null` if it is * a root node. * @param insertInFrontOf DOM node that should be used as an anchor. */ export function a
{ "end_byte": 6553, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_apply.ts" }
angular/packages/core/src/render3/i18n/i18n_apply.ts_6554_14579
plyCreateOpCodes( lView: LView, createOpCodes: I18nCreateOpCodes, parentRNode: RElement | null, insertInFrontOf: RElement | null, ): void { const renderer = lView[RENDERER]; for (let i = 0; i < createOpCodes.length; i++) { const opCode = createOpCodes[i++] as any; const text = createOpCodes[i] as string; const isComment = (opCode & I18nCreateOpCode.COMMENT) === I18nCreateOpCode.COMMENT; const appendNow = (opCode & I18nCreateOpCode.APPEND_EAGERLY) === I18nCreateOpCode.APPEND_EAGERLY; const index = opCode >>> I18nCreateOpCode.SHIFT; let rNode = lView[index]; let lastNodeWasCreated = false; if (rNode === null) { // We only create new DOM nodes if they don't already exist: If ICU switches case back to a // case which was already instantiated, no need to create new DOM nodes. rNode = lView[index] = _locateOrCreateNode( lView, index, text, isComment ? Node.COMMENT_NODE : Node.TEXT_NODE, ); lastNodeWasCreated = wasLastNodeCreated(); } if (appendNow && parentRNode !== null && lastNodeWasCreated) { nativeInsertBefore(renderer, parentRNode, rNode, insertInFrontOf, false); } } } /** * Apply `I18nMutateOpCodes` OpCodes. * * @param tView Current `TView` * @param mutableOpCodes Mutable OpCodes to process * @param lView Current `LView` * @param anchorRNode place where the i18n node should be inserted. */ export function applyMutableOpCodes( tView: TView, mutableOpCodes: IcuCreateOpCodes, lView: LView, anchorRNode: RNode, ): void { ngDevMode && assertDomNode(anchorRNode); const renderer = lView[RENDERER]; // `rootIdx` represents the node into which all inserts happen. let rootIdx: number | null = null; // `rootRNode` represents the real node into which we insert. This can be different from // `lView[rootIdx]` if we have projection. // - null we don't have a parent (as can be the case in when we are inserting into a root of // LView which has no parent.) // - `RElement` The element representing the root after taking projection into account. let rootRNode!: RElement | null; for (let i = 0; i < mutableOpCodes.length; i++) { const opCode = mutableOpCodes[i]; if (typeof opCode == 'string') { const textNodeIndex = mutableOpCodes[++i] as number; if (lView[textNodeIndex] === null) { ngDevMode && ngDevMode.rendererCreateTextNode++; ngDevMode && assertIndexInRange(lView, textNodeIndex); lView[textNodeIndex] = _locateOrCreateNode(lView, textNodeIndex, opCode, Node.TEXT_NODE); } } else if (typeof opCode == 'number') { switch (opCode & IcuCreateOpCode.MASK_INSTRUCTION) { case IcuCreateOpCode.AppendChild: const parentIdx = getParentFromIcuCreateOpCode(opCode); if (rootIdx === null) { // The first operation should save the `rootIdx` because the first operation // must insert into the root. (Only subsequent operations can insert into a dynamic // parent) rootIdx = parentIdx; rootRNode = nativeParentNode(renderer, anchorRNode); } let insertInFrontOf: RNode | null; let parentRNode: RElement | null; if (parentIdx === rootIdx) { insertInFrontOf = anchorRNode; parentRNode = rootRNode; } else { insertInFrontOf = null; parentRNode = unwrapRNode(lView[parentIdx]) as RElement; } // FIXME(misko): Refactor with `processI18nText` if (parentRNode !== null) { // This can happen if the `LView` we are adding to is not attached to a parent `LView`. // In such a case there is no "root" we can attach to. This is fine, as we still need to // create the elements. When the `LView` gets later added to a parent these "root" nodes // get picked up and added. ngDevMode && assertDomNode(parentRNode); const refIdx = getRefFromIcuCreateOpCode(opCode); ngDevMode && assertGreaterThan(refIdx, HEADER_OFFSET, 'Missing ref'); // `unwrapRNode` is not needed here as all of these point to RNodes as part of the i18n // which can't have components. const child = lView[refIdx] as RElement; ngDevMode && assertDomNode(child); nativeInsertBefore(renderer, parentRNode, child, insertInFrontOf, false); const tIcu = getTIcu(tView, refIdx); if (tIcu !== null && typeof tIcu === 'object') { // If we just added a comment node which has ICU then that ICU may have already been // rendered and therefore we need to re-add it here. ngDevMode && assertTIcu(tIcu); const caseIndex = getCurrentICUCaseIndex(tIcu, lView); if (caseIndex !== null) { applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, lView[tIcu.anchorIdx]); } } } break; case IcuCreateOpCode.Attr: const elementNodeIndex = opCode >>> IcuCreateOpCode.SHIFT_REF; const attrName = mutableOpCodes[++i] as string; const attrValue = mutableOpCodes[++i] as string; // This code is used for ICU expressions only, since we don't support // directives/components in ICUs, we don't need to worry about inputs here setElementAttribute( renderer, getNativeByIndex(elementNodeIndex, lView) as RElement, null, null, attrName, attrValue, null, ); break; default: if (ngDevMode) { throw new RuntimeError( RuntimeErrorCode.INVALID_I18N_STRUCTURE, `Unable to determine the type of mutate operation for "${opCode}"`, ); } } } else { switch (opCode) { case ICU_MARKER: const commentValue = mutableOpCodes[++i] as string; const commentNodeIndex = mutableOpCodes[++i] as number; if (lView[commentNodeIndex] === null) { ngDevMode && assertEqual( typeof commentValue, 'string', `Expected "${commentValue}" to be a comment node value`, ); ngDevMode && ngDevMode.rendererCreateComment++; ngDevMode && assertIndexInExpandoRange(lView, commentNodeIndex); const commentRNode = (lView[commentNodeIndex] = _locateOrCreateNode( lView, commentNodeIndex, commentValue, Node.COMMENT_NODE, )); // FIXME(misko): Attaching patch data is only needed for the root (Also add tests) attachPatchData(commentRNode, lView); } break; case ELEMENT_MARKER: const tagName = mutableOpCodes[++i] as string; const elementNodeIndex = mutableOpCodes[++i] as number; if (lView[elementNodeIndex] === null) { ngDevMode && assertEqual( typeof tagName, 'string', `Expected "${tagName}" to be an element node tag name`, ); ngDevMode && ngDevMode.rendererCreateElement++; ngDevMode && assertIndexInExpandoRange(lView, elementNodeIndex); const elementRNode = (lView[elementNodeIndex] = _locateOrCreateNode( lView, elementNodeIndex, tagName, Node.ELEMENT_NODE, )); // FIXME(misko): Attaching patch data is only needed for the root (Also add tests) attachPatchData(elementRNode, lView); } break; default: ngDevMode && throwError(`Unable to determine the type of mutate operation for "${opCode}"`); } } } } /** * Apply `I1
{ "end_byte": 14579, "start_byte": 6554, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_apply.ts" }
angular/packages/core/src/render3/i18n/i18n_apply.ts_14581_21842
UpdateOpCodes` OpCodes * * @param tView Current `TView` * @param lView Current `LView` * @param updateOpCodes OpCodes to process * @param bindingsStartIndex Location of the first `ɵɵi18nApply` * @param changeMask Each bit corresponds to a `ɵɵi18nExp` (Counting backwards from * `bindingsStartIndex`) */ export function applyUpdateOpCodes( tView: TView, lView: LView, updateOpCodes: I18nUpdateOpCodes, bindingsStartIndex: number, changeMask: number, ) { for (let i = 0; i < updateOpCodes.length; i++) { // bit code to check if we should apply the next update const checkBit = updateOpCodes[i] as number; // Number of opCodes to skip until next set of update codes const skipCodes = updateOpCodes[++i] as number; if (checkBit & changeMask) { // The value has been updated since last checked let value = ''; for (let j = i + 1; j <= i + skipCodes; j++) { const opCode = updateOpCodes[j]; if (typeof opCode == 'string') { value += opCode; } else if (typeof opCode == 'number') { if (opCode < 0) { // Negative opCode represent `i18nExp` values offset. value += renderStringify(lView[bindingsStartIndex - opCode]); } else { const nodeIndex = opCode >>> I18nUpdateOpCode.SHIFT_REF; switch (opCode & I18nUpdateOpCode.MASK_OPCODE) { case I18nUpdateOpCode.Attr: const propName = updateOpCodes[++j] as string; const sanitizeFn = updateOpCodes[++j] as SanitizerFn | null; const tNodeOrTagName = tView.data[nodeIndex] as TNode | string; ngDevMode && assertDefined(tNodeOrTagName, 'Experting TNode or string'); if (typeof tNodeOrTagName === 'string') { // IF we don't have a `TNode`, then we are an element in ICU (as ICU content does // not have TNode), in which case we know that there are no directives, and hence // we use attribute setting. setElementAttribute( lView[RENDERER], lView[nodeIndex], null, tNodeOrTagName, propName, value, sanitizeFn, ); } else { elementPropertyInternal( tView, tNodeOrTagName, lView, propName, value, lView[RENDERER], sanitizeFn, false, ); } break; case I18nUpdateOpCode.Text: const rText = lView[nodeIndex] as RText | null; rText !== null && updateTextNode(lView[RENDERER], rText, value); break; case I18nUpdateOpCode.IcuSwitch: applyIcuSwitchCase(tView, getTIcu(tView, nodeIndex)!, lView, value); break; case I18nUpdateOpCode.IcuUpdate: applyIcuUpdateCase(tView, getTIcu(tView, nodeIndex)!, bindingsStartIndex, lView); break; } } } } } else { const opCode = updateOpCodes[i + 1] as number; if (opCode > 0 && (opCode & I18nUpdateOpCode.MASK_OPCODE) === I18nUpdateOpCode.IcuUpdate) { // Special case for the `icuUpdateCase`. It could be that the mask did not match, but // we still need to execute `icuUpdateCase` because the case has changed recently due to // previous `icuSwitchCase` instruction. (`icuSwitchCase` and `icuUpdateCase` always come in // pairs.) const nodeIndex = opCode >>> I18nUpdateOpCode.SHIFT_REF; const tIcu = getTIcu(tView, nodeIndex)!; const currentIndex = lView[tIcu.currentCaseLViewIndex]; if (currentIndex < 0) { applyIcuUpdateCase(tView, tIcu, bindingsStartIndex, lView); } } } i += skipCodes; } } /** * Apply OpCodes associated with updating an existing ICU. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param bindingsStartIndex Location of the first `ɵɵi18nApply` * @param lView Current `LView` */ function applyIcuUpdateCase(tView: TView, tIcu: TIcu, bindingsStartIndex: number, lView: LView) { ngDevMode && assertIndexInRange(lView, tIcu.currentCaseLViewIndex); let activeCaseIndex = lView[tIcu.currentCaseLViewIndex]; if (activeCaseIndex !== null) { let mask = changeMask; if (activeCaseIndex < 0) { // Clear the flag. // Negative number means that the ICU was freshly created and we need to force the update. activeCaseIndex = lView[tIcu.currentCaseLViewIndex] = ~activeCaseIndex; // -1 is same as all bits on, which simulates creation since it marks all bits dirty mask = -1; } applyUpdateOpCodes(tView, lView, tIcu.update[activeCaseIndex], bindingsStartIndex, mask); } } /** * Apply OpCodes associated with switching a case on ICU. * * This involves tearing down existing case and than building up a new case. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param lView Current `LView` * @param value Value of the case to update to. */ function applyIcuSwitchCase(tView: TView, tIcu: TIcu, lView: LView, value: string) { // Rebuild a new case for this ICU const caseIndex = getCaseIndex(tIcu, value); let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView); if (activeCaseIndex !== caseIndex) { applyIcuSwitchCaseRemove(tView, tIcu, lView); lView[tIcu.currentCaseLViewIndex] = caseIndex === null ? null : ~caseIndex; if (caseIndex !== null) { // Add the nodes for the new case const anchorRNode = lView[tIcu.anchorIdx]; if (anchorRNode) { ngDevMode && assertDomNode(anchorRNode); applyMutableOpCodes(tView, tIcu.create[caseIndex], lView, anchorRNode); } claimDehydratedIcuCase(lView, tIcu.anchorIdx, caseIndex); } } } /** * Apply OpCodes associated with tearing ICU case. * * This involves tearing down existing case and than building up a new case. * * @param tView Current `TView` * @param tIcu Current `TIcu` * @param lView Current `LView` */ function applyIcuSwitchCaseRemove(tView: TView, tIcu: TIcu, lView: LView) { let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView); if (activeCaseIndex !== null) { const removeCodes = tIcu.remove[activeCaseIndex]; for (let i = 0; i < removeCodes.length; i++) { const nodeOrIcuIndex = removeCodes[i] as number; if (nodeOrIcuIndex > 0) { // Positive numbers are `RNode`s. const rNode = getNativeByIndex(nodeOrIcuIndex, lView); rNode !== null && nativeRemoveNode(lView[RENDERER], rNode); } else { // Negative numbers are ICUs applyIcuSwitchCaseRemove(tView, getTIcu(tView, ~nodeOrIcuIndex)!, lView); } } } } /** * Returns the index of the current case of an ICU expression depending on the main binding value * * @param icuExpression * @param bindingValue The value of the main binding used by this ICU expression */ function getCaseIndex(i
{ "end_byte": 21842, "start_byte": 14581, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_apply.ts" }
angular/packages/core/src/render3/i18n/i18n_apply.ts_21843_22499
uExpression: TIcu, bindingValue: string): number | null { let index = icuExpression.cases.indexOf(bindingValue); if (index === -1) { switch (icuExpression.type) { case IcuType.plural: { const resolvedCase = getPluralCase(bindingValue, getLocaleId()); index = icuExpression.cases.indexOf(resolvedCase); if (index === -1 && resolvedCase !== 'other') { index = icuExpression.cases.indexOf('other'); } break; } case IcuType.select: { index = icuExpression.cases.indexOf('other'); break; } } } return index === -1 ? null : index; }
{ "end_byte": 22499, "start_byte": 21843, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_apply.ts" }
angular/packages/core/src/render3/i18n/i18n_postprocess.ts_0_5612
/** * @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 */ // i18nPostprocess consts const ROOT_TEMPLATE_ID = 0; const PP_MULTI_VALUE_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]/; const PP_PLACEHOLDERS_REGEXP = /\[(�.+?�?)\]|(�\/?\*\d+:\d+�)/g; const PP_ICU_VARS_REGEXP = /({\s*)(VAR_(PLURAL|SELECT)(_\d+)?)(\s*,)/g; const PP_ICU_PLACEHOLDERS_REGEXP = /{([A-Z0-9_]+)}/g; const PP_ICUS_REGEXP = /�I18N_EXP_(ICU(_\d+)?)�/g; const PP_CLOSE_TEMPLATE_REGEXP = /\/\*/; const PP_TEMPLATE_ID_REGEXP = /\d+\:(\d+)/; // Parsed placeholder structure used in postprocessing (within `i18nPostprocess` function) // Contains the following fields: [templateId, isCloseTemplateTag, placeholder] type PostprocessPlaceholder = [number, boolean, string]; /** * Handles message string post-processing for internationalization. * * Handles message string post-processing by transforming it from intermediate * format (that might contain some markers that we need to replace) to the final * form, consumable by i18nStart instruction. Post processing steps include: * * 1. Resolve all multi-value cases (like [�*1:1��#2:1�|�#4:1�|�5�]) * 2. Replace all ICU vars (like "VAR_PLURAL") * 3. Replace all placeholders used inside ICUs in a form of {PLACEHOLDER} * 4. Replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) * in case multiple ICUs have the same placeholder name * * @param message Raw translation string for post processing * @param replacements Set of replacements that should be applied * * @returns Transformed string that can be consumed by i18nStart instruction * * @codeGenApi */ export function i18nPostprocess( message: string, replacements: {[key: string]: string | string[]} = {}, ): string { /** * Step 1: resolve all multi-value placeholders like [�#5�|�*1:1��#2:1�|�#4:1�] * * Note: due to the way we process nested templates (BFS), multi-value placeholders are typically * grouped by templates, for example: [�#5�|�#6�|�#1:1�|�#3:2�] where �#5� and �#6� belong to root * template, �#1:1� belong to nested template with index 1 and �#1:2� - nested template with index * 3. However in real templates the order might be different: i.e. �#1:1� and/or �#3:2� may go in * front of �#6�. The post processing step restores the right order by keeping track of the * template id stack and looks for placeholders that belong to the currently active template. */ let result: string = message; if (PP_MULTI_VALUE_PLACEHOLDERS_REGEXP.test(message)) { const matches: {[key: string]: PostprocessPlaceholder[]} = {}; const templateIdsStack: number[] = [ROOT_TEMPLATE_ID]; result = result.replace(PP_PLACEHOLDERS_REGEXP, (m: any, phs: string, tmpl: string): string => { const content = phs || tmpl; const placeholders: PostprocessPlaceholder[] = matches[content] || []; if (!placeholders.length) { content.split('|').forEach((placeholder: string) => { const match = placeholder.match(PP_TEMPLATE_ID_REGEXP); const templateId = match ? parseInt(match[1], 10) : ROOT_TEMPLATE_ID; const isCloseTemplateTag = PP_CLOSE_TEMPLATE_REGEXP.test(placeholder); placeholders.push([templateId, isCloseTemplateTag, placeholder]); }); matches[content] = placeholders; } if (!placeholders.length) { throw new Error(`i18n postprocess: unmatched placeholder - ${content}`); } const currentTemplateId = templateIdsStack[templateIdsStack.length - 1]; let idx = 0; // find placeholder index that matches current template id for (let i = 0; i < placeholders.length; i++) { if (placeholders[i][0] === currentTemplateId) { idx = i; break; } } // update template id stack based on the current tag extracted const [templateId, isCloseTemplateTag, placeholder] = placeholders[idx]; if (isCloseTemplateTag) { templateIdsStack.pop(); } else if (currentTemplateId !== templateId) { templateIdsStack.push(templateId); } // remove processed tag from the list placeholders.splice(idx, 1); return placeholder; }); } // return current result if no replacements specified if (!Object.keys(replacements).length) { return result; } /** * Step 2: replace all ICU vars (like "VAR_PLURAL") */ result = result.replace(PP_ICU_VARS_REGEXP, (match, start, key, _type, _idx, end): string => { return replacements.hasOwnProperty(key) ? `${start}${replacements[key]}${end}` : match; }); /** * Step 3: replace all placeholders used inside ICUs in a form of {PLACEHOLDER} */ result = result.replace(PP_ICU_PLACEHOLDERS_REGEXP, (match, key): string => { return replacements.hasOwnProperty(key) ? (replacements[key] as string) : match; }); /** * Step 4: replace all ICU references with corresponding values (like �ICU_EXP_ICU_1�) in case * multiple ICUs have the same placeholder name */ result = result.replace(PP_ICUS_REGEXP, (match, key): string => { if (replacements.hasOwnProperty(key)) { const list = replacements[key] as string[]; if (!list.length) { throw new Error(`i18n postprocess: unmatched ICU - ${match} with key: ${key}`); } return list.shift()!; } return match; }); return result; }
{ "end_byte": 5612, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_postprocess.ts" }
angular/packages/core/src/render3/i18n/i18n_parse.ts_0_3864
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import '../../util/ng_dev_mode'; import '../../util/ng_i18n_closure_mode'; import {XSS_SECURITY_URL} from '../../error_details_base_url'; import { getTemplateContent, URI_ATTRS, VALID_ATTRS, VALID_ELEMENTS, } from '../../sanitization/html_sanitizer'; import {getInertBodyHelper} from '../../sanitization/inert_body'; import {_sanitizeUrl} from '../../sanitization/url_sanitizer'; import { assertDefined, assertEqual, assertGreaterThanOrEqual, assertOneOf, assertString, } from '../../util/assert'; import {CharCode} from '../../util/char_code'; import {loadIcuContainerVisitor} from '../instructions/i18n_icu_container_visitor'; import {allocExpando, createTNodeAtIndex} from '../instructions/shared'; import {getDocument} from '../interfaces/document'; import { ELEMENT_MARKER, I18nCreateOpCode, I18nCreateOpCodes, I18nElementNode, I18nNode, I18nNodeKind, I18nPlaceholderNode, I18nPlaceholderType, I18nRemoveOpCodes, I18nUpdateOpCode, I18nUpdateOpCodes, ICU_MARKER, IcuCreateOpCode, IcuCreateOpCodes, IcuExpression, IcuType, TI18n, TIcu, } from '../interfaces/i18n'; import {TNode, TNodeType} from '../interfaces/node'; import {SanitizerFn} from '../interfaces/sanitization'; import {HEADER_OFFSET, LView, TView} from '../interfaces/view'; import {getCurrentParentTNode, getCurrentTNode, setCurrentTNode} from '../state'; import { i18nCreateOpCodesToString, i18nRemoveOpCodesToString, i18nUpdateOpCodesToString, icuCreateOpCodesToString, } from './i18n_debug'; import {addTNodeAndUpdateInsertBeforeIndex} from './i18n_insert_before_index'; import {ensureIcuContainerVisitorLoaded} from './i18n_tree_shaking'; import { createTNodePlaceholder, icuCreateOpCode, isRootTemplateMessage, setTIcu, setTNodeInsertBeforeIndex, } from './i18n_util'; const BINDING_REGEXP = /�(\d+):?\d*�/gi; const ICU_REGEXP = /({\s*�\d+:?\d*�\s*,\s*\S{6}\s*,[\s\S]*})/gi; const NESTED_ICU = /�(\d+)�/; const ICU_BLOCK_REGEXP = /^\s*(�\d+:?\d*�)\s*,\s*(select|plural)\s*,/; const MARKER = `�`; const SUBTEMPLATE_REGEXP = /�\/?\*(\d+:\d+)�/gi; const PH_REGEXP = /�(\/?[#*]\d+):?\d*�/gi; /** * Angular uses the special entity &ngsp; as a placeholder for non-removable space. * It's replaced by the 0xE500 PUA (Private Use Areas) unicode character and later on replaced by a * space. * We are re-implementing the same idea since translations might contain this special character. */ const NGSP_UNICODE_REGEXP = /\uE500/g; function replaceNgsp(value: string): string { return value.replace(NGSP_UNICODE_REGEXP, ' '); } /** * Patch a `debug` property getter on top of the existing object. * * NOTE: always call this method with `ngDevMode && attachDebugObject(...)` * * @param obj Object to patch * @param debugGetter Getter returning a value to patch */ function attachDebugGetter<T>(obj: T, debugGetter: (this: T) => any): void { if (ngDevMode) { Object.defineProperty(obj, 'debug', {get: debugGetter, enumerable: false}); } else { throw new Error( 'This method should be guarded with `ngDevMode` so that it can be tree shaken in production!', ); } } /** * Create dynamic nodes from i18n translation block. * * - Text nodes are created synchronously * - TNodes are linked into tree lazily * * @param tView Current `TView` * @parentTNodeIndex index to the parent TNode of this i18n block * @param lView Current `LView` * @param index Index of `ɵɵi18nStart` instruction. * @param message Message to translate. * @param subTemplateIndex Index into the sub template of message translation. (ie in case of * `ngIf`) (-1 otherwise) */ export function i18nStartFi
{ "end_byte": 3864, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_parse.ts" }
angular/packages/core/src/render3/i18n/i18n_parse.ts_3865_11016
stCreatePass( tView: TView, parentTNodeIndex: number, lView: LView, index: number, message: string, subTemplateIndex: number, ) { const rootTNode = getCurrentParentTNode(); const createOpCodes: I18nCreateOpCodes = [] as any; const updateOpCodes: I18nUpdateOpCodes = [] as any; const existingTNodeStack: TNode[][] = [[]]; const astStack: Array<Array<I18nNode>> = [[]]; if (ngDevMode) { attachDebugGetter(createOpCodes, i18nCreateOpCodesToString); attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString); } message = getTranslationForTemplate(message, subTemplateIndex); const msgParts = replaceNgsp(message).split(PH_REGEXP); for (let i = 0; i < msgParts.length; i++) { let value = msgParts[i]; if ((i & 1) === 0) { // Even indexes are text (including bindings & ICU expressions) const parts = i18nParseTextIntoPartsAndICU(value); for (let j = 0; j < parts.length; j++) { let part = parts[j]; if ((j & 1) === 0) { // `j` is odd therefore `part` is string const text = part as string; ngDevMode && assertString(text, 'Parsed ICU part should be string'); if (text !== '') { i18nStartFirstCreatePassProcessTextNode( astStack[0], tView, rootTNode, existingTNodeStack[0], createOpCodes, updateOpCodes, lView, text, ); } } else { // `j` is Even therefor `part` is an `ICUExpression` const icuExpression: IcuExpression = part as IcuExpression; // Verify that ICU expression has the right shape. Translations might contain invalid // constructions (while original messages were correct), so ICU parsing at runtime may // not succeed (thus `icuExpression` remains a string). // Note: we intentionally retain the error here by not using `ngDevMode`, because // the value can change based on the locale and users aren't guaranteed to hit // an invalid string while they're developing. if (typeof icuExpression !== 'object') { throw new Error(`Unable to parse ICU expression in "${message}" message.`); } const icuContainerTNode = createTNodeAndAddOpCode( tView, rootTNode, existingTNodeStack[0], lView, createOpCodes, ngDevMode ? `ICU ${index}:${icuExpression.mainBinding}` : '', true, ); const icuNodeIndex = icuContainerTNode.index; ngDevMode && assertGreaterThanOrEqual( icuNodeIndex, HEADER_OFFSET, 'Index must be in absolute LView offset', ); icuStart( astStack[0], tView, lView, updateOpCodes, parentTNodeIndex, icuExpression, icuNodeIndex, ); } } } else { // Odd indexes are placeholders (elements and sub-templates) // At this point value is something like: '/#1:2' (originally coming from '�/#1:2�') const isClosing = value.charCodeAt(0) === CharCode.SLASH; const type = value.charCodeAt(isClosing ? 1 : 0); ngDevMode && assertOneOf(type, CharCode.STAR, CharCode.HASH); const index = HEADER_OFFSET + Number.parseInt(value.substring(isClosing ? 2 : 1)); if (isClosing) { existingTNodeStack.shift(); astStack.shift(); setCurrentTNode(getCurrentParentTNode()!, false); } else { const tNode = createTNodePlaceholder(tView, existingTNodeStack[0], index); existingTNodeStack.unshift([]); setCurrentTNode(tNode, true); const placeholderNode: I18nPlaceholderNode = { kind: I18nNodeKind.PLACEHOLDER, index, children: [], type: type === CharCode.HASH ? I18nPlaceholderType.ELEMENT : I18nPlaceholderType.SUBTEMPLATE, }; astStack[0].push(placeholderNode); astStack.unshift(placeholderNode.children); } } } tView.data[index] = <TI18n>{ create: createOpCodes, update: updateOpCodes, ast: astStack[0], parentTNodeIndex, }; } /** * Allocate space in i18n Range add create OpCode instruction to create a text or comment node. * * @param tView Current `TView` needed to allocate space in i18n range. * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will be * added as part of the `i18nStart` instruction or as part of the `TNode.insertBeforeIndex`. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`. * @param lView Current `LView` needed to allocate space in i18n range. * @param createOpCodes Array storing `I18nCreateOpCodes` where new opCodes will be added. * @param text Text to be added when the `Text` or `Comment` node will be created. * @param isICU true if a `Comment` node for ICU (instead of `Text`) node should be created. */ function createTNodeAndAddOpCode( tView: TView, rootTNode: TNode | null, existingTNodes: TNode[], lView: LView, createOpCodes: I18nCreateOpCodes, text: string | null, isICU: boolean, ): TNode { const i18nNodeIdx = allocExpando(tView, lView, 1, null); let opCode = i18nNodeIdx << I18nCreateOpCode.SHIFT; let parentTNode = getCurrentParentTNode(); if (rootTNode === parentTNode) { // FIXME(misko): A null `parentTNode` should represent when we fall of the `LView` boundary. // (there is no parent), but in some circumstances (because we are inconsistent about how we set // `previousOrParentTNode`) it could point to `rootTNode` So this is a work around. parentTNode = null; } if (parentTNode === null) { // If we don't have a parent that means that we can eagerly add nodes. // If we have a parent than these nodes can't be added now (as the parent has not been created // yet) and instead the `parentTNode` is responsible for adding it. See // `TNode.insertBeforeIndex` opCode |= I18nCreateOpCode.APPEND_EAGERLY; } if (isICU) { opCode |= I18nCreateOpCode.COMMENT; ensureIcuContainerVisitorLoaded(loadIcuContainerVisitor); } createOpCodes.push(opCode, text === null ? '' : text); // We store `{{?}}` so that when looking at debug `TNodeType.template` we can see where the // bindings are. const tNode = createTNodeAtIndex( tView, i18nNodeIdx, isICU ? TNodeType.Icu : TNodeType.Text, text === null ? (ngDevMode ? '{{?}}' : '') : text, null, ); addTNodeAndUpdateInsertBeforeIndex(existingTNodes, tNode); const tNodeIdx = tNode.index; setCurrentTNode(tNode, false /* Text nodes are self closing */); if (parentTNode !== null && rootTNode !== parentTNode) { // We are a child of deeper node (rather than a direct child of `i18nStart` instruction.) // We have to make sure to add ourselves to the parent. setTNodeInsertBeforeIndex(parentTNode, tNodeIdx); } return tNode; } /** * Processes text node in
{ "end_byte": 11016, "start_byte": 3865, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_parse.ts" }
angular/packages/core/src/render3/i18n/i18n_parse.ts_11018_18610
8n block. * * Text nodes can have: * - Create instruction in `createOpCodes` for creating the text node. * - Allocate spec for text node in i18n range of `LView` * - If contains binding: * - bindings => allocate space in i18n range of `LView` to store the binding value. * - populate `updateOpCodes` with update instructions. * * @param tView Current `TView` * @param rootTNode Root `TNode` of the i18n block. This node determines if the new TNode will * be added as part of the `i18nStart` instruction or as part of the * `TNode.insertBeforeIndex`. * @param existingTNodes internal state for `addTNodeAndUpdateInsertBeforeIndex`. * @param createOpCodes Location where the creation OpCodes will be stored. * @param lView Current `LView` * @param text The translated text (which may contain binding) */ function i18nStartFirstCreatePassProcessTextNode( ast: I18nNode[], tView: TView, rootTNode: TNode | null, existingTNodes: TNode[], createOpCodes: I18nCreateOpCodes, updateOpCodes: I18nUpdateOpCodes, lView: LView, text: string, ): void { const hasBinding = text.match(BINDING_REGEXP); const tNode = createTNodeAndAddOpCode( tView, rootTNode, existingTNodes, lView, createOpCodes, hasBinding ? null : text, false, ); const index = tNode.index; if (hasBinding) { generateBindingUpdateOpCodes(updateOpCodes, text, index, null, 0, null); } ast.push({kind: I18nNodeKind.TEXT, index}); } /** * See `i18nAttributes` above. */ export function i18nAttributesFirstPass(tView: TView, index: number, values: string[]) { const previousElement = getCurrentTNode()!; const previousElementIndex = previousElement.index; const updateOpCodes: I18nUpdateOpCodes = [] as any; if (ngDevMode) { attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString); } if (tView.firstCreatePass && tView.data[index] === null) { for (let i = 0; i < values.length; i += 2) { const attrName = values[i]; const message = values[i + 1]; if (message !== '') { // Check if attribute value contains an ICU and throw an error if that's the case. // ICUs in element attributes are not supported. // Note: we intentionally retain the error here by not using `ngDevMode`, because // the `value` can change based on the locale and users aren't guaranteed to hit // an invalid string while they're developing. if (ICU_REGEXP.test(message)) { throw new Error( `ICU expressions are not supported in attributes. Message: "${message}".`, ); } // i18n attributes that hit this code path are guaranteed to have bindings, because // the compiler treats static i18n attributes as regular attribute bindings. // Since this may not be the first i18n attribute on this element we need to pass in how // many previous bindings there have already been. generateBindingUpdateOpCodes( updateOpCodes, message, previousElementIndex, attrName, countBindings(updateOpCodes), null, ); } } tView.data[index] = updateOpCodes; } } /** * Generate the OpCodes to update the bindings of a string. * * @param updateOpCodes Place where the update opcodes will be stored. * @param str The string containing the bindings. * @param destinationNode Index of the destination node which will receive the binding. * @param attrName Name of the attribute, if the string belongs to an attribute. * @param sanitizeFn Sanitization function used to sanitize the string after update, if necessary. * @param bindingStart The lView index of the next expression that can be bound via an opCode. * @returns The mask value for these bindings */ function generateBindingUpdateOpCodes( updateOpCodes: I18nUpdateOpCodes, str: string, destinationNode: number, attrName: string | null, bindingStart: number, sanitizeFn: SanitizerFn | null, ): number { ngDevMode && assertGreaterThanOrEqual( destinationNode, HEADER_OFFSET, 'Index must be in absolute LView offset', ); const maskIndex = updateOpCodes.length; // Location of mask const sizeIndex = maskIndex + 1; // location of size for skipping updateOpCodes.push(null, null); // Alloc space for mask and size const startIndex = maskIndex + 2; // location of first allocation. if (ngDevMode) { attachDebugGetter(updateOpCodes, i18nUpdateOpCodesToString); } const textParts = str.split(BINDING_REGEXP); let mask = 0; for (let j = 0; j < textParts.length; j++) { const textValue = textParts[j]; if (j & 1) { // Odd indexes are bindings const bindingIndex = bindingStart + parseInt(textValue, 10); updateOpCodes.push(-1 - bindingIndex); mask = mask | toMaskBit(bindingIndex); } else if (textValue !== '') { // Even indexes are text updateOpCodes.push(textValue); } } updateOpCodes.push( (destinationNode << I18nUpdateOpCode.SHIFT_REF) | (attrName ? I18nUpdateOpCode.Attr : I18nUpdateOpCode.Text), ); if (attrName) { updateOpCodes.push(attrName, sanitizeFn); } updateOpCodes[maskIndex] = mask; updateOpCodes[sizeIndex] = updateOpCodes.length - startIndex; return mask; } /** * Count the number of bindings in the given `opCodes`. * * It could be possible to speed this up, by passing the number of bindings found back from * `generateBindingUpdateOpCodes()` to `i18nAttributesFirstPass()` but this would then require more * complexity in the code and/or transient objects to be created. * * Since this function is only called once when the template is instantiated, is trivial in the * first instance (since `opCodes` will be an empty array), and it is not common for elements to * contain multiple i18n bound attributes, it seems like this is a reasonable compromise. */ function countBindings(opCodes: I18nUpdateOpCodes): number { let count = 0; for (let i = 0; i < opCodes.length; i++) { const opCode = opCodes[i]; // Bindings are negative numbers. if (typeof opCode === 'number' && opCode < 0) { count++; } } return count; } /** * Convert binding index to mask bit. * * Each index represents a single bit on the bit-mask. Because bit-mask only has 32 bits, we make * the 32nd bit share all masks for all bindings higher than 32. Since it is extremely rare to * have more than 32 bindings this will be hit very rarely. The downside of hitting this corner * case is that we will execute binding code more often than necessary. (penalty of performance) */ function toMaskBit(bindingIndex: number): number { return 1 << Math.min(bindingIndex, 31); } /** * Removes everything inside the sub-templates of a message. */ function removeInnerTemplateTranslation(message: string): string { let match; let res = ''; let index = 0; let inTemplate = false; let tagMatched; while ((match = SUBTEMPLATE_REGEXP.exec(message)) !== null) { if (!inTemplate) { res += message.substring(index, match.index + match[0].length); tagMatched = match[1]; inTemplate = true; } else { if (match[0] === `${MARKER}/*${tagMatched}${MARKER}`) { index = match.index; inTemplate = false; } } } ngDevMode && assertEqual( inTemplate, false, `Tag mismatch: unable to find the end of the sub-template in the translation "${message}"`, ); res += message.slice(index); return res; } /** * Extracts a part of a me
{ "end_byte": 18610, "start_byte": 11018, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_parse.ts" }
angular/packages/core/src/render3/i18n/i18n_parse.ts_18612_24873
age and removes the rest. * * This method is used for extracting a part of the message associated with a template. A * translated message can span multiple templates. * * Example: * ``` * <div i18n>Translate <span *ngIf>me</span>!</div> * ``` * * @param message The message to crop * @param subTemplateIndex Index of the sub-template to extract. If undefined it returns the * external template and removes all sub-templates. */ export function getTranslationForTemplate(message: string, subTemplateIndex: number) { if (isRootTemplateMessage(subTemplateIndex)) { // We want the root template message, ignore all sub-templates return removeInnerTemplateTranslation(message); } else { // We want a specific sub-template const start = message.indexOf(`:${subTemplateIndex}${MARKER}`) + 2 + subTemplateIndex.toString().length; const end = message.search(new RegExp(`${MARKER}\\/\\*\\d+:${subTemplateIndex}${MARKER}`)); return removeInnerTemplateTranslation(message.substring(start, end)); } } /** * Generate the OpCodes for ICU expressions. * * @param icuExpression * @param index Index where the anchor is stored and an optional `TIcuContainerNode` * - `lView[anchorIdx]` points to a `Comment` node representing the anchor for the ICU. * - `tView.data[anchorIdx]` points to the `TIcuContainerNode` if ICU is root (`null` otherwise) */ function icuStart( ast: I18nNode[], tView: TView, lView: LView, updateOpCodes: I18nUpdateOpCodes, parentIdx: number, icuExpression: IcuExpression, anchorIdx: number, ) { ngDevMode && assertDefined(icuExpression, 'ICU expression must be defined'); let bindingMask = 0; const tIcu: TIcu = { type: icuExpression.type, currentCaseLViewIndex: allocExpando(tView, lView, 1, null), anchorIdx, cases: [], create: [], remove: [], update: [], }; addUpdateIcuSwitch(updateOpCodes, icuExpression, anchorIdx); setTIcu(tView, anchorIdx, tIcu); const values = icuExpression.values; const cases: I18nNode[][] = []; for (let i = 0; i < values.length; i++) { // Each value is an array of strings & other ICU expressions const valueArr = values[i]; const nestedIcus: IcuExpression[] = []; for (let j = 0; j < valueArr.length; j++) { const value = valueArr[j]; if (typeof value !== 'string') { // It is an nested ICU expression const icuIndex = nestedIcus.push(value as IcuExpression) - 1; // Replace nested ICU expression by a comment node valueArr[j] = `<!--�${icuIndex}�-->`; } } const caseAst: I18nNode[] = []; cases.push(caseAst); bindingMask = parseIcuCase( caseAst, tView, tIcu, lView, updateOpCodes, parentIdx, icuExpression.cases[i], valueArr.join(''), nestedIcus, ) | bindingMask; } if (bindingMask) { addUpdateIcuUpdate(updateOpCodes, bindingMask, anchorIdx); } ast.push({ kind: I18nNodeKind.ICU, index: anchorIdx, cases, currentCaseLViewIndex: tIcu.currentCaseLViewIndex, }); } /** * Parses text containing an ICU expression and produces a JSON object for it. * Original code from closure library, modified for Angular. * * @param pattern Text containing an ICU expression that needs to be parsed. * */ function parseICUBlock(pattern: string): IcuExpression { const cases = []; const values: (string | IcuExpression)[][] = []; let icuType = IcuType.plural; let mainBinding = 0; pattern = pattern.replace( ICU_BLOCK_REGEXP, function (str: string, binding: string, type: string) { if (type === 'select') { icuType = IcuType.select; } else { icuType = IcuType.plural; } mainBinding = parseInt(binding.slice(1), 10); return ''; }, ); const parts = i18nParseTextIntoPartsAndICU(pattern) as string[]; // Looking for (key block)+ sequence. One of the keys has to be "other". for (let pos = 0; pos < parts.length; ) { let key = parts[pos++].trim(); if (icuType === IcuType.plural) { // Key can be "=x", we just want "x" key = key.replace(/\s*(?:=)?(\w+)\s*/, '$1'); } if (key.length) { cases.push(key); } const blocks = i18nParseTextIntoPartsAndICU(parts[pos++]) as string[]; if (cases.length > values.length) { values.push(blocks); } } // TODO(ocombe): support ICU expressions in attributes, see #21615 return {type: icuType, mainBinding: mainBinding, cases, values}; } /** * Breaks pattern into strings and top level {...} blocks. * Can be used to break a message into text and ICU expressions, or to break an ICU expression * into keys and cases. Original code from closure library, modified for Angular. * * @param pattern (sub)Pattern to be broken. * @returns An `Array<string|IcuExpression>` where: * - odd positions: `string` => text between ICU expressions * - even positions: `ICUExpression` => ICU expression parsed into `ICUExpression` record. */ function i18nParseTextIntoPartsAndICU(pattern: string): (string | IcuExpression)[] { if (!pattern) { return []; } let prevPos = 0; const braceStack = []; const results: (string | IcuExpression)[] = []; const braces = /[{}]/g; // lastIndex doesn't get set to 0 so we have to. braces.lastIndex = 0; let match; while ((match = braces.exec(pattern))) { const pos = match.index; if (match[0] == '}') { braceStack.pop(); if (braceStack.length == 0) { // End of the block. const block = pattern.substring(prevPos, pos); if (ICU_BLOCK_REGEXP.test(block)) { results.push(parseICUBlock(block)); } else { results.push(block); } prevPos = pos + 1; } } else { if (braceStack.length == 0) { const substring = pattern.substring(prevPos, pos); results.push(substring); prevPos = pos + 1; } braceStack.push('{'); } } const substring = pattern.substring(prevPos); results.push(substring); return results; } /** * Parses a node, its children and its siblings, and generates the mutate & update OpCodes. * */ function parseIcuCase( ast: I18nN
{ "end_byte": 24873, "start_byte": 18612, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_parse.ts" }
angular/packages/core/src/render3/i18n/i18n_parse.ts_24874_31780
de[], tView: TView, tIcu: TIcu, lView: LView, updateOpCodes: I18nUpdateOpCodes, parentIdx: number, caseName: string, unsafeCaseHtml: string, nestedIcus: IcuExpression[], ): number { const create: IcuCreateOpCodes = [] as any; const remove: I18nRemoveOpCodes = [] as any; const update: I18nUpdateOpCodes = [] as any; if (ngDevMode) { attachDebugGetter(create, icuCreateOpCodesToString); attachDebugGetter(remove, i18nRemoveOpCodesToString); attachDebugGetter(update, i18nUpdateOpCodesToString); } tIcu.cases.push(caseName); tIcu.create.push(create); tIcu.remove.push(remove); tIcu.update.push(update); const inertBodyHelper = getInertBodyHelper(getDocument()); const inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeCaseHtml); ngDevMode && assertDefined(inertBodyElement, 'Unable to generate inert body element'); const inertRootNode = (getTemplateContent(inertBodyElement!) as Element) || inertBodyElement; if (inertRootNode) { return walkIcuTree( ast, tView, tIcu, lView, updateOpCodes, create, remove, update, inertRootNode, parentIdx, nestedIcus, 0, ); } else { return 0; } } function walkIcuTree( ast: I18nNode[], tView: TView, tIcu: TIcu, lView: LView, sharedUpdateOpCodes: I18nUpdateOpCodes, create: IcuCreateOpCodes, remove: I18nRemoveOpCodes, update: I18nUpdateOpCodes, parentNode: Element, parentIdx: number, nestedIcus: IcuExpression[], depth: number, ): number { let bindingMask = 0; let currentNode = parentNode.firstChild; while (currentNode) { const newIndex = allocExpando(tView, lView, 1, null); switch (currentNode.nodeType) { case Node.ELEMENT_NODE: const element = currentNode as Element; const tagName = element.tagName.toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName)) { addCreateNodeAndAppend(create, ELEMENT_MARKER, tagName, parentIdx, newIndex); tView.data[newIndex] = tagName; const elAttrs = element.attributes; for (let i = 0; i < elAttrs.length; i++) { const attr = elAttrs.item(i)!; const lowerAttrName = attr.name.toLowerCase(); const hasBinding = !!attr.value.match(BINDING_REGEXP); // we assume the input string is safe, unless it's using a binding if (hasBinding) { if (VALID_ATTRS.hasOwnProperty(lowerAttrName)) { if (URI_ATTRS[lowerAttrName]) { generateBindingUpdateOpCodes( update, attr.value, newIndex, attr.name, 0, _sanitizeUrl, ); } else { generateBindingUpdateOpCodes(update, attr.value, newIndex, attr.name, 0, null); } } else { ngDevMode && console.warn( `WARNING: ignoring unsafe attribute value ` + `${lowerAttrName} on element ${tagName} ` + `(see ${XSS_SECURITY_URL})`, ); } } else { addCreateAttribute(create, newIndex, attr); } } const elementNode: I18nElementNode = { kind: I18nNodeKind.ELEMENT, index: newIndex, children: [], }; ast.push(elementNode); // Parse the children of this node (if any) bindingMask = walkIcuTree( elementNode.children, tView, tIcu, lView, sharedUpdateOpCodes, create, remove, update, currentNode as Element, newIndex, nestedIcus, depth + 1, ) | bindingMask; addRemoveNode(remove, newIndex, depth); } break; case Node.TEXT_NODE: const value = currentNode.textContent || ''; const hasBinding = value.match(BINDING_REGEXP); addCreateNodeAndAppend(create, null, hasBinding ? '' : value, parentIdx, newIndex); addRemoveNode(remove, newIndex, depth); if (hasBinding) { bindingMask = generateBindingUpdateOpCodes(update, value, newIndex, null, 0, null) | bindingMask; } ast.push({ kind: I18nNodeKind.TEXT, index: newIndex, }); break; case Node.COMMENT_NODE: // Check if the comment node is a placeholder for a nested ICU const isNestedIcu = NESTED_ICU.exec(currentNode.textContent || ''); if (isNestedIcu) { const nestedIcuIndex = parseInt(isNestedIcu[1], 10); const icuExpression: IcuExpression = nestedIcus[nestedIcuIndex]; // Create the comment node that will anchor the ICU expression addCreateNodeAndAppend( create, ICU_MARKER, ngDevMode ? `nested ICU ${nestedIcuIndex}` : '', parentIdx, newIndex, ); icuStart(ast, tView, lView, sharedUpdateOpCodes, parentIdx, icuExpression, newIndex); addRemoveNestedIcu(remove, newIndex, depth); } break; } currentNode = currentNode.nextSibling; } return bindingMask; } function addRemoveNode(remove: I18nRemoveOpCodes, index: number, depth: number) { if (depth === 0) { remove.push(index); } } function addRemoveNestedIcu(remove: I18nRemoveOpCodes, index: number, depth: number) { if (depth === 0) { remove.push(~index); // remove ICU at `index` remove.push(index); // remove ICU comment at `index` } } function addUpdateIcuSwitch( update: I18nUpdateOpCodes, icuExpression: IcuExpression, index: number, ) { update.push( toMaskBit(icuExpression.mainBinding), 2, -1 - icuExpression.mainBinding, (index << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.IcuSwitch, ); } function addUpdateIcuUpdate(update: I18nUpdateOpCodes, bindingMask: number, index: number) { update.push(bindingMask, 1, (index << I18nUpdateOpCode.SHIFT_REF) | I18nUpdateOpCode.IcuUpdate); } function addCreateNodeAndAppend( create: IcuCreateOpCodes, marker: null | ICU_MARKER | ELEMENT_MARKER, text: string, appendToParentIdx: number, createAtIdx: number, ) { if (marker !== null) { create.push(marker); } create.push( text, createAtIdx, icuCreateOpCode(IcuCreateOpCode.AppendChild, appendToParentIdx, createAtIdx), ); } function addCreateAttribute(create: IcuCreateOpCodes, newIndex: number, attr: Attr) { create.push( (newIndex << IcuCreateOpCode.SHIFT_REF) | IcuCreateOpCode.Attr, attr.name, attr.value, ); }
{ "end_byte": 31780, "start_byte": 24874, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_parse.ts" }
angular/packages/core/src/render3/i18n/i18n_insert_before_index.ts_0_3869
/** * @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} from '../../util/assert'; import {TNode, TNodeType} from '../interfaces/node'; import {setI18nHandling} from '../node_manipulation'; import {getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore} from '../node_manipulation_i18n'; /** * Add `tNode` to `previousTNodes` list and update relevant `TNode`s in `previousTNodes` list * `tNode.insertBeforeIndex`. * * Things to keep in mind: * 1. All i18n text nodes are encoded as `TNodeType.Element` and are created eagerly by the * `ɵɵi18nStart` instruction. * 2. All `TNodeType.Placeholder` `TNodes` are elements which will be created later by * `ɵɵelementStart` instruction. * 3. `ɵɵelementStart` instruction will create `TNode`s in the ascending `TNode.index` order. (So a * smaller index `TNode` is guaranteed to be created before a larger one) * * We use the above three invariants to determine `TNode.insertBeforeIndex`. * * In an ideal world `TNode.insertBeforeIndex` would always be `TNode.next.index`. However, * this will not work because `TNode.next.index` may be larger than `TNode.index` which means that * the next node is not yet created and therefore we can't insert in front of it. * * Rule1: `TNode.insertBeforeIndex = null` if `TNode.next === null` (Initial condition, as we don't * know if there will be further `TNode`s inserted after.) * Rule2: If `previousTNode` is created after the `tNode` being inserted, then * `previousTNode.insertBeforeNode = tNode.index` (So when a new `tNode` is added we check * previous to see if we can update its `insertBeforeTNode`) * * See `TNode.insertBeforeIndex` for more context. * * @param previousTNodes A list of previous TNodes so that we can easily traverse `TNode`s in * reverse order. (If `TNode` would have `previous` this would not be necessary.) * @param newTNode A TNode to add to the `previousTNodes` list. */ export function addTNodeAndUpdateInsertBeforeIndex(previousTNodes: TNode[], newTNode: TNode) { // Start with Rule1 ngDevMode && assertEqual(newTNode.insertBeforeIndex, null, 'We expect that insertBeforeIndex is not set'); previousTNodes.push(newTNode); if (previousTNodes.length > 1) { for (let i = previousTNodes.length - 2; i >= 0; i--) { const existingTNode = previousTNodes[i]; // Text nodes are created eagerly and so they don't need their `indexBeforeIndex` updated. // It is safe to ignore them. if (!isI18nText(existingTNode)) { if ( isNewTNodeCreatedBefore(existingTNode, newTNode) && getInsertBeforeIndex(existingTNode) === null ) { // If it was created before us in time, (and it does not yet have `insertBeforeIndex`) // then add the `insertBeforeIndex`. setInsertBeforeIndex(existingTNode, newTNode.index); } } } } } function isI18nText(tNode: TNode): boolean { return !(tNode.type & TNodeType.Placeholder); } function isNewTNodeCreatedBefore(existingTNode: TNode, newTNode: TNode): boolean { return isI18nText(newTNode) || existingTNode.index > newTNode.index; } function getInsertBeforeIndex(tNode: TNode): number | null { const index = tNode.insertBeforeIndex; return Array.isArray(index) ? index[0] : index; } function setInsertBeforeIndex(tNode: TNode, value: number): void { const index = tNode.insertBeforeIndex; if (Array.isArray(index)) { // Array is stored if we have to insert child nodes. See `TNode.insertBeforeIndex` index[0] = value; } else { setI18nHandling(getInsertInFrontOfRNodeWithI18n, processI18nInsertBefore); tNode.insertBeforeIndex = value; } }
{ "end_byte": 3869, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_insert_before_index.ts" }
angular/packages/core/src/render3/i18n/i18n_locale_id.ts_0_1363
/** * @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 {DEFAULT_LOCALE_ID} from '../../i18n/localization'; import {assertDefined} from '../../util/assert'; /** * The locale id that the application is currently using (for translations and ICU expressions). * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine * but is now defined as a global value. */ let LOCALE_ID = DEFAULT_LOCALE_ID; /** * Sets the locale id that will be used for translations and ICU expressions. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine * but is now defined as a global value. * * @param localeId */ export function setLocaleId(localeId: string) { ngDevMode && assertDefined(localeId, `Expected localeId to be defined`); if (typeof localeId === 'string') { LOCALE_ID = localeId.toLowerCase().replace(/_/g, '-'); } } /** * Gets the locale id that will be used for translations and ICU expressions. * This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine * but is now defined as a global value. */ export function getLocaleId(): string { return LOCALE_ID; }
{ "end_byte": 1363, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/i18n/i18n_locale_id.ts" }
angular/packages/core/src/render3/after_render/manager.ts_0_5565
/** * @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 {AfterRenderPhase, AfterRenderRef} from './api'; import {NgZone} from '../../zone'; import {inject} from '../../di/injector_compatibility'; import {ɵɵdefineInjectable} from '../../di/interface/defs'; import {ErrorHandler} from '../../error_handler'; import { ChangeDetectionScheduler, NotificationSource, } from '../../change_detection/scheduling/zoneless_scheduling'; import {type DestroyRef} from '../../linker/destroy_ref'; export class AfterRenderManager { impl: AfterRenderImpl | null = null; execute(): void { this.impl?.execute(); } /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: AfterRenderManager, providedIn: 'root', factory: () => new AfterRenderManager(), }); } export class AfterRenderImpl { static readonly PHASES = /* @__PURE__ **/ (() => [ AfterRenderPhase.EarlyRead, AfterRenderPhase.Write, AfterRenderPhase.MixedReadWrite, AfterRenderPhase.Read, ] as const)(); private readonly ngZone = inject(NgZone); private readonly scheduler = inject(ChangeDetectionScheduler); private readonly errorHandler = inject(ErrorHandler, {optional: true}); /** Current set of active sequences. */ private readonly sequences = new Set<AfterRenderSequence>(); /** Tracks registrations made during the current set of executions. */ private readonly deferredRegistrations = new Set<AfterRenderSequence>(); /** Whether the `AfterRenderManager` is currently executing hooks. */ executing = false; /** * Run the sequence of phases of hooks, once through. As a result of executing some hooks, more * might be scheduled. */ execute(): void { this.executing = true; for (const phase of AfterRenderImpl.PHASES) { for (const sequence of this.sequences) { if (sequence.erroredOrDestroyed || !sequence.hooks[phase]) { continue; } try { sequence.pipelinedValue = this.ngZone.runOutsideAngular(() => sequence.hooks[phase]!(sequence.pipelinedValue), ); } catch (err) { sequence.erroredOrDestroyed = true; this.errorHandler?.handleError(err); } } } this.executing = false; // Cleanup step to reset sequence state and also collect one-shot sequences for removal. for (const sequence of this.sequences) { sequence.afterRun(); if (sequence.once) { this.sequences.delete(sequence); // Destroy the sequence so its on destroy callbacks can be cleaned up // immediately, instead of waiting until the injector is destroyed. sequence.destroy(); } } for (const sequence of this.deferredRegistrations) { this.sequences.add(sequence); } if (this.deferredRegistrations.size > 0) { this.scheduler.notify(NotificationSource.DeferredRenderHook); } this.deferredRegistrations.clear(); } register(sequence: AfterRenderSequence): void { if (!this.executing) { this.sequences.add(sequence); // Trigger an `ApplicationRef.tick()` if one is not already pending/running, because we have a // new render hook that needs to run. this.scheduler.notify(NotificationSource.RenderHook); } else { this.deferredRegistrations.add(sequence); } } unregister(sequence: AfterRenderSequence): void { if (this.executing && this.sequences.has(sequence)) { // We can't remove an `AfterRenderSequence` in the middle of iteration. // Instead, mark it as destroyed so it doesn't run any more, and mark it as one-shot so it'll // be removed at the end of the current execution. sequence.erroredOrDestroyed = true; sequence.pipelinedValue = undefined; sequence.once = true; } else { // It's safe to directly remove this sequence. this.sequences.delete(sequence); this.deferredRegistrations.delete(sequence); } } /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: AfterRenderImpl, providedIn: 'root', factory: () => new AfterRenderImpl(), }); } export type AfterRenderHook = (value?: unknown) => unknown; export type AfterRenderHooks = [ /* EarlyRead */ AfterRenderHook | undefined, /* Write */ AfterRenderHook | undefined, /* MixedReadWrite */ AfterRenderHook | undefined, /* Read */ AfterRenderHook | undefined, ]; export class AfterRenderSequence implements AfterRenderRef { /** * Whether this sequence errored or was destroyed during this execution, and hooks should no * longer run for it. */ erroredOrDestroyed: boolean = false; /** * The value returned by the last hook execution (if any), ready to be pipelined into the next * one. */ pipelinedValue: unknown = undefined; private unregisterOnDestroy: (() => void) | undefined; constructor( readonly impl: AfterRenderImpl, readonly hooks: AfterRenderHooks, public once: boolean, destroyRef: DestroyRef | null, ) { this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy()); } afterRun(): void { this.erroredOrDestroyed = false; this.pipelinedValue = undefined; } destroy(): void { this.impl.unregister(this); this.unregisterOnDestroy?.(); } }
{ "end_byte": 5565, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/after_render/manager.ts" }
angular/packages/core/src/render3/after_render/api.ts_0_2801
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * The phase to run an `afterRender` or `afterNextRender` callback in. * * Callbacks in the same phase run in the order they are registered. Phases run in the * following order after each render: * * 1. `AfterRenderPhase.EarlyRead` * 2. `AfterRenderPhase.Write` * 3. `AfterRenderPhase.MixedReadWrite` * 4. `AfterRenderPhase.Read` * * Angular is unable to verify or enforce that phases are used correctly, and instead * relies on each developer to follow the guidelines documented for each value and * carefully choose the appropriate one, refactoring their code if necessary. By doing * so, Angular is better able to minimize the performance degradation associated with * manual DOM access, ensuring the best experience for the end users of your application * or library. * * @deprecated Specify the phase for your callback to run in by passing a spec-object as the first * parameter to `afterRender` or `afterNextRender` instead of a function. */ export enum AfterRenderPhase { /** * Use `AfterRenderPhase.EarlyRead` for callbacks that only need to **read** from the * DOM before a subsequent `AfterRenderPhase.Write` callback, for example to perform * custom layout that the browser doesn't natively support. Prefer the * `AfterRenderPhase.EarlyRead` phase if reading can wait until after the write phase. * **Never** write to the DOM in this phase. * * <div class="alert is-important"> * * Using this value can degrade performance. * Instead, prefer using built-in browser functionality when possible. * * </div> */ EarlyRead, /** * Use `AfterRenderPhase.Write` for callbacks that only **write** to the DOM. **Never** * read from the DOM in this phase. */ Write, /** * Use `AfterRenderPhase.MixedReadWrite` for callbacks that read from or write to the * DOM, that haven't been refactored to use a different phase. **Never** use this phase if * it is possible to divide the work among the other phases instead. * * <div class="alert is-critical"> * * Using this value can **significantly** degrade performance. * Instead, prefer dividing work into the appropriate phase callbacks. * * </div> */ MixedReadWrite, /** * Use `AfterRenderPhase.Read` for callbacks that only **read** from the DOM. **Never** * write to the DOM in this phase. */ Read, } /** * A callback that runs after render. * * @developerPreview */ export interface AfterRenderRef { /** * Shut down the callback, preventing it from being called again. */ destroy(): void; }
{ "end_byte": 2801, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/after_render/api.ts" }
angular/packages/core/src/render3/after_render/hooks.ts_0_7700
/** * @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 {assertInInjectionContext} from '../../di'; import {Injector} from '../../di/injector'; import {inject} from '../../di/injector_compatibility'; import {DestroyRef} from '../../linker/destroy_ref'; import {performanceMarkFeature} from '../../util/performance'; import {assertNotInReactiveContext} from '../reactivity/asserts'; import {isPlatformBrowser} from '../util/misc_utils'; import {AfterRenderPhase, AfterRenderRef} from './api'; import { AfterRenderHooks, AfterRenderImpl, AfterRenderManager, AfterRenderSequence, } from './manager'; /** * 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 ɵFirstAvailable<T extends unknown[]> = T extends [infer H, ...infer R] ? [H] extends [never] ? ɵFirstAvailable<R> : [H] : []; /** * Options passed to `afterRender` and `afterNextRender`. * * @developerPreview */ export interface AfterRenderOptions { /** * The `Injector` to use during creation. * * If this is not provided, the current injection context will be used instead (via `inject`). */ injector?: Injector; /** * Whether the hook should require manual cleanup. * * If this is `false` (the default) the hook will automatically register itself to be cleaned up * with the current `DestroyRef`. */ manualCleanup?: boolean; /** * The phase the callback should be invoked in. * * <div class="alert is-critical"> * * Defaults to `AfterRenderPhase.MixedReadWrite`. You should choose a more specific * phase instead. See `AfterRenderPhase` for more information. * * </div> * * @deprecated Specify the phase for your callback to run in by passing a spec-object as the first * parameter to `afterRender` or `afterNextRender` instead of a function. */ phase?: AfterRenderPhase; } /** * Register callbacks to be invoked each time 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: * - Callbacks run in the following phase order *after each render*: * 1. `earlyRead` * 2. `write` * 3. `mixedReadWrite` * 4. `read` * - Callbacks in the same phase run in the order they are registered. * - Callbacks run on browser platforms only, they will not run on the server. * * 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 parameter. 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 callback functions to register * @param options Options to control the behavior of the callback * * @usageNotes * * Use `afterRender` to read or write the DOM after each render. * * ### Example * ```ts * @Component({ * selector: 'my-cmp', * template: `<span #content>{{ ... }}</span>`, * }) * export class MyComponent { * @ViewChild('content') contentRef: ElementRef; * * constructor() { * afterRender({ * read: () => { * console.log('content height: ' + this.contentRef.nativeElement.scrollHeight); * } * }); * } * } * ``` * * @developerPreview */ export function afterRender<E = never, W = never, M = never>( spec: { earlyRead?: () => E; write?: (...args: ɵFirstAvailable<[E]>) => W; mixedReadWrite?: (...args: ɵFirstAvailable<[W, E]>) => M; read?: (...args: ɵFirstAvailable<[M, W, E]>) => void; }, options?: Omit<AfterRenderOptions, 'phase'>, ): AfterRenderRef; /** * Register a callback to be invoked each time the application finishes rendering, during the * `mixedReadWrite` phase. * * <div class="alert is-critical"> * * You should prefer specifying an explicit phase for the callback instead, or you risk significant * performance degradation. * * </div> * * Note that the callback will run * - in the order it was registered * - once per render * - on browser platforms only * - 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 A callback function to register * @param options Options to control the behavior of the callback * * @usageNotes * * Use `afterRender` to read or write the DOM after each render. * * ### Example * ```ts * @Component({ * selector: 'my-cmp', * template: `<span #content>{{ ... }}</span>`, * }) * export class MyComponent { * @ViewChild('content') contentRef: ElementRef; * * constructor() { * afterRender({ * read: () => { * console.log('content height: ' + this.contentRef.nativeElement.scrollHeight); * } * }); * } * } * ``` * * @developerPreview */ export function afterRender(callback: VoidFunction, options?: AfterRenderOptions): AfterRenderRef; export function afterRender( callbackOrSpec: | VoidFunction | { earlyRead?: () => unknown; write?: (r?: unknown) => unknown; mixedReadWrite?: (r?: unknown) => unknown; read?: (r?: unknown) => void; }, options?: AfterRenderOptions, ): AfterRenderRef { ngDevMode && assertNotInReactiveContext( afterRender, 'Call `afterRender` outside of a reactive context. For example, schedule the render ' + 'callback inside the component constructor`.', ); !options?.injector && assertInInjectionContext(afterRender); const injector = options?.injector ?? inject(Injector); if (!isPlatformBrowser(injector)) { return NOOP_AFTER_RENDER_REF; } performanceMarkFeature('NgAfterRender'); return afterRenderImpl(callbackOrSpec, injector, options, /* once */ false); } /**
{ "end_byte": 7700, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/after_render/hooks.ts" }
angular/packages/core/src/render3/after_render/hooks.ts_7702_14954
* Register callbacks to be invoked the next time 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: * - Callbacks run in the following phase order *once, after the next render*: * 1. `earlyRead` * 2. `write` * 3. `mixedReadWrite` * 4. `read` * - Callbacks in the same phase run in the order they are registered. * - Callbacks run on browser platforms only, they will not run on the server. * * 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 parameter. 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 callback functions to register * @param options Options to control the behavior of the callback * * @usageNotes * * Use `afterNextRender` to read or write the DOM once, * for example to initialize a non-Angular library. * * ### Example * ```ts * @Component({ * selector: 'my-chart-cmp', * template: `<div #chart>{{ ... }}</div>`, * }) * export class MyChartCmp { * @ViewChild('chart') chartRef: ElementRef; * chart: MyChart|null; * * constructor() { * afterNextRender({ * write: () => { * this.chart = new MyChart(this.chartRef.nativeElement); * } * }); * } * } * ``` * * @developerPreview */ export function afterNextRender<E = never, W = never, M = never>( spec: { earlyRead?: () => E; write?: (...args: ɵFirstAvailable<[E]>) => W; mixedReadWrite?: (...args: ɵFirstAvailable<[W, E]>) => M; read?: (...args: ɵFirstAvailable<[M, W, E]>) => void; }, options?: Omit<AfterRenderOptions, 'phase'>, ): AfterRenderRef; /** * Register a callback to be invoked the next time the application finishes rendering, during the * `mixedReadWrite` phase. * * <div class="alert is-critical"> * * You should prefer specifying an explicit phase for the callback instead, or you risk significant * performance degradation. * * </div> * * Note that the callback will run * - in the order it was registered * - 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 A callback function to register * @param options Options to control the behavior of the callback * * @usageNotes * * Use `afterNextRender` to read or write the DOM once, * for example to initialize a non-Angular library. * * ### Example * ```ts * @Component({ * selector: 'my-chart-cmp', * template: `<div #chart>{{ ... }}</div>`, * }) * export class MyChartCmp { * @ViewChild('chart') chartRef: ElementRef; * chart: MyChart|null; * * constructor() { * afterNextRender({ * write: () => { * this.chart = new MyChart(this.chartRef.nativeElement); * } * }); * } * } * ``` * * @developerPreview */ export function afterNextRender( callback: VoidFunction, options?: AfterRenderOptions, ): AfterRenderRef; export function afterNextRender( callbackOrSpec: | VoidFunction | { earlyRead?: () => unknown; write?: (r?: unknown) => unknown; mixedReadWrite?: (r?: unknown) => unknown; read?: (r?: unknown) => void; }, options?: AfterRenderOptions, ): AfterRenderRef { !options?.injector && assertInInjectionContext(afterNextRender); const injector = options?.injector ?? inject(Injector); if (!isPlatformBrowser(injector)) { return NOOP_AFTER_RENDER_REF; } performanceMarkFeature('NgAfterNextRender'); return afterRenderImpl(callbackOrSpec, injector, options, /* once */ true); } function getHooks( callbackOrSpec: | VoidFunction | { earlyRead?: () => unknown; write?: (r?: unknown) => unknown; mixedReadWrite?: (r?: unknown) => unknown; read?: (r?: unknown) => void; }, phase: AfterRenderPhase, ): AfterRenderHooks { if (callbackOrSpec instanceof Function) { const hooks: AfterRenderHooks = [undefined, undefined, undefined, undefined]; hooks[phase] = callbackOrSpec; return hooks; } else { return [ callbackOrSpec.earlyRead, callbackOrSpec.write, callbackOrSpec.mixedReadWrite, callbackOrSpec.read, ]; } } /** * Shared implementation for `afterRender` and `afterNextRender`. */ function afterRenderImpl( callbackOrSpec: | VoidFunction | { earlyRead?: () => unknown; write?: (r?: unknown) => unknown; mixedReadWrite?: (r?: unknown) => unknown; read?: (r?: unknown) => void; }, injector: Injector, options: AfterRenderOptions | undefined, once: boolean, ): AfterRenderRef { const manager = injector.get(AfterRenderManager); // Lazily initialize the handler implementation, if necessary. This is so that it can be // tree-shaken if `afterRender` and `afterNextRender` aren't used. manager.impl ??= injector.get(AfterRenderImpl); const hooks = options?.phase ?? AfterRenderPhase.MixedReadWrite; const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null; const sequence = new AfterRenderSequence( manager.impl, getHooks(callbackOrSpec, hooks), once, destroyRef, ); manager.impl.register(sequence); return sequence; } /** `AfterRenderRef` that does nothing. */ export const NOOP_AFTER_RENDER_REF: AfterRenderRef = { destroy() {}, };
{ "end_byte": 14954, "start_byte": 7702, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/after_render/hooks.ts" }
angular/packages/core/src/render3/interfaces/sanitization.ts_0_534
/** * @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 {TrustedHTML, TrustedScript, TrustedScriptURL} from '../../util/security/trusted_type_defs'; /** * Function used to sanitize the value before writing it into the renderer. */ export type SanitizerFn = ( value: any, tagName?: string, propName?: string, ) => string | TrustedHTML | TrustedScript | TrustedScriptURL;
{ "end_byte": 534, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/sanitization.ts" }
angular/packages/core/src/render3/interfaces/type_checks.ts_0_1958
/** * @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 {LContainer, TYPE} from './container'; import {ComponentDef, DirectiveDef} from './definition'; import {TNode, TNodeFlags, TNodeType} from './node'; import {RNode} from './renderer_dom'; import {FLAGS, LView, LViewFlags} from './view'; /** * True if `value` is `LView`. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ export function isLView(value: RNode | LView | LContainer | {} | null): value is LView { return Array.isArray(value) && typeof value[TYPE] === 'object'; } /** * True if `value` is `LContainer`. * @param value wrapped value of `RNode`, `LView`, `LContainer` */ export function isLContainer(value: RNode | LView | LContainer | {} | null): value is LContainer { return Array.isArray(value) && value[TYPE] === true; } export function isContentQueryHost(tNode: TNode): boolean { return (tNode.flags & TNodeFlags.hasContentQuery) !== 0; } export function isComponentHost(tNode: TNode): boolean { return tNode.componentOffset > -1; } export function isDirectiveHost(tNode: TNode): boolean { return (tNode.flags & TNodeFlags.isDirectiveHost) === TNodeFlags.isDirectiveHost; } export function isComponentDef<T>(def: DirectiveDef<T>): def is ComponentDef<T> { return !!(def as ComponentDef<T>).template; } export function isRootView(target: LView): boolean { return (target[FLAGS] & LViewFlags.IsRoot) !== 0; } export function isProjectionTNode(tNode: TNode): boolean { return (tNode.type & TNodeType.Projection) === TNodeType.Projection; } export function hasI18n(lView: LView): boolean { return (lView[FLAGS] & LViewFlags.HasI18n) === LViewFlags.HasI18n; } export function isDestroyed(lView: LView): boolean { return (lView[FLAGS] & LViewFlags.Destroyed) === LViewFlags.Destroyed; }
{ "end_byte": 1958, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/type_checks.ts" }
angular/packages/core/src/render3/interfaces/projection.ts_0_2214
/** * @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 */ /** * Expresses a single CSS Selector. * * Beginning of array * - First index: element name * - Subsequent odd indices: attr keys * - Subsequent even indices: attr values * * After SelectorFlags.CLASS flag * - Class name values * * SelectorFlags.NOT flag * - Changes the mode to NOT * - Can be combined with other flags to set the element / attr / class mode * * e.g. SelectorFlags.NOT | SelectorFlags.ELEMENT * * Example: * Original: `div.foo.bar[attr1=val1][attr2]` * Parsed: ['div', 'attr1', 'val1', 'attr2', '', SelectorFlags.CLASS, 'foo', 'bar'] * * Original: 'div[attr1]:not(.foo[attr2]) * Parsed: [ * 'div', 'attr1', '', * SelectorFlags.NOT | SelectorFlags.ATTRIBUTE 'attr2', '', SelectorFlags.CLASS, 'foo' * ] * * See more examples in node_selector_matcher_spec.ts */ export type CssSelector = (string | SelectorFlags)[]; /** * A list of CssSelectors. * * A directive or component can have multiple selectors. This type is used for * directive defs so any of the selectors in the list will match that directive. * * Original: 'form, [ngForm]' * Parsed: [['form'], ['', 'ngForm', '']] */ export type CssSelectorList = CssSelector[]; /** * List of slots for a projection. A slot can be either based on a parsed CSS selector * which will be used to determine nodes which are projected into that slot. * * When set to "*", the slot is reserved and can be used for multi-slot projection * using {@link ViewContainerRef#createComponent}. The last slot that specifies the * wildcard selector will retrieve all projectable nodes which do not match any selector. */ export type ProjectionSlots = (CssSelectorList | '*')[]; /** Flags used to build up CssSelectors */ export const enum SelectorFlags { /** Indicates this is the beginning of a new negative selector */ NOT = 0b0001, /** Mode for matching attributes */ ATTRIBUTE = 0b0010, /** Mode for matching tag names */ ELEMENT = 0b0100, /** Mode for matching class names */ CLASS = 0b1000, }
{ "end_byte": 2214, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/projection.ts" }
angular/packages/core/src/render3/interfaces/node.ts_0_7681
/** * @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} from '../../util/array_utils'; import {TStylingRange} from '../interfaces/styling'; import {AttributeMarker} from './attribute_marker'; import {InputFlags} from './input_flags'; import {TIcu} from './i18n'; import {CssSelector} from './projection'; import {RNode} from './renderer_dom'; import type {LView, TView} from './view'; /** * TNodeType corresponds to the {@link TNode} `type` property. * * NOTE: type IDs are such that we use each bit to denote a type. This is done so that we can easily * check if the `TNode` is of more than one type. * * `if (tNode.type === TNodeType.Text || tNode.type === TNode.Element)` * can be written as: * `if (tNode.type & (TNodeType.Text | TNodeType.Element))` * * However any given `TNode` can only be of one type. */ export const enum TNodeType { /** * The TNode contains information about a DOM element aka {@link RText}. */ Text = 0b1, /** * The TNode contains information about a DOM element aka {@link RElement}. */ Element = 0b10, /** * The TNode contains information about an {@link LContainer} for embedded views. */ Container = 0b100, /** * The TNode contains information about an `<ng-container>` element {@link RNode}. */ ElementContainer = 0b1000, /** * The TNode contains information about an `<ng-content>` projection */ Projection = 0b10000, /** * The TNode contains information about an ICU comment used in `i18n`. */ Icu = 0b100000, /** * Special node type representing a placeholder for future `TNode` at this location. * * I18n translation blocks are created before the element nodes which they contain. (I18n blocks * can span over many elements.) Because i18n `TNode`s (representing text) are created first they * often may need to point to element `TNode`s which are not yet created. In such a case we create * a `Placeholder` `TNode`. This allows the i18n to structurally link the `TNode`s together * without knowing any information about the future nodes which will be at that location. * * On `firstCreatePass` When element instruction executes it will try to create a `TNode` at that * location. Seeing a `Placeholder` `TNode` already there tells the system that it should reuse * existing `TNode` (rather than create a new one) and just update the missing information. */ Placeholder = 0b1000000, /** * The TNode contains information about a `@let` declaration. */ LetDeclaration = 0b10000000, // Combined Types These should never be used for `TNode.type` only as a useful way to check // if `TNode.type` is one of several choices. // See: https://github.com/microsoft/TypeScript/issues/35875 why we can't refer to existing enum. AnyRNode = 0b11, // Text | Element AnyContainer = 0b1100, // Container | ElementContainer } /** * Converts `TNodeType` into human readable text. * Make sure this matches with `TNodeType` */ export function toTNodeTypeAsString(tNodeType: TNodeType): string { let text = ''; tNodeType & TNodeType.Text && (text += '|Text'); tNodeType & TNodeType.Element && (text += '|Element'); tNodeType & TNodeType.Container && (text += '|Container'); tNodeType & TNodeType.ElementContainer && (text += '|ElementContainer'); tNodeType & TNodeType.Projection && (text += '|Projection'); tNodeType & TNodeType.Icu && (text += '|IcuContainer'); tNodeType & TNodeType.Placeholder && (text += '|Placeholder'); tNodeType & TNodeType.LetDeclaration && (text += '|LetDeclaration'); return text.length > 0 ? text.substring(1) : text; } /** * Helper function to detect if a given value matches a `TNode` shape. * * The logic uses the `insertBeforeIndex` and its possible values as * a way to differentiate a TNode shape from other types of objects * within the `TView.data`. This is not a perfect check, but it can * be a reasonable differentiator, since we control the shapes of objects * within `TView.data`. */ export function isTNodeShape(value: unknown): value is TNode { return ( value != null && typeof value === 'object' && ((value as TNode).insertBeforeIndex === null || typeof (value as TNode).insertBeforeIndex === 'number' || Array.isArray((value as TNode).insertBeforeIndex)) ); } export function isLetDeclaration(tNode: TNode): boolean { return !!(tNode.type & TNodeType.LetDeclaration); } /** * Corresponds to the TNode.flags property. */ export const enum TNodeFlags { /** Bit #1 - This bit is set if the node is a host for any directive (including a component) */ isDirectiveHost = 0x1, /** Bit #2 - This bit is set if the node has been projected */ isProjected = 0x2, /** Bit #3 - This bit is set if any directive on this node has content queries */ hasContentQuery = 0x4, /** Bit #4 - This bit is set if the node has any "class" inputs */ hasClassInput = 0x8, /** Bit #5 - This bit is set if the node has any "style" inputs */ hasStyleInput = 0x10, /** Bit #6 - This bit is set if the node has been detached by i18n */ isDetached = 0x20, /** * Bit #7 - This bit is set if the node has directives with host bindings. * * This flags allows us to guard host-binding logic and invoke it only on nodes * that actually have directives with host bindings. */ hasHostBindings = 0x40, /** * Bit #8 - This bit is set if the node is a located inside skip hydration block. */ inSkipHydrationBlock = 0x80, } /** * Corresponds to the TNode.providerIndexes property. */ export const enum TNodeProviderIndexes { /** The index of the first provider on this node is encoded on the least significant bits. */ ProvidersStartIndexMask = 0b00000000000011111111111111111111, /** * The count of view providers from the component on this node is * encoded on the 20 most significant bits. */ CptViewProvidersCountShift = 20, CptViewProvidersCountShifter = 0b00000000000100000000000000000000, } /** * A combination of: * - Attribute names and values. * - Special markers acting as flags to alter attributes processing. * - Parsed ngProjectAs selectors. */ export type TAttributes = (string | AttributeMarker | CssSelector)[]; /** * Constants that are associated with a view. Includes: * - Attribute arrays. * - Local definition arrays. * - Translated messages (i18n). */ export type TConstants = (TAttributes | string)[]; /** * Factory function that returns an array of consts. Consts can be represented as a function in * case any additional statements are required to define consts in the list. An example is i18n * where additional i18n calls are generated, which should be executed when consts are requested * for the first time. */ export type TConstantsFactory = () => TConstants; /** * TConstants type that describes how the `consts` field is generated on ComponentDef: it can be * either an array or a factory function that returns that array. */ export type TConstantsOrFactory = TConstants | TConstantsFactory; /** * Binding data (flyweight) for a particular node that is shared between all templates * of a specific type. * * If a property is: * - PropertyAliases: that property's data was generated and this is it * - Null: that property's data was already generated and nothing was found. * - Undefined: that property's data has not yet been generated * * see: https://en.wikipedia.org/wiki/Flyweight_pattern for more on the Flyweight pattern */
{ "end_byte": 7681, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/node.ts" }
angular/packages/core/src/render3/interfaces/node.ts_7682_15009
export interface TNode { /** The type of the TNode. See TNodeType. */ type: TNodeType; /** * Index of the TNode in TView.data and corresponding native element in LView. * * This is necessary to get from any TNode to its corresponding native element when * traversing the node tree. * * If index is -1, this is a dynamically created container node or embedded view node. */ index: number; /** * Insert before existing DOM node index. * * When DOM nodes are being inserted, normally they are being appended as they are created. * Under i18n case, the translated text nodes are created ahead of time as part of the * `ɵɵi18nStart` instruction which means that this `TNode` can't just be appended and instead * needs to be inserted using `insertBeforeIndex` semantics. * * Additionally sometimes it is necessary to insert new text nodes as a child of this `TNode`. In * such a case the value stores an array of text nodes to insert. * * Example: * ``` * <div i18n> * Hello <span>World</span>! * </div> * ``` * In the above example the `ɵɵi18nStart` instruction can create `Hello `, `World` and `!` text * nodes. It can also insert `Hello ` and `!` text node as a child of `<div>`, but it can't * insert `World` because the `<span>` node has not yet been created. In such a case the * `<span>` `TNode` will have an array which will direct the `<span>` to not only insert * itself in front of `!` but also to insert the `World` (created by `ɵɵi18nStart`) into * `<span>` itself. * * Pseudo code: * ``` * if (insertBeforeIndex === null) { * // append as normal * } else if (Array.isArray(insertBeforeIndex)) { * // First insert current `TNode` at correct location * const currentNode = lView[this.index]; * parentNode.insertBefore(currentNode, lView[this.insertBeforeIndex[0]]); * // Now append all of the children * for(let i=1; i<this.insertBeforeIndex; i++) { * currentNode.appendChild(lView[this.insertBeforeIndex[i]]); * } * } else { * parentNode.insertBefore(lView[this.index], lView[this.insertBeforeIndex]) * } * ``` * - null: Append as normal using `parentNode.appendChild` * - `number`: Append using * `parentNode.insertBefore(lView[this.index], lView[this.insertBeforeIndex])` * * *Initialization* * * Because `ɵɵi18nStart` executes before nodes are created, on `TView.firstCreatePass` it is not * possible for `ɵɵi18nStart` to set the `insertBeforeIndex` value as the corresponding `TNode` * has not yet been created. For this reason the `ɵɵi18nStart` creates a `TNodeType.Placeholder` * `TNode` at that location. See `TNodeType.Placeholder` for more information. */ insertBeforeIndex: InsertBeforeIndex; /** * The index of the closest injector in this node's LView. * * If the index === -1, there is no injector on this node or any ancestor node in this view. * * If the index !== -1, it is the index of this node's injector OR the index of a parent * injector in the same view. We pass the parent injector index down the node tree of a view so * it's possible to find the parent injector without walking a potentially deep node tree. * Injector indices are not set across view boundaries because there could be multiple component * hosts. * * If tNode.injectorIndex === tNode.parent.injectorIndex, then the index belongs to a parent * injector. */ injectorIndex: number; /** Stores starting index of the directives. */ directiveStart: number; /** * Stores final exclusive index of the directives. * * The area right behind the `directiveStart-directiveEnd` range is used to allocate the * `HostBindingFunction` `vars` (or null if no bindings.) Therefore `directiveEnd` is used to set * `LFrame.bindingRootIndex` before `HostBindingFunction` is executed. */ directiveEnd: number; /** * Offset from the `directiveStart` at which the component (one at most) of the node is stored. * Set to -1 if no components have been applied to the node. Component index can be found using * `directiveStart + componentOffset`. */ componentOffset: number; /** * Stores the last directive which had a styling instruction. * * Initial value of this is `-1` which means that no `hostBindings` styling instruction has * executed. As `hostBindings` instructions execute they set the value to the index of the * `DirectiveDef` which contained the last `hostBindings` styling instruction. * * Valid values are: * - `-1` No `hostBindings` instruction has executed. * - `directiveStart <= directiveStylingLast < directiveEnd`: Points to the `DirectiveDef` of * the last styling instruction which executed in the `hostBindings`. * * This data is needed so that styling instructions know which static styling data needs to be * collected from the `DirectiveDef.hostAttrs`. A styling instruction needs to collect all data * since last styling instruction. */ directiveStylingLast: number; /** * Stores indexes of property bindings. This field is only set in the ngDevMode and holds * indexes of property bindings so TestBed can get bound property metadata for a given node. */ propertyBindings: number[] | null; /** * Stores if Node isComponent, isProjected, hasContentQuery, hasClassInput and hasStyleInput * etc. */ flags: TNodeFlags; /** * This number stores two values using its bits: * * - the index of the first provider on that node (first 16 bits) * - the count of view providers from the component on this node (last 16 bits) */ // TODO(misko): break this into actual vars. providerIndexes: TNodeProviderIndexes; /** * The value name associated with this node. * if type: * `TNodeType.Text`: text value * `TNodeType.Element`: tag name * `TNodeType.ICUContainer`: `TIcu` */ value: any; /** * Attributes associated with an element. We need to store attributes to support various * use-cases (attribute injection, content projection with selectors, directives matching). * Attributes are stored statically because reading them from the DOM would be way too slow for * content projection and queries. * * Since attrs will always be calculated first, they will never need to be marked undefined by * other instructions. * * For regular attributes a name of an attribute and its value alternate in the array. * e.g. ['role', 'checkbox'] * This array can contain flags that will indicate "special attributes" (attributes with * namespaces, attributes extracted from bindings and outputs). */ attrs: TAttributes | null; /** * Same as `TNode.attrs` but contains merged data across all directive host bindings. * * We need to keep `attrs` as unmerged so that it can be used for attribute selectors. * We merge attrs here so that it can be used in a performant way for initial rendering. * * The `attrs` are merged in first pass in following order: * - Component's `hostAttrs` * - Directives' `hostAttrs` * - Template `TNode.attrs` associated with the current `TNode`. */ mergedAttrs: TAttributes | null; /** *
{ "end_byte": 15009, "start_byte": 7682, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/node.ts" }
angular/packages/core/src/render3/interfaces/node.ts_15013_22530
et of local names under which a given element is exported in a template and * visible to queries. An entry in this array can be created for different reasons: * - an element itself is referenced, ex.: `<div #foo>` * - a component is referenced, ex.: `<my-cmpt #foo>` * - a directive is referenced, ex.: `<my-cmpt #foo="directiveExportAs">`. * * A given element might have different local names and those names can be associated * with a directive. We store local names at even indexes while odd indexes are reserved * for directive index in a view (or `-1` if there is no associated directive). * * Some examples: * - `<div #foo>` => `["foo", -1]` * - `<my-cmpt #foo>` => `["foo", myCmptIdx]` * - `<my-cmpt #foo #bar="directiveExportAs">` => `["foo", myCmptIdx, "bar", directiveIdx]` * - `<div #foo #bar="directiveExportAs">` => `["foo", -1, "bar", directiveIdx]` */ localNames: (string | number)[] | null; /** Information about input properties that need to be set once from attribute data. */ initialInputs: InitialInputData | null | undefined; /** * Input data for all directives on this node. `null` means that there are no directives with * inputs on this node. */ inputs: NodeInputBindings | null; /** * Output data for all directives on this node. `null` means that there are no directives with * outputs on this node. */ outputs: NodeOutputBindings | null; /** * The TView attached to this node. * * If this TNode corresponds to an LContainer with a template (e.g. structural * directive), the template's TView will be stored here. * * If this TNode corresponds to an element, tView will be `null`. */ tView: TView | null; /** * The next sibling node. Necessary so we can propagate through the root nodes of a view * to insert them or remove them from the DOM. */ next: TNode | null; /** * The previous sibling node. * This simplifies operations when we need a pointer to the previous node. */ prev: TNode | null; /** * The next projected sibling. Since in Angular content projection works on the node-by-node * basis the act of projecting nodes might change nodes relationship at the insertion point * (target view). At the same time we need to keep initial relationship between nodes as * expressed in content view. */ projectionNext: TNode | null; /** * First child of the current node. * * For component nodes, the child will always be a ContentChild (in same view). * For embedded view nodes, the child will be in their child view. */ child: TNode | null; /** * Parent node (in the same view only). * * We need a reference to a node's parent so we can append the node to its parent's native * element at the appropriate time. * * If the parent would be in a different view (e.g. component host), this property will be null. * It's important that we don't try to cross component boundaries when retrieving the parent * because the parent will change (e.g. index, attrs) depending on where the component was * used (and thus shouldn't be stored on TNode). In these cases, we retrieve the parent through * LView.node instead (which will be instance-specific). * * If this is an inline view node (V), the parent will be its container. */ parent: TElementNode | TContainerNode | null; /** * List of projected TNodes for a given component host element OR index into the said nodes. * * For easier discussion assume this example: * `<parent>`'s view definition: * ``` * <child id="c1">content1</child> * <child id="c2"><span>content2</span></child> * ``` * `<child>`'s view definition: * ``` * <ng-content id="cont1"></ng-content> * ``` * * If `Array.isArray(projection)` then `TNode` is a host element: * - `projection` stores the content nodes which are to be projected. * - The nodes represent categories defined by the selector: For example: * `<ng-content/><ng-content select="abc"/>` would represent the heads for `<ng-content/>` * and `<ng-content select="abc"/>` respectively. * - The nodes we store in `projection` are heads only, we used `.next` to get their * siblings. * - The nodes `.next` is sorted/rewritten as part of the projection setup. * - `projection` size is equal to the number of projections `<ng-content>`. The size of * `c1` will be `1` because `<child>` has only one `<ng-content>`. * - we store `projection` with the host (`c1`, `c2`) rather than the `<ng-content>` (`cont1`) * because the same component (`<child>`) can be used in multiple locations (`c1`, `c2`) and * as a result have different set of nodes to project. * - without `projection` it would be difficult to efficiently traverse nodes to be projected. * * If `typeof projection == 'number'` then `TNode` is a `<ng-content>` element: * - `projection` is an index of the host's `projection`Nodes. * - This would return the first head node to project: * `getHost(currentTNode).projection[currentTNode.projection]`. * - When projecting nodes the parent node retrieved may be a `<ng-content>` node, in which case * the process is recursive in nature. * * If `projection` is of type `RNode[][]` than we have a collection of native nodes passed as * projectable nodes during dynamic component creation. */ projection: (TNode | RNode[])[] | number | null; /** * A collection of all `style` static values for an element (including from host). * * This field will be populated if and when: * * - There are one or more initial `style`s on an element (e.g. `<div style="width:200px;">`) * - There are one or more initial `style`s on a directive/component host * (e.g. `@Directive({host: {style: "width:200px;" } }`) */ styles: string | null; /** * A collection of all `style` static values for an element excluding host sources. * * Populated when there are one or more initial `style`s on an element * (e.g. `<div style="width:200px;">`) * Must be stored separately from `tNode.styles` to facilitate setting directive * inputs that shadow the `style` property. If we used `tNode.styles` as is for shadowed inputs, * we would feed host styles back into directives as "inputs". If we used `tNode.attrs`, we * would have to concatenate the attributes on every template pass. Instead, we process once on * first create pass and store here. */ stylesWithoutHost: string | null; /** * A `KeyValueArray` version of residual `styles`. * * When there are styling instructions than each instruction stores the static styling * which is of lower priority than itself. This means that there may be a higher priority * styling than the instruction. * * Imagine: * ``` * <div style="color: highest;" my-dir> * * @Directive({ * host: { * style: 'color: lowest; ', * '[styles.color]': 'exp' // ɵɵstyleProp('color', ctx.exp); * } * }) * ``` * * In the above case: * - `color: lowest` is stored with `ɵɵstyleProp('color', ctx.exp);` instruction * - `color: highest` is the residual and is stored here. * * - `undefined': not initialized. * - `null`: initialized but `styles` is `null` * - `KeyValueArray`: parsed version of `styles`. */ residualStyles: KeyValueArray<any> | undefined | null; /** * A c
{ "end_byte": 22530, "start_byte": 15013, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/node.ts" }
angular/packages/core/src/render3/interfaces/node.ts_22534_29798
ction of all class static values for an element (including from host). * * This field will be populated if and when: * * - There are one or more initial classes on an element (e.g. `<div class="one two three">`) * - There are one or more initial classes on an directive/component host * (e.g. `@Directive({host: {class: "SOME_CLASS" } }`) */ classes: string | null; /** * A collection of all class static values for an element excluding host sources. * * Populated when there are one or more initial classes on an element * (e.g. `<div class="SOME_CLASS">`) * Must be stored separately from `tNode.classes` to facilitate setting directive * inputs that shadow the `class` property. If we used `tNode.classes` as is for shadowed * inputs, we would feed host classes back into directives as "inputs". If we used * `tNode.attrs`, we would have to concatenate the attributes on every template pass. Instead, * we process once on first create pass and store here. */ classesWithoutHost: string | null; /** * A `KeyValueArray` version of residual `classes`. * * Same as `TNode.residualStyles` but for classes. * * - `undefined': not initialized. * - `null`: initialized but `classes` is `null` * - `KeyValueArray`: parsed version of `classes`. */ residualClasses: KeyValueArray<any> | undefined | null; /** * Stores the head/tail index of the class bindings. * * - If no bindings, the head and tail will both be 0. * - If there are template bindings, stores the head/tail of the class bindings in the template. * - If no template bindings but there are host bindings, the head value will point to the last * host binding for "class" (not the head of the linked list), tail will be 0. * * See: `style_binding_list.ts` for details. * * This is used by `insertTStylingBinding` to know where the next styling binding should be * inserted so that they can be sorted in priority order. */ classBindings: TStylingRange; /** * Stores the head/tail index of the class bindings. * * - If no bindings, the head and tail will both be 0. * - If there are template bindings, stores the head/tail of the style bindings in the template. * - If no template bindings but there are host bindings, the head value will point to the last * host binding for "style" (not the head of the linked list), tail will be 0. * * See: `style_binding_list.ts` for details. * * This is used by `insertTStylingBinding` to know where the next styling binding should be * inserted so that they can be sorted in priority order. */ styleBindings: TStylingRange; } /** * See `TNode.insertBeforeIndex` */ export type InsertBeforeIndex = null | number | number[]; /** Static data for an element */ export interface TElementNode extends TNode { /** Index in the data[] array */ index: number; child: TElementNode | TTextNode | TElementContainerNode | TContainerNode | TProjectionNode | null; /** * Element nodes will have parents unless they are the first node of a component or * embedded view (which means their parent is in a different view and must be * retrieved using viewData[HOST_NODE]). */ parent: TElementNode | TElementContainerNode | null; tView: null; /** * If this is a component TNode with projection, this will be an array of projected * TNodes or native nodes (see TNode.projection for more info). If it's a regular element node * or a component without projection, it will be null. */ projection: (TNode | RNode[])[] | null; /** * Stores TagName */ value: string; } /** Static data for a text node */ export interface TTextNode extends TNode { /** Index in the data[] array */ index: number; child: null; /** * Text nodes will have parents unless they are the first node of a component or * embedded view (which means their parent is in a different view and must be * retrieved using LView.node). */ parent: TElementNode | TElementContainerNode | null; tView: null; projection: null; } /** Static data for an LContainer */ export interface TContainerNode extends TNode { /** * Index in the data[] array. * * If it's -1, this is a dynamically created container node that isn't stored in * data[] (e.g. when you inject ViewContainerRef) . */ index: number; child: null; /** * Container nodes will have parents unless: * * - They are the first node of a component or embedded view * - They are dynamically created */ parent: TElementNode | TElementContainerNode | null; tView: TView | null; projection: null; value: null; } /** Static data for an <ng-container> */ export interface TElementContainerNode extends TNode { /** Index in the LView[] array. */ index: number; child: TElementNode | TTextNode | TContainerNode | TElementContainerNode | TProjectionNode | null; parent: TElementNode | TElementContainerNode | null; tView: null; projection: null; } /** Static data for an ICU expression */ export interface TIcuContainerNode extends TNode { /** Index in the LView[] array. */ index: number; child: null; parent: TElementNode | TElementContainerNode | null; tView: null; projection: null; value: TIcu; } /** Static data for an LProjectionNode */ export interface TProjectionNode extends TNode { /** Index in the data[] array */ child: null; /** * Projection nodes will have parents unless they are the first node of a component * or embedded view (which means their parent is in a different view and must be * retrieved using LView.node). */ parent: TElementNode | TElementContainerNode | null; tView: null; /** Index of the projection node. (See TNode.projection for more info.) */ projection: number; value: null; } /** * Static data for a `@let` declaration. This node is necessary, because the expression of a * `@let` declaration can contain code that uses the node injector (e.g. pipes). In order for * the node injector to work, it needs this `TNode`. */ export interface TLetDeclarationNode extends TNode { index: number; child: null; parent: TElementNode | TElementContainerNode | null; tView: null; projection: null; value: null; // TODO(crisbeto): capture the name here? Might come in handy for the dev tools. } /** * A union type representing all TNode types that can host a directive. */ export type TDirectiveHostNode = TElementNode | TContainerNode | TElementContainerNode; /** * Store the runtime output names for all the directives. * * i+0: directive instance index * i+1: privateName * * e.g. * ``` * { * "publicName": [0, 'change-minified'] * } */ export type NodeOutputBindings = Record<string, (number | string)[]>; /** * Store the runtime input for all directives applied to a node. * * This allows efficiently setting the same input on a directive that * might apply to multiple directives. * * i+0: directive instance index * i+1: privateName * i+2: input flags * * e.g. * ``` * { * "publicName": [0, 'change-minified', <bit-input-flags>] * } * ``` */ export type NodeInputBindings = Record<string, (number | string | InputFlags)[]>; /** * This ar
{ "end_byte": 29798, "start_byte": 22534, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/node.ts" }
angular/packages/core/src/render3/interfaces/node.ts_29800_32269
y contains information about input properties that * need to be set once from attribute data. It's ordered by * directive index (relative to element) so it's simple to * look up a specific directive's initial input data. * * Within each sub-array: * * i+0: attribute name * i+1: minified/internal input name * i+2: initial value * * If a directive on a node does not have any input properties * that should be set from attributes, its index is set to null * to avoid a sparse array. * * e.g. [null, ['role-min', 'minified-input', 'button']] */ export type InitialInputData = (InitialInputs | null)[]; /** * Used by InitialInputData to store input properties * that should be set once from attributes. * * i+0: attribute name * i+1: minified/internal input name * i+2: input flags * i+3: initial value * * e.g. ['role-min', 'minified-input', 'button'] */ export type InitialInputs = (string | InputFlags)[]; /** * Type representing a set of TNodes that can have local refs (`#foo`) placed on them. */ export type TNodeWithLocalRefs = TContainerNode | TElementNode | TElementContainerNode; /** * Type for a function that extracts a value for a local refs. * Example: * - `<div #nativeDivEl>` - `nativeDivEl` should point to the native `<div>` element; * - `<ng-template #tplRef>` - `tplRef` should point to the `TemplateRef` instance; */ export type LocalRefExtractor = (tNode: TNodeWithLocalRefs, currentView: LView) => any; /** * Returns `true` if the `TNode` has a directive which has `@Input()` for `class` binding. * * ``` * <div my-dir [class]="exp"></div> * ``` * and * ``` * @Directive({ * }) * class MyDirective { * @Input() * class: string; * } * ``` * * In the above case it is necessary to write the reconciled styling information into the * directive's input. * * @param tNode */ export function hasClassInput(tNode: TNode) { return (tNode.flags & TNodeFlags.hasClassInput) !== 0; } /** * Returns `true` if the `TNode` has a directive which has `@Input()` for `style` binding. * * ``` * <div my-dir [style]="exp"></div> * ``` * and * ``` * @Directive({ * }) * class MyDirective { * @Input() * class: string; * } * ``` * * In the above case it is necessary to write the reconciled styling information into the * directive's input. * * @param tNode */ export function hasStyleInput(tNode: TNode) { return (tNode.flags & TNodeFlags.hasStyleInput) !== 0; }
{ "end_byte": 32269, "start_byte": 29800, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/node.ts" }
angular/packages/core/src/render3/interfaces/i18n.ts_0_6732
/** * @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 './sanitization'; /** * Stores a list of nodes which need to be removed. * * Numbers are indexes into the `LView` * - index > 0: `removeRNode(lView[0])` * - index < 0: `removeICU(~lView[0])` */ export interface I18nRemoveOpCodes extends Array<number> { __brand__: 'I18nRemoveOpCodes'; } /** * `I18nMutateOpCode` defines OpCodes for `I18nMutateOpCodes` array. * * OpCodes are efficient operations which can be applied to the DOM to update it. (For example to * update to a new ICU case requires that we clean up previous elements and create new ones.) * * OpCodes contain three parts: * 1) Parent node index offset. (p) * 2) Reference node index offset. (r) * 3) The instruction to execute. (i) * * pppp pppp pppp pppp rrrr rrrr rrrr riii * 3322 2222 2222 1111 1111 1110 0000 0000 * 1098 7654 3210 9876 5432 1098 7654 3210 * * ``` * var parent = lView[opCode >>> SHIFT_PARENT]; * var refNode = lView[((opCode & MASK_REF) >>> SHIFT_REF)]; * var instruction = opCode & MASK_OPCODE; * ``` * * See: `I18nCreateOpCodes` for example of usage. */ export const enum IcuCreateOpCode { /** * Stores shift amount for bits 17-3 that contain reference index. */ SHIFT_REF = 1, /** * Stores shift amount for bits 31-17 that contain parent index. */ SHIFT_PARENT = 17, /** * Mask for OpCode */ MASK_INSTRUCTION = 0b1, /** * Mask for the Reference node (bits 16-3) */ MASK_REF = 0b11111111111111110, // 11111110000000000 // 65432109876543210 /** * Instruction to append the current node to `PARENT`. */ AppendChild = 0b0, /** * Instruction to set the attribute of a node. */ Attr = 0b1, } /** * Array storing OpCode for dynamically creating `i18n` blocks. * * Example: * ```ts * <I18nCreateOpCode>[ * // For adding text nodes * // --------------------- * // Equivalent to: * // lView[1].appendChild(lView[0] = document.createTextNode('xyz')); * 'xyz', 0, 1 << SHIFT_PARENT | 0 << SHIFT_REF | AppendChild, * * // For adding element nodes * // --------------------- * // Equivalent to: * // lView[1].appendChild(lView[0] = document.createElement('div')); * ELEMENT_MARKER, 'div', 0, 1 << SHIFT_PARENT | 0 << SHIFT_REF | AppendChild, * * // For adding comment nodes * // --------------------- * // Equivalent to: * // lView[1].appendChild(lView[0] = document.createComment('')); * ICU_MARKER, '', 0, 1 << SHIFT_PARENT | 0 << SHIFT_REF | AppendChild, * * // For moving existing nodes to a different location * // -------------------------------------------------- * // Equivalent to: * // const node = lView[1]; * // lView[2].appendChild(node); * 1 << SHIFT_REF | Select, 2 << SHIFT_PARENT | 0 << SHIFT_REF | AppendChild, * * // For removing existing nodes * // -------------------------------------------------- * // const node = lView[1]; * // removeChild(tView.data(1), node, lView); * 1 << SHIFT_REF | Remove, * * // For writing attributes * // -------------------------------------------------- * // const node = lView[1]; * // node.setAttribute('attr', 'value'); * 1 << SHIFT_REF | Attr, 'attr', 'value' * ]; * ``` */ export interface IcuCreateOpCodes extends Array<number | string | ELEMENT_MARKER | ICU_MARKER | null>, I18nDebug { __brand__: 'I18nCreateOpCodes'; } export const enum I18nUpdateOpCode { /** * Stores shift amount for bits 17-2 that contain reference index. */ SHIFT_REF = 2, /** * Mask for OpCode */ MASK_OPCODE = 0b11, /** * Instruction to update a text node. */ Text = 0b00, /** * Instruction to update a attribute of a node. */ Attr = 0b01, /** * Instruction to switch the current ICU case. */ IcuSwitch = 0b10, /** * Instruction to update the current ICU case. */ IcuUpdate = 0b11, } /** * Marks that the next string is an element name. * * See `I18nMutateOpCodes` documentation. */ export const ELEMENT_MARKER: ELEMENT_MARKER = { marker: 'element', }; export interface ELEMENT_MARKER { marker: 'element'; } /** * Marks that the next string is comment text need for ICU. * * See `I18nMutateOpCodes` documentation. */ export const ICU_MARKER: ICU_MARKER = { marker: 'ICU', }; export interface ICU_MARKER { marker: 'ICU'; } export interface I18nDebug { /** * Human readable representation of the OpCode arrays. * * NOTE: This property only exists if `ngDevMode` is set to `true` and it is not present in * production. Its presence is purely to help debug issue in development, and should not be relied * on in production application. */ debug?: string[]; } /** * Array storing OpCode for dynamically creating `i18n` translation DOM elements. * * This array creates a sequence of `Text` and `Comment` (as ICU anchor) DOM elements. It consists * of a pair of `number` and `string` pairs which encode the operations for the creation of the * translated block. * * The number is shifted and encoded according to `I18nCreateOpCode` * * Pseudocode: * ``` * const i18nCreateOpCodes = [ * 10 << I18nCreateOpCode.SHIFT, "Text Node add to DOM", * 11 << I18nCreateOpCode.SHIFT | I18nCreateOpCode.COMMENT, "Comment Node add to DOM", * 12 << I18nCreateOpCode.SHIFT | I18nCreateOpCode.APPEND_LATER, "Text Node added later" * ]; * * for(var i=0; i<i18nCreateOpCodes.length; i++) { * const opcode = i18NCreateOpCodes[i++]; * const index = opcode >> I18nCreateOpCode.SHIFT; * const text = i18NCreateOpCodes[i]; * let node: Text|Comment; * if (opcode & I18nCreateOpCode.COMMENT === I18nCreateOpCode.COMMENT) { * node = lView[~index] = document.createComment(text); * } else { * node = lView[index] = document.createText(text); * } * if (opcode & I18nCreateOpCode.APPEND_EAGERLY !== I18nCreateOpCode.APPEND_EAGERLY) { * parentNode.appendChild(node); * } * } * ``` */ export interface I18nCreateOpCodes extends Array<number | string>, I18nDebug { __brand__: 'I18nCreateOpCodes'; } /** * See `I18nCreateOpCodes` */ export enum I18nCreateOpCode { /** * Number of bits to shift index so that it can be combined with the `APPEND_EAGERLY` and * `COMMENT`. */ SHIFT = 2, /** * Should the node be appended to parent immediately after creation. */ APPEND_EAGERLY = 0b01, /** * If set the node should be comment (rather than a text) node. */ COMMENT = 0b10, }
{ "end_byte": 6732, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/i18n.ts" }
angular/packages/core/src/render3/interfaces/i18n.ts_6734_13693
/** * Stores DOM operations which need to be applied to update DOM render tree due to changes in * expressions. * * The basic idea is that `i18nExp` OpCodes capture expression changes and update a change * mask bit. (Bit 1 for expression 1, bit 2 for expression 2 etc..., bit 32 for expression 32 and * higher.) The OpCodes then compare its own change mask against the expression change mask to * determine if the OpCodes should execute. * * NOTE: 32nd bit is special as it says 32nd or higher. This way if we have more than 32 bindings * the code still works, but with lower efficiency. (it is unlikely that a translation would have * more than 32 bindings.) * * These OpCodes can be used by both the i18n block as well as ICU sub-block. * * ## Example * * Assume * ```ts * if (rf & RenderFlags.Update) { * i18nExp(ctx.exp1); // If changed set mask bit 1 * i18nExp(ctx.exp2); // If changed set mask bit 2 * i18nExp(ctx.exp3); // If changed set mask bit 3 * i18nExp(ctx.exp4); // If changed set mask bit 4 * i18nApply(0); // Apply all changes by executing the OpCodes. * } * ``` * We can assume that each call to `i18nExp` sets an internal `changeMask` bit depending on the * index of `i18nExp`. * * ### OpCodes * ```ts * <I18nUpdateOpCodes>[ * // The following OpCodes represent: `<div i18n-title="pre{{exp1}}in{{exp2}}post">` * // If `changeMask & 0b11` * // has changed then execute update OpCodes. * // has NOT changed then skip `8` values and start processing next OpCodes. * 0b11, 8, * // Concatenate `newValue = 'pre'+lView[bindIndex-4]+'in'+lView[bindIndex-3]+'post';`. * 'pre', -4, 'in', -3, 'post', * // Update attribute: `elementAttribute(1, 'title', sanitizerFn(newValue));` * 1 << SHIFT_REF | Attr, 'title', sanitizerFn, * * // The following OpCodes represent: `<div i18n>Hello {{exp3}}!">` * // If `changeMask & 0b100` * // has changed then execute update OpCodes. * // has NOT changed then skip `4` values and start processing next OpCodes. * 0b100, 4, * // Concatenate `newValue = 'Hello ' + lView[bindIndex -2] + '!';`. * 'Hello ', -2, '!', * // Update text: `lView[1].textContent = newValue;` * 1 << SHIFT_REF | Text, * * // The following OpCodes represent: `<div i18n>{exp4, plural, ... }">` * // If `changeMask & 0b1000` * // has changed then execute update OpCodes. * // has NOT changed then skip `2` values and start processing next OpCodes. * 0b1000, 2, * // Concatenate `newValue = lView[bindIndex -1];`. * -1, * // Switch ICU: `icuSwitchCase(lView[1], 0, newValue);` * 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuSwitch, * * // Note `changeMask & -1` is always true, so the IcuUpdate will always execute. * -1, 1, * // Update ICU: `icuUpdateCase(lView[1], 0);` * 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuUpdate, * * ]; * ``` * */ export interface I18nUpdateOpCodes extends Array<string | number | SanitizerFn | null>, I18nDebug { __brand__: 'I18nUpdateOpCodes'; } /** * Store information for the i18n translation block. */ export interface TI18n { /** * A set of OpCodes which will create the Text Nodes and ICU anchors for the translation blocks. * * NOTE: The ICU anchors are filled in with ICU Update OpCode. */ create: I18nCreateOpCodes; /** * A set of OpCodes which will be executed on each change detection to determine if any changes to * DOM are required. */ update: I18nUpdateOpCodes; /** * An AST representing the translated message. This is used for hydration (and serialization), * while the Update and Create OpCodes are used at runtime. */ ast: Array<I18nNode>; /** * Index of a parent TNode, which represents a host node for this i18n block. */ parentTNodeIndex: number; } /** * Defines the ICU type of `select` or `plural` */ export const enum IcuType { select = 0, plural = 1, } export interface TIcu { /** * Defines the ICU type of `select` or `plural` */ type: IcuType; /** * Index in `LView` where the anchor node is stored. `<!-- ICU 0:0 -->` */ anchorIdx: number; /** * Currently selected ICU case pointer. * * `lView[currentCaseLViewIndex]` stores the currently selected case. This is needed to know how * to clean up the current case when transitioning no the new case. * * If the value stored is: * `null`: No current case selected. * `<0`: A flag which means that the ICU just switched and that `icuUpdate` must be executed * regardless of the `mask`. (After the execution the flag is cleared) * `>=0` A currently selected case index. */ currentCaseLViewIndex: number; /** * A list of case values which the current ICU will try to match. * * The last value is `other` */ cases: any[]; /** * A set of OpCodes to apply in order to build up the DOM render tree for the ICU */ create: IcuCreateOpCodes[]; /** * A set of OpCodes to apply in order to destroy the DOM render tree for the ICU. */ remove: I18nRemoveOpCodes[]; /** * A set of OpCodes to apply in order to update the DOM render tree for the ICU bindings. */ update: I18nUpdateOpCodes[]; } /** * Parsed ICU expression */ export interface IcuExpression { type: IcuType; mainBinding: number; cases: string[]; values: (string | IcuExpression)[][]; } // A parsed I18n AST Node export type I18nNode = I18nTextNode | I18nElementNode | I18nICUNode | I18nPlaceholderNode; /** * Represents a block of text in a translation, such as `Hello, {{ name }}!`. */ export interface I18nTextNode { /** The AST node kind */ kind: I18nNodeKind.TEXT; /** The LView index */ index: number; } /** * Represents a simple DOM element in a translation, such as `<div>...</div>` */ export interface I18nElementNode { /** The AST node kind */ kind: I18nNodeKind.ELEMENT; /** The LView index */ index: number; /** The child nodes */ children: Array<I18nNode>; } /** * Represents an ICU in a translation. */ export interface I18nICUNode { /** The AST node kind */ kind: I18nNodeKind.ICU; /** The LView index */ index: number; /** The branching cases */ cases: Array<Array<I18nNode>>; /** The LView index that stores the active case */ currentCaseLViewIndex: number; } /** * Represents special content that is embedded into the translation. This can * either be a special built-in element, such as <ng-container> and <ng-content>, * or it can be a sub-template, for example, from a structural directive. */ export interface I18nPlaceholderNode { /** The AST node kind */ kind: I18nNodeKind.PLACEHOLDER; /** The LView index */ index: number; /** The child nodes */ children: Array<I18nNode>; /** The placeholder type */ type: I18nPlaceholderType; } export const enum I18nPlaceholderType { ELEMENT, SUBTEMPLATE, }
{ "end_byte": 13693, "start_byte": 6734, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/i18n.ts" }
angular/packages/core/src/render3/interfaces/i18n.ts_13695_13770
export const enum I18nNodeKind { TEXT, ELEMENT, PLACEHOLDER, ICU, }
{ "end_byte": 13770, "start_byte": 13695, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/i18n.ts" }
angular/packages/core/src/render3/interfaces/definition.ts_0_3406
/** * @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 {ModuleWithProviders, ProcessProvidersFunction} from '../../di/interface/provider'; import {EnvironmentInjector} from '../../di/r3_injector'; import {Type} from '../../interface/type'; import {SchemaMetadata} from '../../metadata/schema'; import {ViewEncapsulation} from '../../metadata/view'; import {FactoryFn} from '../definition_factory'; import {TAttributes, TConstantsOrFactory} from './node'; import {CssSelectorList} from './projection'; import type {TView} from './view'; import {InputFlags} from './input_flags'; /** * Definition of what a template rendering function should look like for a component. */ export type ComponentTemplate<T> = { // Note: the ctx parameter is typed as T|U, as using only U would prevent a template with // e.g. ctx: {} from being assigned to ComponentTemplate<any> as TypeScript won't infer U = any // in that scenario. By including T this incompatibility is resolved. <U extends T>(rf: RenderFlags, ctx: T | U): void; }; /** * Definition of what a view queries function should look like. */ export type ViewQueriesFunction<T> = <U extends T>(rf: RenderFlags, ctx: U) => void; /** * Definition of what a content queries function should look like. */ export type ContentQueriesFunction<T> = <U extends T>( rf: RenderFlags, ctx: U, directiveIndex: number, ) => void; export interface ClassDebugInfo { className: string; filePath?: string; lineNumber?: number; forbidOrphanRendering?: boolean; } /** * Flags passed into template functions to determine which blocks (i.e. creation, update) * should be executed. * * Typically, a template runs both the creation block and the update block on initialization and * subsequent runs only execute the update block. However, dynamically created views require that * the creation block be executed separately from the update block (for backwards compat). */ export const enum RenderFlags { /* Whether to run the creation block (e.g. create elements and directives) */ Create = 0b01, /* Whether to run the update block (e.g. refresh bindings) */ Update = 0b10, } /** * A subclass of `Type` which has a static `ɵcmp`:`ComponentDef` field making it * consumable for rendering. */ export interface ComponentType<T> extends Type<T> { ɵcmp: unknown; } /** * A subclass of `Type` which has a static `ɵdir`:`DirectiveDef` field making it * consumable for rendering. */ export interface DirectiveType<T> extends Type<T> { ɵdir: unknown; ɵfac: unknown; } /** * A subclass of `Type` which has a static `ɵpipe`:`PipeDef` field making it * consumable for rendering. */ export interface PipeType<T> extends Type<T> { ɵpipe: unknown; } /** * Runtime link information for Directives. * * This is an internal data structure used by the render to link * directives into templates. * * NOTE: Always use `defineDirective` function to create this object, * never create the object directly since the shape of this object * can change between versions. * * @param Selector type metadata specifying the selector of the directive or component * * See: {@link defineDirective} */ export
{ "end_byte": 3406, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/definition.ts" }
angular/packages/core/src/render3/interfaces/definition.ts_3407_9916
interface DirectiveDef<T> { /** * A dictionary mapping the inputs' public name to their minified property names * (along with flags if there are any). */ readonly inputs: {[P in keyof T]?: string | [minifiedName: string, flags: InputFlags]}; /** * A dictionary mapping the private names of inputs to their transformation functions. * 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. * * Note: Signal inputs will not have transforms captured here. This is because their * transform function is already integrated into the `InputSignal`. */ readonly inputTransforms: {[classPropertyName: string]: InputTransformFunction} | null; /** * Contains the raw input information produced by the compiler. Can be * used to do further processing after the `inputs` have been inverted. */ readonly inputConfig: { [P in keyof T]?: string | [InputFlags, string, string?, InputTransformFunction?]; }; /** * @deprecated This is only here because `NgOnChanges` incorrectly uses declared name instead of * public or minified name. */ readonly declaredInputs: Record<string, string>; /** * A dictionary mapping the outputs' minified property names to their public API names, which * are their aliases if any, or their original unminified property names * (as in `@Output('alias') propertyName: any;`). */ readonly outputs: {[P in keyof T]?: string}; /** * Function to create and refresh content queries associated with a given directive. */ contentQueries: ContentQueriesFunction<T> | null; /** * Query-related instructions for a directive. Note that while directives don't have a * view and as such view queries won't necessarily do anything, there might be * components that extend the directive. */ viewQuery: ViewQueriesFunction<T> | null; /** * Refreshes host bindings on the associated directive. */ readonly hostBindings: HostBindingsFunction<T> | null; /** * The number of bindings in this directive `hostBindings` (including pure fn bindings). * * Used to calculate the length of the component's LView array, so we * can pre-fill the array and set the host binding start index. */ readonly hostVars: number; /** * Assign static attribute values to a host element. * * This property will assign static attribute values as well as class and style * values to a host element. Since attribute values can consist of different types of values, the * `hostAttrs` array must include the values in the following format: * * attrs = [ * // static attributes (like `title`, `name`, `id`...) * attr1, value1, attr2, value, * * // a single namespace value (like `x:id`) * NAMESPACE_MARKER, namespaceUri1, name1, value1, * * // another single namespace value (like `x:name`) * NAMESPACE_MARKER, namespaceUri2, name2, value2, * * // a series of CSS classes that will be applied to the element (no spaces) * CLASSES_MARKER, class1, class2, class3, * * // a series of CSS styles (property + value) that will be applied to the element * STYLES_MARKER, prop1, value1, prop2, value2 * ] * * All non-class and non-style attributes must be defined at the start of the list * first before all class and style values are set. When there is a change in value * type (like when classes and styles are introduced) a marker must be used to separate * the entries. The marker values themselves are set via entries found in the * [AttributeMarker] enum. */ readonly hostAttrs: TAttributes | null; /** Token representing the directive. Used by DI. */ readonly type: Type<T>; /** Function that resolves providers and publishes them into the DI system. */ providersResolver: | (<U extends T>(def: DirectiveDef<U>, processProvidersFn?: ProcessProvidersFunction) => void) | null; /** The selectors that will be used to match nodes to this directive. */ readonly selectors: CssSelectorList; /** * Name under which the directive is exported (for use with local references in template) */ readonly exportAs: string[] | null; /** * Whether this directive (or component) is standalone. */ readonly standalone: boolean; /** * Whether this directive (or component) uses the signals authoring experience. */ readonly signals: boolean; /** * Factory function used to create a new directive instance. Will be null initially. * Populated when the factory is first requested by directive instantiation logic. */ readonly factory: FactoryFn<T> | null; /** * The features applied to this directive */ readonly features: DirectiveDefFeature[] | null; /** * Info related to debugging/troubleshooting for this component. This info is only available in * dev mode. */ debugInfo: ClassDebugInfo | null; /** * Function that will add the host directives to the list of matches during directive matching. * Patched onto the definition by the `HostDirectivesFeature`. * @param currentDef Definition that has been matched. * @param matchedDefs List of all matches for a specified node. Will be mutated to include the * host directives. * @param hostDirectiveDefs Mapping of directive definitions to their host directive * configuration. Host directives will be added to the map as they're being matched to the node. */ findHostDirectiveDefs: | (( currentDef: DirectiveDef<unknown>, matchedDefs: DirectiveDef<unknown>[], hostDirectiveDefs: HostDirectiveDefs, ) => void) | null; /** Additional directives to be applied whenever the directive has been matched. */ hostDirectives: HostDirectiveDef[] | null; setInput: | (<U extends T>( this: DirectiveDef<U>, instance: U, inputSignalNode: null | InputSignalNode<unknown, unknown>, value: any, publicName: string, privateName: string, ) => void) | null; } /** * Runtime link information for Components. * * This is an internal data structure used by the render to link * components into templates. * * NOTE: Always use `defineComponent` function to create this object, * never create the object directly since the shape of this object * can change between versions. * * See: {@link defineComponent} */ export
{ "end_byte": 9916, "start_byte": 3407, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/definition.ts" }
angular/packages/core/src/render3/interfaces/definition.ts_9917_18248
interface ComponentDef<T> extends DirectiveDef<T> { /** * Unique ID for the component. Used in view encapsulation and * to keep track of the injector in standalone components. */ readonly id: string; /** * The View template of the component. */ readonly template: ComponentTemplate<T>; /** Constants associated with the component's view. */ readonly consts: TConstantsOrFactory | null; /** * An array of `ngContent[selector]` values that were found in the template. */ readonly ngContentSelectors?: string[]; /** * A set of styles that the component needs to be present for component to render correctly. */ readonly styles: string[]; /** * The number of nodes, local refs, and pipes in this component template. * * Used to calculate the length of the component's LView array, so we * can pre-fill the array and set the binding start index. */ // TODO(kara): remove queries from this count readonly decls: number; /** * The number of bindings in this component template (including pure fn bindings). * * Used to calculate the length of the component's LView array, so we * can pre-fill the array and set the host binding start index. */ readonly vars: number; /** * Query-related instructions for a component. */ viewQuery: ViewQueriesFunction<T> | null; /** * The view encapsulation type, which determines how styles are applied to * DOM elements. One of * - `Emulated` (default): Emulate native scoping of styles. * - `Native`: Use the native encapsulation mechanism of the renderer. * - `ShadowDom`: Use modern [ShadowDOM](https://w3c.github.io/webcomponents/spec/shadow/) and * create a ShadowRoot for component's host element. * - `None`: Do not provide any template or style encapsulation. */ readonly encapsulation: ViewEncapsulation; /** * Defines arbitrary developer-defined data to be stored on a renderer instance. * This is useful for renderers that delegate to other renderers. */ readonly data: { [kind: string]: any; animation?: any[]; }; /** Whether or not this component's ChangeDetectionStrategy is OnPush */ readonly onPush: boolean; /** Whether or not this component is signal-based. */ readonly signals: boolean; /** * Registry of directives and components that may be found in this view. * * The property is either an array of `DirectiveDef`s or a function which returns the array of * `DirectiveDef`s. The function is necessary to be able to support forward declarations. */ directiveDefs: DirectiveDefListOrFactory | null; /** * Registry of pipes that may be found in this view. * * The property is either an array of `PipeDefs`s or a function which returns the array of * `PipeDefs`s. The function is necessary to be able to support forward declarations. */ pipeDefs: PipeDefListOrFactory | null; /** * Unfiltered list of all dependencies of a component, or `null` if none. */ dependencies: TypeOrFactory<DependencyTypeList> | null; /** * The set of schemas that declare elements to be allowed in the component's template. */ schemas: SchemaMetadata[] | null; /** * Ivy runtime uses this place to store the computed tView for the component. This gets filled on * the first run of component. */ tView: TView | null; /** * A function used by the framework to create standalone injectors. */ getStandaloneInjector: | ((parentInjector: EnvironmentInjector) => EnvironmentInjector | null) | null; /** * A function added by the {@link ɵɵExternalStylesFeature} and used by the framework to create * the list of external runtime style URLs. */ getExternalStyles: ((encapsulationId?: string) => string[]) | null; /** * Used to store the result of `noSideEffects` function so that it is not removed by closure * compiler. The property should never be read. */ readonly _?: unknown; } /** * Runtime link information for Pipes. * * This is an internal data structure used by the renderer to link * pipes into templates. * * NOTE: Always use `definePipe` function to create this object, * never create the object directly since the shape of this object * can change between versions. * * See: {@link definePipe} */ export interface PipeDef<T> { /** Token representing the pipe. */ type: Type<T>; /** * Pipe name. * * Used to resolve pipe in templates. */ readonly name: string; /** * Factory function used to create a new pipe instance. Will be null initially. * Populated when the factory is first requested by pipe instantiation logic. */ factory: FactoryFn<T> | null; /** * Whether or not the pipe is pure. * * Pure pipes result only depends on the pipe input and not on internal * state of the pipe. */ readonly pure: boolean; /** * Whether this pipe is standalone. */ readonly standalone: boolean; /* The following are lifecycle hooks for this pipe */ onDestroy: (() => void) | null; } export interface DirectiveDefFeature { <T>(directiveDef: DirectiveDef<T>): void; /** * Marks a feature as something that {@link InheritDefinitionFeature} will execute * during inheritance. * * NOTE: DO NOT SET IN ROOT OF MODULE! Doing so will result in tree-shakers/bundlers * identifying the change as a side effect, and the feature will be included in * every bundle. */ ngInherit?: true; } /** Runtime information used to configure a host directive. */ export interface HostDirectiveDef<T = unknown> { /** Class representing the host directive. */ directive: Type<T>; /** Directive inputs that have been exposed. */ inputs: HostDirectiveBindingMap; /** Directive outputs that have been exposed. */ outputs: HostDirectiveBindingMap; } /** * Mapping between the public aliases of directive bindings and the underlying inputs/outputs that * they represent. Also serves as an allowlist of the inputs/outputs from the host directive that * the author has decided to expose. */ export type HostDirectiveBindingMap = { [publicName: string]: string; }; /** * Mapping between a directive that was used as a host directive * and the configuration that was used to define it as such. */ export type HostDirectiveDefs = Map<DirectiveDef<unknown>, HostDirectiveDef>; export interface ComponentDefFeature { <T>(componentDef: ComponentDef<T>): void; /** * Marks a feature as something that {@link InheritDefinitionFeature} will execute * during inheritance. * * NOTE: DO NOT SET IN ROOT OF MODULE! Doing so will result in tree-shakers/bundlers * identifying the change as a side effect, and the feature will be included in * every bundle. */ ngInherit?: true; } /** Function that can be used to transform incoming input values. */ export type InputTransformFunction = (value: any) => any; /** * Type used for directiveDefs on component definition. * * The function is necessary to be able to support forward declarations. */ export type DirectiveDefListOrFactory = (() => DirectiveDefList) | DirectiveDefList; export type DirectiveDefList = (DirectiveDef<any> | ComponentDef<any>)[]; export type DependencyDef = DirectiveDef<unknown> | ComponentDef<unknown> | PipeDef<unknown>; export type DirectiveTypesOrFactory = (() => DirectiveTypeList) | DirectiveTypeList; export type DirectiveTypeList = ( | DirectiveType<any> | ComponentType<any> | Type<any> ) /* Type as workaround for: Microsoft/TypeScript/issues/4881 */[]; export type DependencyType = DirectiveType<any> | ComponentType<any> | PipeType<any> | Type<any>; export type DependencyTypeList = Array<DependencyType>; export type TypeOrFactory<T> = T | (() => T); export type HostBindingsFunction<T> = <U extends T>(rf: RenderFlags, ctx: U) => void; /** * Type used for PipeDefs on component definition. * * The function is necessary to be able to support forward declarations. */ export type PipeDefListOrFactory = (() => PipeDefList) | PipeDefList; export type PipeDefList = PipeDef<any>[]; export type PipeTypesOrFactory = (() => PipeTypeList) | PipeTypeList; export type PipeTypeList = ( | PipeType<any> | Type<any> ) /* Type as workaround for: Microsoft/TypeScript/issues/4881 */[]; /** *
{ "end_byte": 18248, "start_byte": 9917, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/definition.ts" }
angular/packages/core/src/render3/interfaces/definition.ts_18250_20022
Module scope info as provided by AoT compiler * * In full compilation Ivy resolved all the "module with providers" and forward refs the whole array * if at least one element is forward refed. So we end up with type `Type<any>[]|(() => * Type<any>[])`. * * In local mode the compiler passes the raw info as they are to the runtime functions as it is not * possible to resolve them any further due to limited info at compile time. So we end up with type * `RawScopeInfoFromDecorator[]`. */ export interface NgModuleScopeInfoFromDecorator { /** List of components, directives, and pipes declared by this module. */ declarations?: Type<any>[] | (() => Type<any>[]) | RawScopeInfoFromDecorator[]; /** List of modules or `ModuleWithProviders` or standalone components imported by this module. */ imports?: Type<any>[] | (() => Type<any>[]) | RawScopeInfoFromDecorator[]; /** * List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this * module. */ exports?: Type<any>[] | (() => Type<any>[]) | RawScopeInfoFromDecorator[]; /** * The set of components that are bootstrapped when this module is bootstrapped. This field is * only available in local compilation mode. In full compilation mode bootstrap info is passed * directly to the module def runtime after statically analyzed and resolved. */ bootstrap?: Type<any>[] | (() => Type<any>[]) | RawScopeInfoFromDecorator[]; } /** * The array element type passed to: * - NgModule's annotation imports/exports/declarations fields * - standalone component annotation imports field */ export type RawScopeInfoFromDecorator = | Type<any> | ModuleWithProviders<any> | (() => Type<any>) | (() => ModuleWithProviders<any>) | any[];
{ "end_byte": 20022, "start_byte": 18250, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/definition.ts" }
angular/packages/core/src/render3/interfaces/document.ts_0_2360
/** * @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'; /** * Most of the use of `document` in Angular is from within the DI system so it is possible to simply * inject the `DOCUMENT` token and are done. * * Ivy is special because it does not rely upon the DI and must get hold of the document some other * way. * * The solution is to define `getDocument()` and `setDocument()` top-level functions for ivy. * Wherever ivy needs the global document, it calls `getDocument()` instead. * * When running ivy outside of a browser environment, it is necessary to call `setDocument()` to * tell ivy what the global `document` is. * * Angular does this for us in each of the standard platforms (`Browser` and `Server`) * by calling `setDocument()` when providing the `DOCUMENT` token. */ let DOCUMENT: Document | undefined = undefined; /** * Tell ivy what the `document` is for this platform. * * It is only necessary to call this if the current platform is not a browser. * * @param document The object representing the global `document` in this environment. */ export function setDocument(document: Document | undefined): void { DOCUMENT = document; } /** * Access the object that represents the `document` for this platform. * * Ivy calls this whenever it needs to access the `document` object. * For example to create the renderer or to do sanitization. */ export function getDocument(): Document { if (DOCUMENT !== undefined) { return DOCUMENT; } else if (typeof document !== 'undefined') { return document; } throw new RuntimeError( RuntimeErrorCode.MISSING_DOCUMENT, (typeof ngDevMode === 'undefined' || ngDevMode) && `The document object is not available in this context. Make sure the DOCUMENT injection token is provided.`, ); // No "document" can be found. This should only happen if we are running ivy outside Angular and // the current platform is not a browser. Since this is not a supported scenario at the moment // this should not happen in Angular apps. // Once we support running ivy outside of Angular we will need to publish `setDocument()` as a // public API. }
{ "end_byte": 2360, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/document.ts" }
angular/packages/core/src/render3/interfaces/context.ts_0_1747
/** * @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 {getLViewById} from './lview_tracking'; import {RNode} from './renderer_dom'; import {LView} from './view'; /** * The internal view context which is specific to a given DOM element, directive or * component instance. Each value in here (besides the LView and element node details) * can be present, null or undefined. If undefined then it implies the value has not been * looked up yet, otherwise, if null, then a lookup was executed and nothing was found. * * Each value will get filled when the respective value is examined within the getContext * function. The component, element and each directive instance will share the same instance * of the context. */ export class LContext { /** * The instance of the Component node. */ public component: {} | null | undefined; /** * The list of active directives that exist on this element. */ public directives: any[] | null | undefined; /** * The map of local references (local reference name => element or directive instance) that * exist on this element. */ public localRefs: {[key: string]: any} | null | undefined; /** Component's parent view data. */ get lView(): LView | null { return getLViewById(this.lViewId); } constructor( /** * ID of the component's parent view data. */ private lViewId: number, /** * The index instance of the node. */ public nodeIndex: number, /** * The instance of the DOM node that is attached to the lNode. */ public native: RNode, ) {} }
{ "end_byte": 1747, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/context.ts" }
angular/packages/core/src/render3/interfaces/view.ts_0_3713
/** * @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 {ChangeDetectionScheduler} from '../../change_detection/scheduling/zoneless_scheduling'; import {TDeferBlockDetails} from '../../defer/interfaces'; import type {Injector} from '../../di/injector'; import {ProviderToken} from '../../di/provider_token'; import {DehydratedView} from '../../hydration/interfaces'; import {SchemaMetadata} from '../../metadata/schema'; import {Sanitizer} from '../../sanitization/sanitizer'; import type {AfterRenderManager} from '../after_render/manager'; import type {ReactiveLViewConsumer} from '../reactive_lview_consumer'; import type {ViewEffectNode} from '../reactivity/effect'; import {LContainer} from './container'; import { ComponentDef, ComponentTemplate, DirectiveDef, DirectiveDefList, HostBindingsFunction, PipeDef, PipeDefList, ViewQueriesFunction, } from './definition'; import {I18nUpdateOpCodes, TI18n, TIcu} from './i18n'; import {TConstants, TNode} from './node'; import type {LQueries, TQueries} from './query'; import {Renderer, RendererFactory} from './renderer'; import {RElement} from './renderer_dom'; import {TStylingKey, TStylingRange} from './styling'; // Below are constants for LView indices to help us look up LView members // without having to remember the specific indices. // Uglify will inline these when minifying so there shouldn't be a cost. export const HOST = 0; export const TVIEW = 1; // Shared with LContainer export const FLAGS = 2; export const PARENT = 3; export const NEXT = 4; export const T_HOST = 5; // End shared with LContainer export const HYDRATION = 6; export const CLEANUP = 7; export const CONTEXT = 8; export const INJECTOR = 9; export const ENVIRONMENT = 10; export const RENDERER = 11; export const CHILD_HEAD = 12; export const CHILD_TAIL = 13; // FIXME(misko): Investigate if the three declarations aren't all same thing. export const DECLARATION_VIEW = 14; export const DECLARATION_COMPONENT_VIEW = 15; export const DECLARATION_LCONTAINER = 16; export const PREORDER_HOOK_FLAGS = 17; export const QUERIES = 18; export const ID = 19; export const EMBEDDED_VIEW_INJECTOR = 20; export const ON_DESTROY_HOOKS = 21; export const EFFECTS_TO_SCHEDULE = 22; export const EFFECTS = 23; export const REACTIVE_TEMPLATE_CONSUMER = 24; /** * Size of LView's header. Necessary to adjust for it when setting slots. * * IMPORTANT: `HEADER_OFFSET` should only be referred to the in the `ɵɵ*` instructions to translate * instruction index into `LView` index. All other indexes should be in the `LView` index space and * there should be no need to refer to `HEADER_OFFSET` anywhere else. */ export const HEADER_OFFSET = 25; // This interface replaces the real LView interface if it is an arg or a // return value of a public instruction. This ensures we don't need to expose // the actual interface, which should be kept private. export interface OpaqueViewState { '__brand__': 'Brand for OpaqueViewState that nothing will match'; } /** * `LView` stores all of the information needed to process the instructions as * they are invoked from the template. Each embedded view and component view has its * own `LView`. When processing a particular view, we set the `viewData` to that * `LView`. When that view is done processing, the `viewData` is set back to * whatever the original `viewData` was before (the parent `LView`). * * Keeping separate state for each view facilities view insertion / deletion, so we * don't have to edit the data array based on which views are present. */ e
{ "end_byte": 3713, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_3714_9431
port interface LView<T = unknown> extends Array<any> { /** * The node into which this `LView` is inserted. */ [HOST]: RElement | null; /** * The static data for this view. We need a reference to this so we can easily walk up the * node tree in DI and get the TView.data array associated with a node (where the * directive defs are stored). */ readonly [TVIEW]: TView; /** Flags for this view. See LViewFlags for more info. */ [FLAGS]: LViewFlags; /** * This may store an {@link LView} or {@link LContainer}. * * `LView` - The parent view. This is needed when we exit the view and must restore the previous * LView. Without this, the render method would have to keep a stack of * views as it is recursively rendering templates. * * `LContainer` - The current view is part of a container, and is an embedded view. */ [PARENT]: LView | LContainer | null; /** * * The next sibling LView or LContainer. * * Allows us to propagate between sibling view states that aren't in the same * container. Embedded views already have a node.next, but it is only set for * views in the same container. We need a way to link component views and views * across containers as well. */ [NEXT]: LView | LContainer | null; /** Queries active for this view - nodes from a view are reported to those queries. */ [QUERIES]: LQueries | null; /** * Store the `TNode` of the location where the current `LView` is inserted into. * * Given: * ``` * <div> * <ng-template><span></span></ng-template> * </div> * ``` * * We end up with two `TView`s. * - `parent` `TView` which contains `<div><!-- anchor --></div>` * - `child` `TView` which contains `<span></span>` * * Typically the `child` is inserted into the declaration location of the `parent`, but it can be * inserted anywhere. Because it can be inserted anywhere it is not possible to store the * insertion information in the `TView` and instead we must store it in the `LView[T_HOST]`. * * So to determine where is our insertion parent we would execute: * ``` * const parentLView = lView[PARENT]; * const parentTNode = lView[T_HOST]; * const insertionParent = parentLView[parentTNode.index]; * ``` * * * If `null`, this is the root view of an application (root component is in this view) and it has * no parents. */ [T_HOST]: TNode | null; /** * When a view is destroyed, listeners need to be released and outputs need to be * unsubscribed. This context array stores both listener functions wrapped with * their context and output subscription instances for a particular view. * * These change per LView instance, so they cannot be stored on TView. Instead, * TView.cleanup saves an index to the necessary context in this array. * * After `LView` is created it is possible to attach additional instance specific functions at the * end of the `lView[CLEANUP]` because we know that no more `T` level cleanup functions will be * added here. */ [CLEANUP]: any[] | null; /** * - For dynamic views, this is the context with which to render the template (e.g. * `NgForContext`), or `{}` if not defined explicitly. * - For root view of the root component it's a reference to the component instance itself. * - For components, the context is a reference to the component instance itself. * - For inline views, the context is null. */ [CONTEXT]: T; /** An optional Module Injector to be used as fall back after Element Injectors are consulted. */ readonly [INJECTOR]: Injector | null; /** * Contextual data that is shared across multiple instances of `LView` in the same application. */ [ENVIRONMENT]: LViewEnvironment; /** Renderer to be used for this view. */ [RENDERER]: Renderer; /** * Reference to the first LView or LContainer beneath this LView in * the hierarchy. * * Necessary to store this so views can traverse through their nested views * to remove listeners and call onDestroy callbacks. */ [CHILD_HEAD]: LView | LContainer | null; /** * The last LView or LContainer beneath this LView in the hierarchy. * * The tail allows us to quickly add a new state to the end of the view list * without having to propagate starting from the first child. */ [CHILD_TAIL]: LView | LContainer | null; /** * View where this view's template was declared. * * The template for a dynamically created view may be declared in a different view than * it is inserted. We already track the "insertion view" (view where the template was * inserted) in LView[PARENT], but we also need access to the "declaration view" * (view where the template was declared). Otherwise, we wouldn't be able to call the * view's template function with the proper contexts. Context should be inherited from * the declaration view tree, not the insertion view tree. * * Example (AppComponent template): * * <ng-template #foo></ng-template> <-- declared here --> * <some-comp [tpl]="foo"></some-comp> <-- inserted inside this component --> * * The <ng-template> above is declared in the AppComponent template, but it will be passed into * SomeComp and inserted there. In this case, the declaration view would be the AppComponent, * but the insertion view would be SomeComp. When we are removing views, we would want to * traverse through the insertion view to clean up listeners. When we are calling the * template function during change detection, we need the declaration view to get inherited * context. */ [DECLARATION_VIEW]: LView | null;
{ "end_byte": 9431, "start_byte": 3714, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_9435_15205
* * Points to the declaration component view, used to track transplanted `LView`s. * * See: `DECLARATION_VIEW` which points to the actual `LView` where it was declared, whereas * `DECLARATION_COMPONENT_VIEW` points to the component which may not be same as * `DECLARATION_VIEW`. * * Example: * ``` * <#VIEW #myComp> * <div *ngIf="true"> * <ng-template #myTmpl>...</ng-template> * </div> * </#VIEW> * ``` * In the above case `DECLARATION_VIEW` for `myTmpl` points to the `LView` of `ngIf` whereas * `DECLARATION_COMPONENT_VIEW` points to `LView` of the `myComp` which owns the template. * * The reason for this is that all embedded views are always check-always whereas the component * view can be check-always or on-push. When we have a transplanted view it is important to * determine if we have transplanted a view from check-always declaration to on-push insertion * point. In such a case the transplanted view needs to be added to the `LContainer` in the * declared `LView` and CD during the declared view CD (in addition to the CD at the insertion * point.) (Any transplanted views which are intra Component are of no interest because the CD * strategy of declaration and insertion will always be the same, because it is the same * component.) * * Queries already track moved views in `LView[DECLARATION_LCONTAINER]` and * `LContainer[MOVED_VIEWS]`. However the queries also track `LView`s which moved within the same * component `LView`. Transplanted views are a subset of moved views, and we use * `DECLARATION_COMPONENT_VIEW` to differentiate them. As in this example. * * Example showing intra component `LView` movement. * ``` * <#VIEW #myComp> * <div *ngIf="condition; then thenBlock else elseBlock"></div> * <ng-template #thenBlock>Content to render when condition is true.</ng-template> * <ng-template #elseBlock>Content to render when condition is false.</ng-template> * </#VIEW> * ``` * The `thenBlock` and `elseBlock` is moved but not transplanted. * * Example showing inter component `LView` movement (transplanted view). * ``` * <#VIEW #myComp> * <ng-template #myTmpl>...</ng-template> * <insertion-component [template]="myTmpl"></insertion-component> * </#VIEW> * ``` * In the above example `myTmpl` is passed into a different component. If `insertion-component` * instantiates `myTmpl` and `insertion-component` is on-push then the `LContainer` needs to be * marked as containing transplanted views and those views need to be CD as part of the * declaration CD. * * * When change detection runs, it iterates over `[MOVED_VIEWS]` and CDs any child `LView`s where * the `DECLARATION_COMPONENT_VIEW` of the current component and the child `LView` does not match * (it has been transplanted across components.) * * Note: `[DECLARATION_COMPONENT_VIEW]` points to itself if the LView is a component view (the * simplest / most common case). * * see also: * - https://hackmd.io/@mhevery/rJUJsvv9H write up of the problem * - `LContainer[HAS_TRANSPLANTED_VIEWS]` which marks which `LContainer` has transplanted views. * - `LContainer[TRANSPLANT_HEAD]` and `LContainer[TRANSPLANT_TAIL]` storage for transplanted * - `LView[DECLARATION_LCONTAINER]` similar problem for queries * - `LContainer[MOVED_VIEWS]` similar problem for queries */ [DECLARATION_COMPONENT_VIEW]: LView; /** * A declaration point of embedded views (ones instantiated based on the content of a * <ng-template>), null for other types of views. * * We need to track all embedded views created from a given declaration point so we can prepare * query matches in a proper order (query matches are ordered based on their declaration point and * _not_ the insertion point). */ [DECLARATION_LCONTAINER]: LContainer | null; /** * More flags for this view. See PreOrderHookFlags for more info. */ [PREORDER_HOOK_FLAGS]: PreOrderHookFlags; /** Unique ID of the view. Used for `__ngContext__` lookups in the `LView` registry. */ [ID]: number; /** * A container related to hydration annotation information that's associated with this LView. */ [HYDRATION]: DehydratedView | null; /** * Optional injector assigned to embedded views that takes * precedence over the element and module injectors. */ readonly [EMBEDDED_VIEW_INJECTOR]: Injector | null; /** * Effect scheduling operations that need to run during this views's update pass. */ [EFFECTS_TO_SCHEDULE]: Array<() => void> | null; [EFFECTS]: Set<ViewEffectNode> | null; /** * A collection of callbacks functions that are executed when a given LView is destroyed. Those * are user defined, LView-specific destroy callbacks that don't have any corresponding TView * entries. */ [ON_DESTROY_HOOKS]: Array<() => void> | null; /** * The `Consumer` for this `LView`'s template so that signal reads can be tracked. * * This is initially `null` and gets assigned a consumer after template execution * if any signals were read. */ [REACTIVE_TEMPLATE_CONSUMER]: ReactiveLViewConsumer | null; } /** * Contextual data that is shared across multiple instances of `LView` in the same application. */ export interface LViewEnvironment { /** Factory to be used for creating Renderer. */ rendererFactory: RendererFactory; /** An optional custom sanitizer. */ sanitizer: Sanitizer | null; /** Scheduler for change detection to notify when application state changes. */ changeDetectionScheduler: ChangeDetectionScheduler | null; } /** Flags associated with an LView (saved in LView[FLAGS]) */ e
{ "end_byte": 15205, "start_byte": 9435, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_15206_22560
port const enum LViewFlags { /** The state of the init phase on the first 2 bits */ InitPhaseStateIncrementer = 0b00000000001, InitPhaseStateMask = 0b00000000011, /** * Whether or not the view is in creationMode. * * This must be stored in the view rather than using `data` as a marker so that * we can properly support embedded views. Otherwise, when exiting a child view * back into the parent view, `data` will be defined and `creationMode` will be * improperly reported as false. */ CreationMode = 1 << 2, /** * Whether or not this LView instance is on its first processing pass. * * An LView instance is considered to be on its "first pass" until it * has completed one creation mode run and one update mode run. At this * time, the flag is turned off. */ FirstLViewPass = 1 << 3, /** Whether this view has default change detection strategy (checks always) or onPush */ CheckAlways = 1 << 4, /** Whether there are any i18n blocks inside this LView. */ HasI18n = 1 << 5, /** Whether or not this view is currently dirty (needing check) */ Dirty = 1 << 6, /** Whether or not this view is currently attached to change detection tree. */ Attached = 1 << 7, /** Whether or not this view is destroyed. */ Destroyed = 1 << 8, /** Whether or not this view is the root view */ IsRoot = 1 << 9, /** * Whether this moved LView was needs to be refreshed. Similar to the Dirty flag, but used for * transplanted and signal views where the parent/ancestor views are not marked dirty as well. * i.e. "Refresh just this view". Used in conjunction with the HAS_CHILD_VIEWS_TO_REFRESH * flag. */ RefreshView = 1 << 10, /** Indicates that the view **or any of its ancestors** have an embedded view injector. */ HasEmbeddedViewInjector = 1 << 11, /** Indicates that the view was created with `signals: true`. */ SignalView = 1 << 12, /** * Indicates that this LView has a view underneath it that needs to be refreshed during change * detection. This flag indicates that even if this view is not dirty itself, we still need to * traverse its children during change detection. */ HasChildViewsToRefresh = 1 << 13, /** * This is the count of the bits the 1 was shifted above (base 10) */ IndexWithinInitPhaseShift = 14, /** * Index of the current init phase on last 21 bits */ IndexWithinInitPhaseIncrementer = 1 << IndexWithinInitPhaseShift, // Subtracting 1 gives all 1s to the right of the initial shift // So `(1 << 3) - 1` would give 3 1s: 1 << 3 = 0b01000, subtract 1 = 0b00111 IndexWithinInitPhaseReset = (1 << IndexWithinInitPhaseShift) - 1, } /** * Possible states of the init phase: * - 00: OnInit hooks to be run. * - 01: AfterContentInit hooks to be run * - 10: AfterViewInit hooks to be run * - 11: All init hooks have been run */ export const enum InitPhaseState { OnInitHooksToBeRun = 0b00, AfterContentInitHooksToBeRun = 0b01, AfterViewInitHooksToBeRun = 0b10, InitPhaseCompleted = 0b11, } /** More flags associated with an LView (saved in LView[PREORDER_HOOK_FLAGS]) */ export const enum PreOrderHookFlags { /** The index of the next pre-order hook to be called in the hooks array, on the first 16 bits */ IndexOfTheNextPreOrderHookMaskMask = 0b01111111111111111, /** * The number of init hooks that have already been called, on the last 16 bits */ NumberOfInitHooksCalledIncrementer = 0b010000000000000000, NumberOfInitHooksCalledShift = 16, NumberOfInitHooksCalledMask = 0b11111111111111110000000000000000, } /** * Stores a set of OpCodes to process `HostBindingsFunction` associated with a current view. * * In order to invoke `HostBindingsFunction` we need: * 1. 'elementIdx`: Index to the element associated with the `HostBindingsFunction`. * 2. 'directiveIdx`: Index to the directive associated with the `HostBindingsFunction`. (This will * become the context for the `HostBindingsFunction` invocation.) * 3. `bindingRootIdx`: Location where the bindings for the `HostBindingsFunction` start. Internally * `HostBindingsFunction` binding indexes start from `0` so we need to add `bindingRootIdx` to * it. * 4. `HostBindingsFunction`: A host binding function to execute. * * The above information needs to be encoded into the `HostBindingOpCodes` in an efficient manner. * * 1. `elementIdx` is encoded into the `HostBindingOpCodes` as `~elementIdx` (so a negative number); * 2. `directiveIdx` * 3. `bindingRootIdx` * 4. `HostBindingsFunction` is passed in as is. * * The `HostBindingOpCodes` array contains: * - negative number to select the element index. * - followed by 1 or more of: * - a number to select the directive index * - a number to select the bindingRoot index * - and a function to invoke. * * ## Example * * ``` * const hostBindingOpCodes = [ * ~30, // Select element 30 * 40, 45, MyDir.ɵdir.hostBindings // Invoke host bindings on MyDir on element 30; * // directiveIdx = 40; bindingRootIdx = 45; * 50, 55, OtherDir.ɵdir.hostBindings // Invoke host bindings on OtherDire on element 30 * // directiveIdx = 50; bindingRootIdx = 55; * ] * ``` * * ## Pseudocode * ``` * const hostBindingOpCodes = tView.hostBindingOpCodes; * if (hostBindingOpCodes === null) return; * for (let i = 0; i < hostBindingOpCodes.length; i++) { * const opCode = hostBindingOpCodes[i] as number; * if (opCode < 0) { * // Negative numbers are element indexes. * setSelectedIndex(~opCode); * } else { * // Positive numbers are NumberTuple which store bindingRootIndex and directiveIndex. * const directiveIdx = opCode; * const bindingRootIndx = hostBindingOpCodes[++i] as number; * const hostBindingFn = hostBindingOpCodes[++i] as HostBindingsFunction<any>; * setBindingRootForHostBindings(bindingRootIndx, directiveIdx); * const context = lView[directiveIdx]; * hostBindingFn(RenderFlags.Update, context); * } * } * ``` * */ export interface HostBindingOpCodes extends Array<number | HostBindingsFunction<any>> { __brand__: 'HostBindingOpCodes'; debug?: string[]; } /** * Explicitly marks `TView` as a specific type in `ngDevMode` * * It is useful to know conceptually what time of `TView` we are dealing with when * debugging an application (even if the runtime does not need it.) For this reason * we store this information in the `ngDevMode` `TView` and than use it for * better debugging experience. */ export const enum TViewType { /** * Root `TView` is the used to bootstrap components into. It is used in conjunction with * `LView` which takes an existing DOM node not owned by Angular and wraps it in `TView`/`LView` * so that other components can be loaded into it. */ Root = 0, /** * `TView` associated with a Component. This would be the `TView` directly associated with the * component view (as opposed an `Embedded` `TView` which would be a child of `Component` `TView`) */ Component = 1, /** * `TView` associated with a template. Such as `*ngIf`, `<ng-template>` etc... A `Component` * can have zero or more `Embedded` `TView`s. */ Embedded = 2, } /*
{ "end_byte": 22560, "start_byte": 15206, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_22562_22694
* The static data for an LView (shared between all templates of a * given type). * * Stored on the `ComponentDef.tView`. */ exp
{ "end_byte": 22694, "start_byte": 22562, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_22695_30716
rt interface TView { /** * Type of `TView` (`Root`|`Component`|`Embedded`). */ type: TViewType; /** * This is a blueprint used to generate LView instances for this TView. Copying this * blueprint is faster than creating a new LView from scratch. */ blueprint: LView; /** * The template function used to refresh the view of dynamically created views * and components. Will be null for inline views. */ template: ComponentTemplate<{}> | null; /** * A function containing query-related instructions. */ viewQuery: ViewQueriesFunction<{}> | null; /** * A `TNode` representing the declaration location of this `TView` (not part of this TView). */ declTNode: TNode | null; // FIXME(misko): Why does `TView` not have `declarationTView` property? /** Whether or not this template has been processed in creation mode. */ firstCreatePass: boolean; /** * Whether or not this template has been processed in update mode (e.g. change detected) * * `firstUpdatePass` is used by styling to set up `TData` to contain metadata about the styling * instructions. (Mainly to build up a linked list of styling priority order.) * * Typically this function gets cleared after first execution. If exception is thrown then this * flag can remain turned un until there is first successful (no exception) pass. This means that * individual styling instructions keep track of if they have already been added to the linked * list to prevent double adding. */ firstUpdatePass: boolean; /** Static data equivalent of LView.data[]. Contains TNodes, PipeDefInternal or TI18n. */ data: TData; /** * The binding start index is the index at which the data array * starts to store bindings only. Saving this value ensures that we * will begin reading bindings at the correct point in the array when * we are in update mode. * * -1 means that it has not been initialized. */ bindingStartIndex: number; /** * The index where the "expando" section of `LView` begins. The expando * section contains injectors, directive instances, and host binding values. * Unlike the "decls" and "vars" sections of `LView`, the length of this * section cannot be calculated at compile-time because directives are matched * at runtime to preserve locality. * * We store this start index so we know where to start checking host bindings * in `setHostBindings`. */ expandoStartIndex: number; /** * Whether or not there are any static view queries tracked on this view. * * We store this so we know whether or not we should do a view query * refresh after creation mode to collect static query results. */ staticViewQueries: boolean; /** * Whether or not there are any static content queries tracked on this view. * * We store this so we know whether or not we should do a content query * refresh after creation mode to collect static query results. */ staticContentQueries: boolean; /** * A reference to the first child node located in the view. */ firstChild: TNode | null; /** * Stores the OpCodes to be replayed during change-detection to process the `HostBindings` * * See `HostBindingOpCodes` for encoding details. */ hostBindingOpCodes: HostBindingOpCodes | null; /** * Full registry of directives and components that may be found in this view. * * It's necessary to keep a copy of the full def list on the TView so it's possible * to render template functions without a host component. */ directiveRegistry: DirectiveDefList | null; /** * Full registry of pipes that may be found in this view. * * The property is either an array of `PipeDefs`s or a function which returns the array of * `PipeDefs`s. The function is necessary to be able to support forward declarations. * * It's necessary to keep a copy of the full def list on the TView so it's possible * to render template functions without a host component. */ pipeRegistry: PipeDefList | null; /** * Array of ngOnInit, ngOnChanges and ngDoCheck hooks that should be executed for this view in * creation mode. * * This array has a flat structure and contains TNode indices, directive indices (where an * instance can be found in `LView`) and hook functions. TNode index is followed by the directive * index and a hook function. If there are multiple hooks for a given TNode, the TNode index is * not repeated and the next lifecycle hook information is stored right after the previous hook * function. This is done so that at runtime the system can efficiently iterate over all of the * functions to invoke without having to make any decisions/lookups. */ preOrderHooks: HookData | null; /** * Array of ngOnChanges and ngDoCheck hooks that should be executed for this view in update mode. * * This array has the same structure as the `preOrderHooks` one. */ preOrderCheckHooks: HookData | null; /** * Array of ngAfterContentInit and ngAfterContentChecked hooks that should be executed * for this view in creation mode. * * Even indices: Directive index * Odd indices: Hook function */ contentHooks: HookData | null; /** * Array of ngAfterContentChecked hooks that should be executed for this view in update * mode. * * Even indices: Directive index * Odd indices: Hook function */ contentCheckHooks: HookData | null; /** * Array of ngAfterViewInit and ngAfterViewChecked hooks that should be executed for * this view in creation mode. * * Even indices: Directive index * Odd indices: Hook function */ viewHooks: HookData | null; /** * Array of ngAfterViewChecked hooks that should be executed for this view in * update mode. * * Even indices: Directive index * Odd indices: Hook function */ viewCheckHooks: HookData | null; /** * Array of ngOnDestroy hooks that should be executed when this view is destroyed. * * Even indices: Directive index * Odd indices: Hook function */ destroyHooks: DestroyHookData | null; /** * When a view is destroyed, listeners need to be released and outputs need to be * unsubscribed. This cleanup array stores both listener data (in chunks of 4) * and output data (in chunks of 2) for a particular view. Combining the arrays * saves on memory (70 bytes per array) and on a few bytes of code size (for two * separate for loops). * * If it's a native DOM listener or output subscription being stored: * 1st index is: event name `name = tView.cleanup[i+0]` * 2nd index is: index of native element or a function that retrieves global target (window, * document or body) reference based on the native element: * `typeof idxOrTargetGetter === 'function'`: global target getter function * `typeof idxOrTargetGetter === 'number'`: index of native element * * 3rd index is: index of listener function `listener = lView[CLEANUP][tView.cleanup[i+2]]` * 4th index is: `useCaptureOrIndx = tView.cleanup[i+3]` * `typeof useCaptureOrIndx == 'boolean' : useCapture boolean * `typeof useCaptureOrIndx == 'number': * `useCaptureOrIndx >= 0` `removeListener = LView[CLEANUP][useCaptureOrIndx]` * `useCaptureOrIndx < 0` `subscription = LView[CLEANUP][-useCaptureOrIndx]` * * If it's an output subscription or query list destroy hook: * 1st index is: output unsubscribe function / query list destroy function * 2nd index is: index of function context in LView.cleanupInstances[] * `tView.cleanup[i+0].call(lView[CLEANUP][tView.cleanup[i+1]])` */ cleanup: any[] | null; /** * A list of element indices for child components that will need to be * refreshed when the current view has finished its check. These indices have * already been adjusted for the HEADER_OFFSET. * */ components: number[] | null;
{ "end_byte": 30716, "start_byte": 22695, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/view.ts_30720_35155
* A collection of queries tracked in a given view. */ queries: TQueries | null; /** * An array of indices pointing to directives with content queries alongside with the * corresponding query index. Each entry in this array is a tuple of: * - index of the first content query index declared by a given directive; * - index of a directive. * * We are storing those indexes so we can refresh content queries as part of a view refresh * process. */ contentQueries: number[] | null; /** * Set of schemas that declare elements to be allowed inside the view. */ schemas: SchemaMetadata[] | null; /** * Array of constants for the view. Includes attribute arrays, local definition arrays etc. * Used for directive matching, attribute bindings, local definitions and more. */ consts: TConstants | null; /** * Indicates that there was an error before we managed to complete the first create pass of the * view. This means that the view is likely corrupted and we should try to recover it. */ incompleteFirstPass: boolean; /** * Unique id of this TView for hydration purposes: * - TViewType.Embedded: a unique id generated during serialization on the server * - TViewType.Component: an id generated based on component properties * (see `getComponentId` function for details) */ ssrId: string | null; } /** Single hook callback function. */ export type HookFn = () => void; /** * Information necessary to call a hook. E.g. the callback that * needs to invoked and the index at which to find its context. */ export type HookEntry = number | HookFn; /** * Array of hooks that should be executed for a view and their directive indices. * * For each node of the view, the following data is stored: * 1) Node index (optional) * 2) A series of number/function pairs where: * - even indices are directive indices * - odd indices are hook functions * * Special cases: * - a negative directive index flags an init hook (ngOnInit, ngAfterContentInit, ngAfterViewInit) */ export type HookData = HookEntry[]; /** * Array of destroy hooks that should be executed for a view and their directive indices. * * The array is set up as a series of number/function or number/(number|function)[]: * - Even indices represent the context with which hooks should be called. * - Odd indices are the hook functions themselves. If a value at an odd index is an array, * it represents the destroy hooks of a `multi` provider where: * - Even indices represent the index of the provider for which we've registered a destroy hook, * inside of the `multi` provider array. * - Odd indices are the destroy hook functions. * For example: * LView: `[0, 1, 2, AService, 4, [BService, CService, DService]]` * destroyHooks: `[3, AService.ngOnDestroy, 5, [0, BService.ngOnDestroy, 2, DService.ngOnDestroy]]` * * In the example above `AService` is a type provider with an `ngOnDestroy`, whereas `BService`, * `CService` and `DService` are part of a `multi` provider where only `BService` and `DService` * have an `ngOnDestroy` hook. */ export type DestroyHookData = (HookEntry | HookData)[]; /** * Static data that corresponds to the instance-specific data array on an LView. * * Each node's static data is stored in tData at the same index that it's stored * in the data array. Any nodes that do not have static data store a null value in * tData to avoid a sparse array. * * Each pipe's definition is stored here at the same index as its pipe instance in * the data array. * * Each host property's name is stored here at the same index as its value in the * data array. * * Each property binding name is stored here at the same index as its value in * the data array. If the binding is an interpolation, the static string values * are stored parallel to the dynamic values. Example: * * id="prefix {{ v0 }} a {{ v1 }} b {{ v2 }} suffix" * * LView | TView.data *------------------------ * v0 value | 'a' * v1 value | 'b' * v2 value | id � prefix � suffix * * Injector bloom filters are also stored here. */ export type TData = ( | TNode | PipeDef<any> | DirectiveDef<any> | ComponentDef<any> | number | TStylingRange | TStylingKey | ProviderToken<any> | TI18n | I18nUpdateOpCodes | TIcu | null | string | TDeferBlockDetails )[];
{ "end_byte": 35155, "start_byte": 30720, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/view.ts" }
angular/packages/core/src/render3/interfaces/container.ts_0_4547
/** * @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 {DehydratedContainerView} from '../../hydration/interfaces'; import {TNode} from './node'; import {RComment, RElement} from './renderer_dom'; import {FLAGS, HOST, LView, NEXT, PARENT, T_HOST} from './view'; /** * Special location which allows easy identification of type. If we have an array which was * retrieved from the `LView` and that array has `true` at `TYPE` location, we know it is * `LContainer`. */ export const TYPE = 1; /** * Below are constants for LContainer indices to help us look up LContainer members * without having to remember the specific indices. * Uglify will inline these when minifying so there shouldn't be a cost. */ // FLAGS, PARENT, NEXT, and T_HOST are indices 2, 3, 4, and 5 // As we already have these constants in LView, we don't need to re-create them. export const DEHYDRATED_VIEWS = 6; export const NATIVE = 7; export const VIEW_REFS = 8; export const MOVED_VIEWS = 9; /** * Size of LContainer's header. Represents the index after which all views in the * container will be inserted. We need to keep a record of current views so we know * which views are already in the DOM (and don't need to be re-added) and so we can * remove views from the DOM when they are no longer required. */ export const CONTAINER_HEADER_OFFSET = 10; /** * The state associated with a container. * * This is an array so that its structure is closer to LView. This helps * when traversing the view tree (which is a mix of containers and component * views), so we can jump to viewOrContainer[NEXT] in the same way regardless * of type. */ export interface LContainer extends Array<any> { /** * The host element of this LContainer. * * The host could be an LView if this container is on a component node. * In that case, the component LView is its HOST. */ readonly [HOST]: RElement | RComment | LView; /** * This is a type field which allows us to differentiate `LContainer` from `StylingContext` in an * efficient way. The value is always set to `true` */ [TYPE]: true; /** Flags for this container. See LContainerFlags for more info. */ [FLAGS]: LContainerFlags; /** * Access to the parent view is necessary so we can propagate back * up from inside a container to parent[NEXT]. */ [PARENT]: LView; /** * This allows us to jump from a container to a sibling container or component * view with the same parent, so we can remove listeners efficiently. */ [NEXT]: LView | LContainer | null; /** * A collection of views created based on the underlying `<ng-template>` element but inserted into * a different `LContainer`. We need to track views created from a given declaration point since * queries collect matches from the embedded view declaration point and _not_ the insertion point. */ [MOVED_VIEWS]: LView[] | null; /** * Pointer to the `TNode` which represents the host of the container. */ [T_HOST]: TNode; /** The comment element that serves as an anchor for this LContainer. */ [NATIVE]: RComment; /** * Array of `ViewRef`s used by any `ViewContainerRef`s that point to this container. * * This is lazily initialized by `ViewContainerRef` when the first view is inserted. * * NOTE: This is stored as `any[]` because render3 should really not be aware of `ViewRef` and * doing so creates circular dependency. */ [VIEW_REFS]: unknown[] | null; /** * Array of dehydrated views within this container. * * This information is used during the hydration process on the client. * The hydration logic tries to find a matching dehydrated view, "claim" it * and use this information to do further matching. After that, this "claimed" * view is removed from the list. The remaining "unclaimed" views are * "garbage-collected" later on, i.e. removed from the DOM once the hydration * logic finishes. */ [DEHYDRATED_VIEWS]: DehydratedContainerView[] | null; } /** Flags associated with an LContainer (saved in LContainer[FLAGS]) */ export enum LContainerFlags { None = 0, /** * Flag to signify that this `LContainer` may have transplanted views which need to be change * detected. (see: `LView[DECLARATION_COMPONENT_VIEW])`. * * This flag, once set, is never unset for the `LContainer`. */ HasTransplantedViews = 1 << 1, }
{ "end_byte": 4547, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/container.ts" }
angular/packages/core/src/render3/interfaces/injector.ts_0_5942
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectFlags} from '../../di/interface/injector'; import {ProviderToken} from '../../di/provider_token'; import {assertDefined, assertEqual} from '../../util/assert'; import {TDirectiveHostNode} from './node'; import {LView, TData} from './view'; /** * Offsets of the `NodeInjector` data structure in the expando. * * `NodeInjector` is stored in both `LView` as well as `TView.data`. All storage requires 9 words. * First 8 are reserved for bloom filter and the 9th is reserved for the associated `TNode` as well * as parent `NodeInjector` pointer. All indexes are starting with `index` and have an offset as * shown. * * `LView` layout: * ``` * index + 0: cumulative bloom filter * index + 1: cumulative bloom filter * index + 2: cumulative bloom filter * index + 3: cumulative bloom filter * index + 4: cumulative bloom filter * index + 5: cumulative bloom filter * index + 6: cumulative bloom filter * index + 7: cumulative bloom filter * index + 8: cumulative bloom filter * index + PARENT: Index to the parent injector. See `RelativeInjectorLocation` * `const parent = lView[index + NodeInjectorOffset.PARENT]` * ``` * * `TViewData` layout: * ``` * index + 0: cumulative bloom filter * index + 1: cumulative bloom filter * index + 2: cumulative bloom filter * index + 3: cumulative bloom filter * index + 4: cumulative bloom filter * index + 5: cumulative bloom filter * index + 6: cumulative bloom filter * index + 7: cumulative bloom filter * index + 8: cumulative bloom filter * index + TNODE: TNode associated with this `NodeInjector` * `const tNode = tView.data[index + NodeInjectorOffset.TNODE]` * ``` */ export const enum NodeInjectorOffset { TNODE = 8, PARENT = 8, BLOOM_SIZE = 8, SIZE = 9, } /** * Represents a relative location of parent injector. * * The interfaces encodes number of parents `LView`s to traverse and index in the `LView` * pointing to the parent injector. */ export type RelativeInjectorLocation = number & { __brand__: 'RelativeInjectorLocationFlags'; }; export const enum RelativeInjectorLocationFlags { InjectorIndexMask = 0b111111111111111, ViewOffsetShift = 16, NO_PARENT = -1, } export const NO_PARENT_INJECTOR = -1 as RelativeInjectorLocation; /** * Each injector is saved in 9 contiguous slots in `LView` and 9 contiguous slots in * `TView.data`. This allows us to store information about the current node's tokens (which * can be shared in `TView`) as well as the tokens of its ancestor nodes (which cannot be * shared, so they live in `LView`). * * Each of these slots (aside from the last slot) contains a bloom filter. This bloom filter * determines whether a directive is available on the associated node or not. This prevents us * from searching the directives array at this level unless it's probable the directive is in it. * * See: https://en.wikipedia.org/wiki/Bloom_filter for more about bloom filters. * * Because all injectors have been flattened into `LView` and `TViewData`, they cannot typed * using interfaces as they were previously. The start index of each `LInjector` and `TInjector` * will differ based on where it is flattened into the main array, so it's not possible to know * the indices ahead of time and save their types here. The interfaces are still included here * for documentation purposes. * * export interface LInjector extends Array<any> { * * // Cumulative bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE) * [0]: number; * * // Cumulative bloom for directive IDs 32-63 * [1]: number; * * // Cumulative bloom for directive IDs 64-95 * [2]: number; * * // Cumulative bloom for directive IDs 96-127 * [3]: number; * * // Cumulative bloom for directive IDs 128-159 * [4]: number; * * // Cumulative bloom for directive IDs 160 - 191 * [5]: number; * * // Cumulative bloom for directive IDs 192 - 223 * [6]: number; * * // Cumulative bloom for directive IDs 224 - 255 * [7]: number; * * // We need to store a reference to the injector's parent so DI can keep looking up * // the injector tree until it finds the dependency it's looking for. * [PARENT_INJECTOR]: number; * } * * export interface TInjector extends Array<any> { * * // Shared node bloom for directive IDs 0-31 (IDs are % BLOOM_SIZE) * [0]: number; * * // Shared node bloom for directive IDs 32-63 * [1]: number; * * // Shared node bloom for directive IDs 64-95 * [2]: number; * * // Shared node bloom for directive IDs 96-127 * [3]: number; * * // Shared node bloom for directive IDs 128-159 * [4]: number; * * // Shared node bloom for directive IDs 160 - 191 * [5]: number; * * // Shared node bloom for directive IDs 192 - 223 * [6]: number; * * // Shared node bloom for directive IDs 224 - 255 * [7]: number; * * // Necessary to find directive indices for a particular node. * [TNODE]: TElementNode|TElementContainerNode|TContainerNode; * } */ /** * Factory for creating instances of injectors in the NodeInjector. * * This factory is complicated by the fact that it can resolve `multi` factories as well. * * NOTE: Some of the fields are optional which means that this class has two hidden classes. * - One without `multi` support (most common) * - One with `multi` values, (rare). * * Since VMs can cache up to 4 inline hidden classes this is OK. * * - Single factory: Only `resolving` and `factory` is defined. * - `providers` factory: `componentProviders` is a number and `index = -1`. * - `viewProviders` factory: `componentProviders` is a number and `index` points to `providers`. */
{ "end_byte": 5942, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/injector.ts" }
angular/packages/core/src/render3/interfaces/injector.ts_5943_10182
export class NodeInjectorFactory { /** * The inject implementation to be activated when using the factory. */ injectImpl: null | (<T>(token: ProviderToken<T>, flags?: InjectFlags) => T); /** * Marker set to true during factory invocation to see if we get into recursive loop. * Recursive loop causes an error to be displayed. */ resolving = false; /** * Marks that the token can see other Tokens declared in `viewProviders` on the same node. */ canSeeViewProviders: boolean; /** * An array of factories to use in case of `multi` provider. */ multi?: Array<() => any>; /** * Number of `multi`-providers which belong to the component. * * This is needed because when multiple components and directives declare the `multi` provider * they have to be concatenated in the correct order. * * Example: * * If we have a component and directive active an a single element as declared here * ``` * component: * providers: [ {provide: String, useValue: 'component', multi: true} ], * viewProviders: [ {provide: String, useValue: 'componentView', multi: true} ], * * directive: * providers: [ {provide: String, useValue: 'directive', multi: true} ], * ``` * * Then the expected results are: * * ``` * providers: ['component', 'directive'] * viewProviders: ['component', 'componentView', 'directive'] * ``` * * The way to think about it is that the `viewProviders` have been inserted after the component * but before the directives, which is why we need to know how many `multi`s have been declared by * the component. */ componentProviders?: number; /** * Current index of the Factory in the `data`. Needed for `viewProviders` and `providers` merging. * See `providerFactory`. */ index?: number; /** * Because the same `multi` provider can be declared in `providers` and `viewProviders` it is * possible for `viewProviders` to shadow the `providers`. For this reason we store the * `provideFactory` of the `providers` so that `providers` can be extended with `viewProviders`. * * Example: * * Given: * ``` * providers: [ {provide: String, useValue: 'all', multi: true} ], * viewProviders: [ {provide: String, useValue: 'viewOnly', multi: true} ], * ``` * * We have to return `['all']` in case of content injection, but `['all', 'viewOnly']` in case * of view injection. We further have to make sure that the shared instances (in our case * `all`) are the exact same instance in both the content as well as the view injection. (We * have to make sure that we don't double instantiate.) For this reason the `viewProviders` * `Factory` has a pointer to the shadowed `providers` factory so that it can instantiate the * `providers` (`['all']`) and then extend it with `viewProviders` (`['all'] + ['viewOnly'] = * ['all', 'viewOnly']`). */ providerFactory?: NodeInjectorFactory | null; constructor( /** * Factory to invoke in order to create a new instance. */ public factory: ( this: NodeInjectorFactory, _: undefined, /** * array where injectables tokens are stored. This is used in * case of an error reporting to produce friendlier errors. */ tData: TData, /** * array where existing instances of injectables are stored. This is used in case * of multi shadow is needed. See `multi` field documentation. */ lView: LView, /** * The TNode of the same element injector. */ tNode: TDirectiveHostNode, ) => any, /** * Set to `true` if the token is declared in `viewProviders` (or if it is component). */ isViewProvider: boolean, injectImplementation: null | (<T>(token: ProviderToken<T>, flags?: InjectFlags) => T), ) { ngDevMode && assertDefined(factory, 'Factory not specified'); ngDevMode && assertEqual(typeof factory, 'function', 'Expected factory function.'); this.canSeeViewProviders = isViewProvider; this.injectImpl = injectImplementation; } } export function isFactory(obj: any): obj is NodeInjectorFactory { return obj instanceof NodeInjectorFactory; }
{ "end_byte": 10182, "start_byte": 5943, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/injector.ts" }
angular/packages/core/src/render3/interfaces/input_flags.ts_0_356
/** * @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 */ /** Flags describing an input for a directive. */ export enum InputFlags { None = 0, SignalBased = 1 << 0, HasDecoratorInputTransform = 1 << 1, }
{ "end_byte": 356, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/input_flags.ts" }
angular/packages/core/src/render3/interfaces/attribute_marker.ts_0_3581
/** * @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 */ /** * A set of marker values to be used in the attributes arrays. These markers indicate that some * items are not regular attributes and the processing should be adapted accordingly. */ export const enum AttributeMarker { /** * An implicit marker which indicates that the value in the array are of `attributeKey`, * `attributeValue` format. * * NOTE: This is implicit as it is the type when no marker is present in array. We indicate that * it should not be present at runtime by the negative number. */ ImplicitAttributes = -1, /** * Marker indicates that the following 3 values in the attributes array are: * namespaceUri, attributeName, attributeValue * in that order. */ NamespaceURI = 0, /** * Signals class declaration. * * Each value following `Classes` designates a class name to include on the element. * ## Example: * * Given: * ``` * <div class="foo bar baz">...<d/vi> * ``` * * the generated code is: * ``` * var _c1 = [AttributeMarker.Classes, 'foo', 'bar', 'baz']; * ``` */ Classes = 1, /** * Signals style declaration. * * Each pair of values following `Styles` designates a style name and value to include on the * element. * ## Example: * * Given: * ``` * <div style="width:100px; height:200px; color:red">...</div> * ``` * * the generated code is: * ``` * var _c1 = [AttributeMarker.Styles, 'width', '100px', 'height'. '200px', 'color', 'red']; * ``` */ Styles = 2, /** * Signals that the following attribute names were extracted from input or output bindings. * * For example, given the following HTML: * * ``` * <div moo="car" [foo]="exp" (bar)="doSth()"> * ``` * * the generated code is: * * ``` * var _c1 = ['moo', 'car', AttributeMarker.Bindings, 'foo', 'bar']; * ``` */ Bindings = 3, /** * Signals that the following attribute names were hoisted from an inline-template declaration. * * For example, given the following HTML: * * ``` * <div *ngFor="let value of values; trackBy:trackBy" dirA [dirB]="value"> * ``` * * the generated code for the `template()` instruction would include: * * ``` * ['dirA', '', AttributeMarker.Bindings, 'dirB', AttributeMarker.Template, 'ngFor', 'ngForOf', * 'ngForTrackBy', 'let-value'] * ``` * * while the generated code for the `element()` instruction inside the template function would * include: * * ``` * ['dirA', '', AttributeMarker.Bindings, 'dirB'] * ``` */ Template = 4, /** * Signals that the following attribute is `ngProjectAs` and its value is a parsed * `CssSelector`. * * For example, given the following HTML: * * ``` * <h1 attr="value" ngProjectAs="[title]"> * ``` * * the generated code for the `element()` instruction would include: * * ``` * ['attr', 'value', AttributeMarker.ProjectAs, ['', 'title', '']] * ``` */ ProjectAs = 5, /** * Signals that the following attribute will be translated by runtime i18n * * For example, given the following HTML: * * ``` * <div moo="car" foo="value" i18n-foo [bar]="binding" i18n-bar> * ``` * * the generated code is: * * ``` * var _c1 = ['moo', 'car', AttributeMarker.I18n, 'foo', 'bar']; */ I18n = 6, }
{ "end_byte": 3581, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/attribute_marker.ts" }
angular/packages/core/src/render3/interfaces/styling.ts_0_7296
/** * @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} from '../../util/array_utils'; import {assertNumber, assertNumberInRange} from '../../util/assert'; /** * Value stored in the `TData` which is needed to re-concatenate the styling. * * See: `TStylingKeyPrimitive` and `TStylingStatic` */ export type TStylingKey = TStylingKeyPrimitive | TStylingStatic; /** * The primitive portion (`TStylingStatic` removed) of the value stored in the `TData` which is * needed to re-concatenate the styling. * * - `string`: Stores the property name. Used with `ɵɵstyleProp`/`ɵɵclassProp` instruction. * - `null`: Represents map, so there is no name. Used with `ɵɵstyleMap`/`ɵɵclassMap`. * - `false`: Represents an ignore case. This happens when `ɵɵstyleProp`/`ɵɵclassProp` instruction * is combined with directive which shadows its input `@Input('class')`. That way the binding * should not participate in the styling resolution. */ export type TStylingKeyPrimitive = string | null | false; /** * Store the static values for the styling binding. * * The `TStylingStatic` is just `KeyValueArray` where key `""` (stored at location 0) contains the * `TStylingKey` (stored at location 1). In other words this wraps the `TStylingKey` such that the * `""` contains the wrapped value. * * When instructions are resolving styling they may need to look forward or backwards in the linked * list to resolve the value. For this reason we have to make sure that he linked list also contains * the static values. However the list only has space for one item per styling instruction. For this * reason we store the static values here as part of the `TStylingKey`. This means that the * resolution function when looking for a value needs to first look at the binding value, and than * at `TStylingKey` (if it exists). * * Imagine we have: * * ``` * <div class="TEMPLATE" my-dir> * * @Directive({ * host: { * class: 'DIR', * '[class.dynamic]': 'exp' // ɵɵclassProp('dynamic', ctx.exp); * } * }) * ``` * * In the above case the linked list will contain one item: * * ``` * // assume binding location: 10 for `ɵɵclassProp('dynamic', ctx.exp);` * tData[10] = <TStylingStatic>[ * '': 'dynamic', // This is the wrapped value of `TStylingKey` * 'DIR': true, // This is the default static value of directive binding. * ]; * tData[10 + 1] = 0; // We don't have prev/next. * * lView[10] = undefined; // assume `ctx.exp` is `undefined` * lView[10 + 1] = undefined; // Just normalized `lView[10]` * ``` * * So when the function is resolving styling value, it first needs to look into the linked list * (there is none) and than into the static `TStylingStatic` too see if there is a default value for * `dynamic` (there is not). Therefore it is safe to remove it. * * If setting `true` case: * ``` * lView[10] = true; // assume `ctx.exp` is `true` * lView[10 + 1] = true; // Just normalized `lView[10]` * ``` * So when the function is resolving styling value, it first needs to look into the linked list * (there is none) and than into `TNode.residualClass` (TNode.residualStyle) which contains * ``` * tNode.residualClass = [ * 'TEMPLATE': true, * ]; * ``` * * This means that it is safe to add class. */ export interface TStylingStatic extends KeyValueArray<any> {} /** * This is a branded number which contains previous and next index. * * When we come across styling instructions we need to store the `TStylingKey` in the correct * order so that we can re-concatenate the styling value in the desired priority. * * The insertion can happen either at the: * - end of template as in the case of coming across additional styling instruction in the template * - in front of the template in the case of coming across additional instruction in the * `hostBindings`. * * We use `TStylingRange` to store the previous and next index into the `TData` where the template * bindings can be found. * * - bit 0 is used to mark that the previous index has a duplicate for current value. * - bit 1 is used to mark that the next index has a duplicate for the current value. * - bits 2-16 are used to encode the next/tail of the template. * - bits 17-32 are used to encode the previous/head of template. * * NODE: *duplicate* false implies that it is statically known that this binding will not collide * with other bindings and therefore there is no need to check other bindings. For example the * bindings in `<div [style.color]="exp" [style.width]="exp">` will never collide and will have * their bits set accordingly. Previous duplicate means that we may need to check previous if the * current binding is `null`. Next duplicate means that we may need to check next bindings if the * current binding is not `null`. * * NOTE: `0` has special significance and represents `null` as in no additional pointer. */ export type TStylingRange = number & { __brand__: 'TStylingRange'; }; /** * Shift and masks constants for encoding two numbers into and duplicate info into a single number. */ export const enum StylingRange { /// Number of bits to shift for the previous pointer PREV_SHIFT = 17, /// Previous pointer mask. PREV_MASK = 0xfffe0000, /// Number of bits to shift for the next pointer NEXT_SHIFT = 2, /// Next pointer mask. NEXT_MASK = 0x001fffc, // Mask to remove negative bit. (interpret number as positive) UNSIGNED_MASK = 0x7fff, /** * This bit is set if the previous bindings contains a binding which could possibly cause a * duplicate. For example: `<div [style]="map" [style.width]="width">`, the `width` binding will * have previous duplicate set. The implication is that if `width` binding becomes `null`, it is * necessary to defer the value to `map.width`. (Because `width` overwrites `map.width`.) */ PREV_DUPLICATE = 0x02, /** * This bit is set to if the next binding contains a binding which could possibly cause a * duplicate. For example: `<div [style]="map" [style.width]="width">`, the `map` binding will * have next duplicate set. The implication is that if `map.width` binding becomes not `null`, it * is necessary to defer the value to `width`. (Because `width` overwrites `map.width`.) */ NEXT_DUPLICATE = 0x01, } export function toTStylingRange(prev: number, next: number): TStylingRange { ngDevMode && assertNumberInRange(prev, 0, StylingRange.UNSIGNED_MASK); ngDevMode && assertNumberInRange(next, 0, StylingRange.UNSIGNED_MASK); return ((prev << StylingRange.PREV_SHIFT) | (next << StylingRange.NEXT_SHIFT)) as TStylingRange; } export function getTStylingRangePrev(tStylingRange: TStylingRange): number { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange >> StylingRange.PREV_SHIFT) & StylingRange.UNSIGNED_MASK; } export function getTStylingRangePrevDuplicate(tStylingRange: TStylingRange): boolean { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange & StylingRange.PREV_DUPLICATE) == StylingRange.PREV_DUPLICATE; } export functio
{ "end_byte": 7296, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/styling.ts" }
angular/packages/core/src/render3/interfaces/styling.ts_7298_9201
setTStylingRangePrev( tStylingRange: TStylingRange, previous: number, ): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); ngDevMode && assertNumberInRange(previous, 0, StylingRange.UNSIGNED_MASK); return ((tStylingRange & ~StylingRange.PREV_MASK) | (previous << StylingRange.PREV_SHIFT)) as TStylingRange; } export function setTStylingRangePrevDuplicate(tStylingRange: TStylingRange): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange | StylingRange.PREV_DUPLICATE) as TStylingRange; } export function getTStylingRangeNext(tStylingRange: TStylingRange): number { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange & StylingRange.NEXT_MASK) >> StylingRange.NEXT_SHIFT; } export function setTStylingRangeNext(tStylingRange: TStylingRange, next: number): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); ngDevMode && assertNumberInRange(next, 0, StylingRange.UNSIGNED_MASK); return ((tStylingRange & ~StylingRange.NEXT_MASK) | // (next << StylingRange.NEXT_SHIFT)) as TStylingRange; } export function getTStylingRangeNextDuplicate(tStylingRange: TStylingRange): boolean { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange & StylingRange.NEXT_DUPLICATE) === StylingRange.NEXT_DUPLICATE; } export function setTStylingRangeNextDuplicate(tStylingRange: TStylingRange): TStylingRange { ngDevMode && assertNumber(tStylingRange, 'expected number'); return (tStylingRange | StylingRange.NEXT_DUPLICATE) as TStylingRange; } export function getTStylingRangeTail(tStylingRange: TStylingRange): number { ngDevMode && assertNumber(tStylingRange, 'expected number'); const next = getTStylingRangeNext(tStylingRange); return next === 0 ? getTStylingRangePrev(tStylingRange) : next; }
{ "end_byte": 9201, "start_byte": 7298, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/styling.ts" }
angular/packages/core/src/render3/interfaces/renderer_dom.ts_0_2829
/** * @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 {TrustedHTML, TrustedScript, TrustedScriptURL} from '../../util/security/trusted_type_defs'; /** * The goal here is to make sure that the browser DOM API is the Renderer. * We do this by defining a subset of DOM API to be the renderer and then * use that at runtime for rendering. * * At runtime we can then use the DOM api directly, in server or web-worker * it will be easy to implement such API. */ /** Subset of API needed for appending elements and text nodes. */ export interface RNode { /** * Returns the parent Element, Document, or DocumentFragment */ parentNode: RNode | null; /** * Returns the parent Element if there is one */ parentElement: RElement | null; /** * Gets the Node immediately following this one in the parent's childNodes */ nextSibling: RNode | null; /** * Insert a child node. * * Used exclusively for adding View root nodes into ViewAnchor location. */ insertBefore(newChild: RNode, refChild: RNode | null, isViewRoot: boolean): void; /** * Append a child node. * * Used exclusively for building up DOM which are static (ie not View roots) */ appendChild(newChild: RNode): RNode; } /** * Subset of API needed for writing attributes, properties, and setting up * listeners on Element. */ export interface RElement extends RNode { firstChild: RNode | null; style: RCssStyleDeclaration; classList: RDomTokenList; className: string; tagName: string; textContent: string | null; hasAttribute(name: string): boolean; getAttribute(name: string): string | null; setAttribute(name: string, value: string | TrustedHTML | TrustedScript | TrustedScriptURL): void; removeAttribute(name: string): void; setAttributeNS( namespaceURI: string, qualifiedName: string, value: string | TrustedHTML | TrustedScript | TrustedScriptURL, ): void; addEventListener(type: string, listener: EventListener, useCapture?: boolean): void; removeEventListener(type: string, listener?: EventListener, options?: boolean): void; remove(): void; setProperty?(name: string, value: any): void; } export interface RCssStyleDeclaration { removeProperty(propertyName: string): string; setProperty(propertyName: string, value: string | null, priority?: string): void; } export interface RDomTokenList { add(token: string): void; remove(token: string): void; } export interface RText extends RNode { textContent: string | null; } export interface RComment extends RNode { textContent: string | null; } export interface RTemplate extends RElement { tagName: 'TEMPLATE'; content: RNode; }
{ "end_byte": 2829, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/renderer_dom.ts" }
angular/packages/core/src/render3/interfaces/lview_tracking.ts_0_1384
/** * @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 {assertNumber} from '../../util/assert'; import {ID, LView} from './view'; // Keeps track of the currently-active LViews. const TRACKED_LVIEWS = new Map<number, LView>(); // Used for generating unique IDs for LViews. let uniqueIdCounter = 0; /** Gets a unique ID that can be assigned to an LView. */ export function getUniqueLViewId(): number { return uniqueIdCounter++; } /** Starts tracking an LView. */ export function registerLView(lView: LView): void { ngDevMode && assertNumber(lView[ID], 'LView must have an ID in order to be registered'); TRACKED_LVIEWS.set(lView[ID], lView); } /** Gets an LView by its unique ID. */ export function getLViewById(id: number): LView | null { ngDevMode && assertNumber(id, 'ID used for LView lookup must be a number'); return TRACKED_LVIEWS.get(id) || null; } /** Stops tracking an LView. */ export function unregisterLView(lView: LView): void { ngDevMode && assertNumber(lView[ID], 'Cannot stop tracking an LView that does not have an ID'); TRACKED_LVIEWS.delete(lView[ID]); } /** Gets the currently-tracked views. */ export function getTrackedLViews(): ReadonlyMap<number, LView> { return TRACKED_LVIEWS; }
{ "end_byte": 1384, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/lview_tracking.ts" }
angular/packages/core/src/render3/interfaces/renderer.ts_0_3000
/** * @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 {RendererStyleFlags2, RendererType2} from '../../render/api_flags'; import {TrustedHTML, TrustedScript, TrustedScriptURL} from '../../util/security/trusted_type_defs'; import {RComment, RElement, RNode, RText} from './renderer_dom'; /** * The goal here is to make sure that the browser DOM API is the Renderer. * We do this by defining a subset of DOM API to be the renderer and then * use that at runtime for rendering. * * At runtime we can then use the DOM api directly, in server or web-worker * it will be easy to implement such API. */ export type GlobalTargetName = 'document' | 'window' | 'body'; export type GlobalTargetResolver = (element: any) => EventTarget; /** * Procedural style of API needed to create elements and text nodes. * * In non-native browser environments (e.g. platforms such as web-workers), this is the * facade that enables element manipulation. In practice, this is implemented by `Renderer2`. */ export interface Renderer { destroy(): void; createComment(value: string): RComment; createElement(name: string, namespace?: string | null): RElement; createText(value: string): RText; /** * This property is allowed to be null / undefined, * in which case the view engine won't call it. * This is used as a performance optimization for production mode. */ destroyNode?: ((node: RNode) => void) | null; appendChild(parent: RElement, newChild: RNode): void; insertBefore(parent: RNode, newChild: RNode, refChild: RNode | null, isMove?: boolean): void; removeChild(parent: RElement | null, oldChild: RNode, isHostElement?: boolean): void; selectRootElement(selectorOrNode: string | any, preserveContent?: boolean): RElement; parentNode(node: RNode): RElement | null; nextSibling(node: RNode): RNode | null; setAttribute( el: RElement, name: string, value: string | TrustedHTML | TrustedScript | TrustedScriptURL, namespace?: string | null, ): void; removeAttribute(el: RElement, name: string, namespace?: string | null): void; addClass(el: RElement, name: string): void; removeClass(el: RElement, name: string): void; setStyle(el: RElement, style: string, value: any, flags?: RendererStyleFlags2): void; removeStyle(el: RElement, style: string, flags?: RendererStyleFlags2): void; setProperty(el: RElement, name: string, value: any): void; setValue(node: RText | RComment, value: string): void; // TODO(misko): Deprecate in favor of addEventListener/removeEventListener listen( target: GlobalTargetName | RNode, eventName: string, callback: (event: any) => boolean | void, ): () => void; } export interface RendererFactory { createRenderer(hostElement: RElement | null, rendererType: RendererType2 | null): Renderer; begin?(): void; end?(): void; }
{ "end_byte": 3000, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/renderer.ts" }
angular/packages/core/src/render3/interfaces/public_definitions.ts_0_3069
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // This file contains types that will be published to npm in library typings files. // Formatting does horrible things to these declarations. /** * @publicApi */ export type ɵɵDirectiveDeclaration< T, Selector extends string, ExportAs extends string[], // `string` keys are for backwards compatibility with pre-16 versions. InputMap extends { [key: string]: string | {alias: string | null; required: boolean; isSignal?: boolean}; }, OutputMap extends {[key: string]: string}, QueryFields extends string[], // Optional as this was added to align the `IsStandalone` parameters // between directive and component declarations. NgContentSelectors extends never = never, // Optional as this was added in Angular v14. All pre-existing directives // are not standalone. IsStandalone extends boolean = false, HostDirectives = never, IsSignal extends boolean = false, > = unknown; /** * @publicApi */ export type ɵɵComponentDeclaration< T, Selector extends String, ExportAs extends string[], // `string` keys are for backwards compatibility with pre-16 versions. InputMap extends {[key: string]: string | {alias: string | null; required: boolean}}, OutputMap extends {[key: string]: string}, QueryFields extends string[], NgContentSelectors extends string[], // Optional as this was added in Angular v14. All pre-existing components // are not standalone. IsStandalone extends boolean = false, HostDirectives = never, IsSignal extends boolean = false, > = unknown; /** * @publicApi */ export type ɵɵNgModuleDeclaration<T, Declarations, Imports, Exports> = unknown; /** * @publicApi */ export type ɵɵPipeDeclaration< T, Name extends string, // Optional as this was added in Angular v14. All pre-existing directives // are not standalone. IsStandalone extends boolean = false, > = unknown; /** * @publicApi */ export type ɵɵInjectorDeclaration<T> = unknown; /** * @publicApi */ export type ɵɵFactoryDeclaration<T, CtorDependencies extends CtorDependency[]> = unknown; /** * An object literal of this type is used to represent the metadata of a constructor dependency. * The type itself is never referred to from generated code. * * @publicApi */ export type CtorDependency = { /** * If an `@Attribute` decorator is used, this represents the injected attribute's name. If the * attribute name is a dynamic expression instead of a string literal, this will be the unknown * type. */ attribute?: string | unknown; /** * If `@Optional()` is used, this key is set to true. */ optional?: true; /** * If `@Host` is used, this key is set to true. */ host?: true; /** * If `@Self` is used, this key is set to true. */ self?: true; /** * If `@SkipSelf` is used, this key is set to true. */ skipSelf?: true; } | null;
{ "end_byte": 3069, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/public_definitions.ts" }
angular/packages/core/src/render3/interfaces/query.ts_0_8185
/** * @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 {QueryList} from '../../linker/query_list'; import {TNode} from './node'; import {TView} from './view'; /** * An object representing query metadata extracted from query annotations. */ export interface TQueryMetadata { predicate: ProviderToken<unknown> | string[]; read: any; flags: QueryFlags; } /** * A set of flags to be used with Queries. * * NOTE: Ensure changes here are reflected in `packages/compiler/src/render3/view/compiler.ts` */ export const enum QueryFlags { /** * No flags */ none = 0b0000, /** * Whether or not the query should descend into children. */ descendants = 0b0001, /** * The query can be computed statically and hence can be assigned eagerly. * * NOTE: Backwards compatibility with ViewEngine. */ isStatic = 0b0010, /** * If the `QueryList` should fire change event only if actual change to query was computed (vs old * behavior where the change was fired whenever the query was recomputed, even if the recomputed * query resulted in the same list.) */ emitDistinctChangesOnly = 0b0100, } /** * TQuery objects represent all the query-related data that remain the same from one view instance * to another and can be determined on the very first template pass. Most notably TQuery holds all * the matches for a given view. */ export interface TQuery { /** * Query metadata extracted from query annotations. */ metadata: TQueryMetadata; /** * Index of a query in a declaration view in case of queries propagated to en embedded view, -1 * for queries declared in a given view. We are storing this index so we can find a parent query * to clone for an embedded view (when an embedded view is created). */ indexInDeclarationView: number; /** * Matches collected on the first template pass. Each match is a pair of: * - TNode index; * - match index; * * A TNode index can be either: * - a positive number (the most common case) to indicate a matching TNode; * - a negative number to indicate that a given query is crossing a <ng-template> element and * results from views created based on TemplateRef should be inserted at this place. * * A match index is a number used to find an actual value (for a given node) when query results * are materialized. This index can have one of the following values: * - -2 - indicates that we need to read a special token (TemplateRef, ViewContainerRef etc.); * - -1 - indicates that we need to read a default value based on the node type (TemplateRef for * ng-template and ElementRef for other elements); * - a positive number - index of an injectable to be read from the element injector. */ matches: number[] | null; /** * A flag indicating if a given query crosses an <ng-template> element. This flag exists for * performance reasons: we can notice that queries not crossing any <ng-template> elements will * have matches from a given view only (and adapt processing accordingly). */ crossesNgTemplate: boolean; /** * A method call when a given query is crossing an element (or element container). This is where a * given TNode is matched against a query predicate. * @param tView * @param tNode */ elementStart(tView: TView, tNode: TNode): void; /** * A method called when processing the elementEnd instruction - this is mostly useful to determine * if a given content query should match any nodes past this point. * @param tNode */ elementEnd(tNode: TNode): void; /** * A method called when processing the template instruction. This is where a * given TContainerNode is matched against a query predicate. * @param tView * @param tNode */ template(tView: TView, tNode: TNode): void; /** * A query-related method called when an embedded TView is created based on the content of a * <ng-template> element. We call this method to determine if a given query should be propagated * to the embedded view and if so - return a cloned TQuery for this embedded view. * @param tNode * @param childQueryIndex */ embeddedTView(tNode: TNode, childQueryIndex: number): TQuery | null; } /** * TQueries represent a collection of individual TQuery objects tracked in a given view. Most of the * methods on this interface are simple proxy methods to the corresponding functionality on TQuery. */ export interface TQueries { /** * Adds a new TQuery to a collection of queries tracked in a given view. * @param tQuery */ track(tQuery: TQuery): void; /** * Returns a TQuery instance for at the given index in the queries array. * @param index */ getByIndex(index: number): TQuery; /** * Returns the number of queries tracked in a given view. */ length: number; /** * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding * `elementStart` on each and every TQuery. * @param tView * @param tNode */ elementStart(tView: TView, tNode: TNode): void; /** * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding * `elementEnd` on each and every TQuery. * @param tNode */ elementEnd(tNode: TNode): void; /** * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding * `template` on each and every TQuery. * @param tView * @param tNode */ template(tView: TView, tNode: TNode): void; /** * A proxy method that iterates over all the TQueries in a given TView and calls the corresponding * `embeddedTView` on each and every TQuery. * @param tNode */ embeddedTView(tNode: TNode): TQueries | null; } /** * An interface that represents query-related information specific to a view instance. Most notably * it contains: * - materialized query matches; * - a pointer to a QueryList where materialized query results should be reported. */ export interface LQuery<T> { /** * Materialized query matches for a given view only (!). Results are initialized lazily so the * array of matches is set to `null` initially. */ matches: (T | null)[] | null; /** * A QueryList where materialized query results should be reported. */ queryList: QueryList<T>; /** * Clones an LQuery for an embedded view. A cloned query shares the same `QueryList` but has a * separate collection of materialized matches. */ clone(): LQuery<T>; /** * Called when an embedded view, impacting results of this query, is inserted or removed. */ setDirty(): void; } /** * lQueries represent a collection of individual LQuery objects tracked in a given view. */ export interface LQueries { /** * A collection of queries tracked in a given view. */ queries: LQuery<any>[]; /** * A method called when a new embedded view is created. As a result a set of LQueries applicable * for a new embedded view is instantiated (cloned) from the declaration view. * @param tView */ createEmbeddedView(tView: TView): LQueries | null; /** * A method called when an embedded view is inserted into a container. As a result all impacted * `LQuery` objects (and associated `QueryList`) are marked as dirty. * @param tView */ insertView(tView: TView): void; /** * A method called when an embedded view is detached from a container. As a result all impacted * `LQuery` objects (and associated `QueryList`) are marked as dirty. * @param tView */ detachView(tView: TView): void; /** * A method called when a view finishes its creation pass. As a result all impacted * `LQuery` objects (and associated `QueryList`) are marked as dirty. This additional dirty * marking gives us a precise point in time where we can collect results for a given view in an * atomic way. * @param tView */ finishViewCreation(tView: TView): void; }
{ "end_byte": 8185, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/interfaces/query.ts" }
angular/packages/core/src/render3/debug/injector_profiler.ts_0_9014
/** * @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 {FactoryProvider} from '../../di'; import {resolveForwardRef} from '../../di/forward_ref'; import {InjectionToken} from '../../di/injection_token'; import type {Injector} from '../../di/injector'; import {InjectFlags, InjectOptions, InternalInjectFlags} from '../../di/interface/injector'; import type {SingleProvider} from '../../di/provider_collection'; import {Type} from '../../interface/type'; import {throwError} from '../../util/assert'; import type {TNode} from '../interfaces/node'; import type {LView} from '../interfaces/view'; /** * An enum describing the types of events that can be emitted from the injector profiler */ export const enum InjectorProfilerEventType { /** * Emits when a service is injected. */ Inject, /** * Emits when an Angular class instance is created by an injector. */ InstanceCreatedByInjector, /** * Emits when an injector configures a provider. */ ProviderConfigured, } /** * An object that defines an injection context for the injector profiler. */ export interface InjectorProfilerContext { /** * The Injector that service is being injected into. * - Example: if ModuleA --provides--> ServiceA --injects--> ServiceB * then inject(ServiceB) in ServiceA has ModuleA as an injector context */ injector: Injector; /** * The class where the constructor that is calling `inject` is located * - Example: if ModuleA --provides--> ServiceA --injects--> ServiceB * then inject(ServiceB) in ServiceA has ServiceA as a construction context */ token: Type<unknown> | null; } export interface InjectedServiceEvent { type: InjectorProfilerEventType.Inject; context: InjectorProfilerContext; service: InjectedService; } export interface InjectorCreatedInstanceEvent { type: InjectorProfilerEventType.InstanceCreatedByInjector; context: InjectorProfilerContext; instance: InjectorCreatedInstance; } export interface ProviderConfiguredEvent { type: InjectorProfilerEventType.ProviderConfigured; context: InjectorProfilerContext; providerRecord: ProviderRecord; } /** * An object representing an event that is emitted through the injector profiler */ export type InjectorProfilerEvent = | InjectedServiceEvent | InjectorCreatedInstanceEvent | ProviderConfiguredEvent; /** * An object that contains information about a provider that has been configured * * TODO: rename to indicate that it is a debug structure eg. ProviderDebugInfo. */ export interface ProviderRecord { /** * DI token that this provider is configuring */ token: Type<unknown> | InjectionToken<unknown>; /** * Determines if provider is configured as view provider. */ isViewProvider: boolean; /** * The raw provider associated with this ProviderRecord. */ provider: SingleProvider; /** * The path of DI containers that were followed to import this provider */ importPath?: Type<unknown>[]; } /** * An object that contains information about a value that has been constructed within an injector */ export interface InjectorCreatedInstance { /** * Value of the created instance */ value: unknown; } /** * An object that contains information a service that has been injected within an * InjectorProfilerContext */ export interface InjectedService { /** * DI token of the Service that is injected */ token?: Type<unknown> | InjectionToken<unknown>; /** * Value of the injected service */ value: unknown; /** * Flags that this service was injected with */ flags?: InternalInjectFlags | InjectFlags | InjectOptions; /** * Injector that this service was provided in. */ providedIn?: Injector; /** * In NodeInjectors, the LView and TNode that serviced this injection. */ injectedIn?: {lView: LView; tNode: TNode}; } export interface InjectorProfiler { (event: InjectorProfilerEvent): void; } let _injectorProfilerContext: InjectorProfilerContext; export function getInjectorProfilerContext() { !ngDevMode && throwError('getInjectorProfilerContext should never be called in production mode'); return _injectorProfilerContext; } export function setInjectorProfilerContext(context: InjectorProfilerContext) { !ngDevMode && throwError('setInjectorProfilerContext should never be called in production mode'); const previous = _injectorProfilerContext; _injectorProfilerContext = context; return previous; } let injectorProfilerCallback: InjectorProfiler | null = null; /** * Sets the callback function which will be invoked during certain DI events within the * runtime (for example: injecting services, creating injectable instances, configuring providers) * * Warning: this function is *INTERNAL* and should not be relied upon in application's code. * The contract of the function might be changed in any release and/or the function can be removed * completely. * * @param profiler function provided by the caller or null value to disable profiling. */ export const setInjectorProfiler = (injectorProfiler: InjectorProfiler | null) => { !ngDevMode && throwError('setInjectorProfiler should never be called in production mode'); injectorProfilerCallback = injectorProfiler; }; /** * Injector profiler function which emits on DI events executed by the runtime. * * @param event InjectorProfilerEvent corresponding to the DI event being emitted */ function injectorProfiler(event: InjectorProfilerEvent): void { !ngDevMode && throwError('Injector profiler should never be called in production mode'); if (injectorProfilerCallback != null /* both `null` and `undefined` */) { injectorProfilerCallback!(event); } } /** * Emits an InjectorProfilerEventType.ProviderConfigured to the injector profiler. The data in the * emitted event includes the raw provider, as well as the token that provider is providing. * * @param eventProvider A provider object */ export function emitProviderConfiguredEvent( eventProvider: SingleProvider, isViewProvider: boolean = false, ): void { !ngDevMode && throwError('Injector profiler should never be called in production mode'); let token; // if the provider is a TypeProvider (typeof provider is function) then the token is the // provider itself if (typeof eventProvider === 'function') { token = eventProvider; } // if the provider is an injection token, then the token is the injection token. else if (eventProvider instanceof InjectionToken) { token = eventProvider; } // in all other cases we can access the token via the `provide` property of the provider else { token = resolveForwardRef(eventProvider.provide); } let provider = eventProvider; // Injection tokens may define their own default provider which gets attached to the token itself // as `ɵprov`. In this case, we want to emit the provider that is attached to the token, not the // token itself. if (eventProvider instanceof InjectionToken) { provider = (eventProvider.ɵprov as FactoryProvider) || eventProvider; } injectorProfiler({ type: InjectorProfilerEventType.ProviderConfigured, context: getInjectorProfilerContext(), providerRecord: {token, provider, isViewProvider}, }); } /** * Emits an event to the injector profiler with the instance that was created. Note that * the injector associated with this emission can be accessed by using getDebugInjectContext() * * @param instance an object created by an injector */ export function emitInstanceCreatedByInjectorEvent(instance: unknown): void { !ngDevMode && throwError('Injector profiler should never be called in production mode'); injectorProfiler({ type: InjectorProfilerEventType.InstanceCreatedByInjector, context: getInjectorProfilerContext(), instance: {value: instance}, }); } /** * @param token DI token associated with injected service * @param value the instance of the injected service (i.e the result of `inject(token)`) * @param flags the flags that the token was injected with */ export function emitInjectEvent(token: Type<unknown>, value: unknown, flags: InjectFlags): void { !ngDevMode && throwError('Injector profiler should never be called in production mode'); injectorProfiler({ type: InjectorProfilerEventType.Inject, context: getInjectorProfilerContext(), service: {token, value, flags}, }); } export function runInInjectorProfilerContext( injector: Injector, token: Type<unknown>, callback: () => void, ): void { !ngDevMode && throwError('runInInjectorProfilerContext should never be called in production mode'); const prevInjectContext = setInjectorProfilerContext({injector, token}); try { callback(); } finally { setInjectorProfilerContext(prevInjectContext); } }
{ "end_byte": 9014, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/debug/injector_profiler.ts" }
angular/packages/core/src/render3/debug/set_debug_info.ts_0_639
/** * @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 {getComponentDef} from '../def_getters'; import {ClassDebugInfo} from '../interfaces/definition'; /** * Sets the debug info for an Angular class. * * This runtime is guarded by ngDevMode flag. */ export function ɵsetClassDebugInfo(type: Type<any>, debugInfo: ClassDebugInfo): void { const def = getComponentDef(type); if (def !== null) { def.debugInfo = debugInfo; } }
{ "end_byte": 639, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/debug/set_debug_info.ts" }
angular/packages/core/src/render3/debug/framework_injector_profiler.ts_0_7764
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injector} from '../../di/injector'; import {EnvironmentInjector} from '../../di/r3_injector'; import {Type} from '../../interface/type'; import {assertDefined, throwError} from '../../util/assert'; import {assertTNode, assertTNodeForLView} from '../assert'; import {getComponentDef} from '../def_getters'; import {getNodeInjectorLView, getNodeInjectorTNode, NodeInjector} from '../di'; import {TNode} from '../interfaces/node'; import {LView} from '../interfaces/view'; import { InjectedService, InjectorCreatedInstance, InjectorProfilerContext, InjectorProfilerEvent, InjectorProfilerEventType, ProviderRecord, setInjectorProfiler, } from './injector_profiler'; /** * These are the data structures that our framework injector profiler will fill with data in order * to support DI debugging APIs. * * resolverToTokenToDependencies: Maps an injector to a Map of tokens to an Array of * dependencies. Injector -> Token -> Dependencies This is used to support the * getDependenciesFromInjectable API, which takes in an injector and a token and returns it's * dependencies. * * resolverToProviders: Maps a DI resolver (an Injector or a TNode) to the providers configured * within it This is used to support the getInjectorProviders API, which takes in an injector and * returns the providers that it was configured with. Note that for the element injector case we * use the TNode instead of the LView as the DI resolver. This is because the registration of * providers happens only once per type of TNode. If an injector is created with an identical TNode, * the providers for that injector will not be reconfigured. * * standaloneInjectorToComponent: Maps the injector of a standalone component to the standalone * component that it is associated with. Used in the getInjectorProviders API, specificially in the * discovery of import paths for each provider. This is necessary because the imports array of a * standalone component is processed and configured in its standalone injector, but exists within * the component's definition. Because getInjectorProviders takes in an injector, if that injector * is the injector of a standalone component, we need to be able to discover the place where the * imports array is located (the component) in order to flatten the imports array within it to * discover all of it's providers. * * * All of these data structures are instantiated with WeakMaps. This will ensure that the presence * of any object in the keys of these maps does not prevent the garbage collector from collecting * those objects. Because of this property of WeakMaps, these data structures will never be the * source of a memory leak. * * An example of this advantage: When components are destroyed, we don't need to do * any additional work to remove that component from our mappings. * */ class DIDebugData { resolverToTokenToDependencies = new WeakMap< Injector | LView, WeakMap<Type<unknown>, InjectedService[]> >(); resolverToProviders = new WeakMap<Injector | TNode, ProviderRecord[]>(); standaloneInjectorToComponent = new WeakMap<Injector, Type<unknown>>(); reset() { this.resolverToTokenToDependencies = new WeakMap< Injector | LView, WeakMap<Type<unknown>, InjectedService[]> >(); this.resolverToProviders = new WeakMap<Injector | TNode, ProviderRecord[]>(); this.standaloneInjectorToComponent = new WeakMap<Injector, Type<unknown>>(); } } let frameworkDIDebugData = new DIDebugData(); export function getFrameworkDIDebugData(): DIDebugData { return frameworkDIDebugData; } /** * Initalize default handling of injector events. This handling parses events * as they are emitted and constructs the data structures necessary to support * some of debug APIs. * * See handleInjectEvent, handleCreateEvent and handleProviderConfiguredEvent * for descriptions of each handler * * Supported APIs: * - getDependenciesFromInjectable * - getInjectorProviders */ export function setupFrameworkInjectorProfiler(): void { frameworkDIDebugData.reset(); setInjectorProfiler((injectorProfilerEvent) => handleInjectorProfilerEvent(injectorProfilerEvent), ); } function handleInjectorProfilerEvent(injectorProfilerEvent: InjectorProfilerEvent): void { const {context, type} = injectorProfilerEvent; if (type === InjectorProfilerEventType.Inject) { handleInjectEvent(context, injectorProfilerEvent.service); } else if (type === InjectorProfilerEventType.InstanceCreatedByInjector) { handleInstanceCreatedByInjectorEvent(context, injectorProfilerEvent.instance); } else if (type === InjectorProfilerEventType.ProviderConfigured) { handleProviderConfiguredEvent(context, injectorProfilerEvent.providerRecord); } } /** * * Stores the injected service in frameworkDIDebugData.resolverToTokenToDependencies * based on it's injector and token. * * @param context InjectorProfilerContext the injection context that this event occurred in. * @param data InjectedService the service associated with this inject event. * */ function handleInjectEvent(context: InjectorProfilerContext, data: InjectedService) { const diResolver = getDIResolver(context.injector); if (diResolver === null) { throwError('An Inject event must be run within an injection context.'); } const diResolverToInstantiatedToken = frameworkDIDebugData.resolverToTokenToDependencies; if (!diResolverToInstantiatedToken.has(diResolver)) { diResolverToInstantiatedToken.set(diResolver, new WeakMap<Type<unknown>, InjectedService[]>()); } // if token is a primitive type, ignore this event. We do this because we cannot keep track of // non-primitive tokens in WeakMaps since they are not garbage collectable. if (!canBeHeldWeakly(context.token)) { return; } const instantiatedTokenToDependencies = diResolverToInstantiatedToken.get(diResolver)!; if (!instantiatedTokenToDependencies.has(context.token!)) { instantiatedTokenToDependencies.set(context.token!, []); } const {token, value, flags} = data; assertDefined(context.token, 'Injector profiler context token is undefined.'); const dependencies = instantiatedTokenToDependencies.get(context.token); assertDefined(dependencies, 'Could not resolve dependencies for token.'); if (context.injector instanceof NodeInjector) { dependencies.push({token, value, flags, injectedIn: getNodeInjectorContext(context.injector)}); } else { dependencies.push({token, value, flags}); } } /** * * Returns the LView and TNode associated with a NodeInjector. Returns undefined if the injector * is not a NodeInjector. * * @param injector * @returns {lView: LView, tNode: TNode}|undefined */ function getNodeInjectorContext(injector: Injector): {lView: LView; tNode: TNode} | undefined { if (!(injector instanceof NodeInjector)) { throwError('getNodeInjectorContext must be called with a NodeInjector'); } const lView = getNodeInjectorLView(injector); const tNode = getNodeInjectorTNode(injector); if (tNode === null) { return; } assertTNodeForLView(tNode, lView); return {lView, tNode}; } /** * * If the created instance is an instance of a standalone component, maps the injector to that * standalone component in frameworkDIDebugData.standaloneInjectorToComponent * * @param context InjectorProfilerContext the injection context that this event occurred in. * @param data InjectorCreatedInstance an object containing the instance that was just created * */
{ "end_byte": 7764, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/debug/framework_injector_profiler.ts" }
angular/packages/core/src/render3/debug/framework_injector_profiler.ts_7765_11949
function handleInstanceCreatedByInjectorEvent( context: InjectorProfilerContext, data: InjectorCreatedInstance, ): void { const {value} = data; if (getDIResolver(context.injector) === null) { throwError('An InjectorCreatedInstance event must be run within an injection context.'); } // if our value is an instance of a standalone component, map the injector of that standalone // component to the component class. Otherwise, this event is a noop. let standaloneComponent: Type<unknown> | undefined | null = undefined; if (typeof value === 'object') { standaloneComponent = value?.constructor as Type<unknown> | undefined | null; } // We want to also cover if `standaloneComponent === null` in addition to `undefined` if (standaloneComponent == undefined || !isStandaloneComponent(standaloneComponent)) { return; } const environmentInjector: EnvironmentInjector | null = context.injector.get( EnvironmentInjector, null, {optional: true}, ); // Standalone components should have an environment injector. If one cannot be // found we may be in a test case for low level functionality that did not explicitly // setup this injector. In those cases, we simply ignore this event. if (environmentInjector === null) { return; } const {standaloneInjectorToComponent} = frameworkDIDebugData; // If our injector has already been mapped, as is the case // when a standalone component imports another standalone component, // we consider the original component (the component doing the importing) // as the component connected to our injector. if (standaloneInjectorToComponent.has(environmentInjector)) { return; } // If our injector hasn't been mapped, then we map it to the standalone component standaloneInjectorToComponent.set(environmentInjector, standaloneComponent); } function isStandaloneComponent(value: Type<unknown>): boolean { const def = getComponentDef(value); return !!def?.standalone; } /** * * Stores the emitted ProviderRecords from the InjectorProfilerEventType.ProviderConfigured * event in frameworkDIDebugData.resolverToProviders * * @param context InjectorProfilerContext the injection context that this event occurred in. * @param data ProviderRecord an object containing the instance that was just created * */ function handleProviderConfiguredEvent( context: InjectorProfilerContext, data: ProviderRecord, ): void { const {resolverToProviders} = frameworkDIDebugData; let diResolver: Injector | TNode; if (context?.injector instanceof NodeInjector) { diResolver = getNodeInjectorTNode(context.injector) as TNode; } else { diResolver = context.injector; } if (diResolver === null) { throwError('A ProviderConfigured event must be run within an injection context.'); } if (!resolverToProviders.has(diResolver)) { resolverToProviders.set(diResolver, []); } resolverToProviders.get(diResolver)!.push(data); } function getDIResolver(injector: Injector | undefined): Injector | LView | null { let diResolver: Injector | LView | null = null; if (injector === undefined) { return diResolver; } // We use the LView as the diResolver for NodeInjectors because they // do not persist anywhere in the framework. They are simply wrappers around an LView and a TNode // that do persist. Because of this, we rely on the LView of the NodeInjector in order to use // as a concrete key to represent this injector. If we get the same LView back later, we know // we're looking at the same injector. if (injector instanceof NodeInjector) { diResolver = getNodeInjectorLView(injector); } // Other injectors can be used a keys for a map because their instances // persist else { diResolver = injector; } return diResolver; } // inspired by // https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#sec-canbeheldweakly function canBeHeldWeakly(value: any): boolean { // we check for value !== null here because typeof null === 'object return ( value !== null && (typeof value === 'object' || typeof value === 'function' || typeof value === 'symbol') ); }
{ "end_byte": 11949, "start_byte": 7765, "url": "https://github.com/angular/angular/blob/main/packages/core/src/render3/debug/framework_injector_profiler.ts" }
angular/packages/core/src/application/create_application.ts_0_3143
/** * @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 {internalProvideZoneChangeDetection} from '../change_detection/scheduling/ng_zone_scheduling'; import {EnvironmentProviders, Provider, StaticProvider} from '../di/interface/provider'; import {EnvironmentInjector} from '../di/r3_injector'; import {Type} from '../interface/type'; import {createOrReusePlatformInjector} from '../platform/platform'; import {assertStandaloneComponentType} from '../render3/errors'; import {EnvironmentNgModuleRefAdapter} from '../render3/ng_module_ref'; import {NgZone} from '../zone/ng_zone'; import {_callAndReportToErrorHandler, ApplicationRef} from './application_ref'; import {ChangeDetectionScheduler} from '../change_detection/scheduling/zoneless_scheduling'; import {ChangeDetectionSchedulerImpl} from '../change_detection/scheduling/zoneless_scheduling_impl'; import {bootstrap} from '../platform/bootstrap'; /** * Internal create application API that implements the core application creation logic and optional * bootstrap logic. * * Platforms (such as `platform-browser`) may require different set of application and platform * providers for an application to function correctly. As a result, platforms may use this function * internally and supply the necessary providers during the bootstrap, while exposing * platform-specific APIs as a part of their public API. * * @returns A promise that returns an `ApplicationRef` instance once resolved. */ export function internalCreateApplication(config: { rootComponent?: Type<unknown>; appProviders?: Array<Provider | EnvironmentProviders>; platformProviders?: Provider[]; }): Promise<ApplicationRef> { try { const {rootComponent, appProviders, platformProviders} = config; if ((typeof ngDevMode === 'undefined' || ngDevMode) && rootComponent !== undefined) { assertStandaloneComponentType(rootComponent); } const platformInjector = createOrReusePlatformInjector(platformProviders as StaticProvider[]); // Create root application injector based on a set of providers configured at the platform // bootstrap level as well as providers passed to the bootstrap call by a user. const allAppProviders = [ internalProvideZoneChangeDetection({}), {provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl}, ...(appProviders || []), ]; const adapter = new EnvironmentNgModuleRefAdapter({ providers: allAppProviders, parent: platformInjector as EnvironmentInjector, debugName: typeof ngDevMode === 'undefined' || ngDevMode ? 'Environment Injector' : '', // We skip environment initializers because we need to run them inside the NgZone, which // happens after we get the NgZone instance from the Injector. runEnvironmentInitializers: false, }); return bootstrap({ r3Injector: adapter.injector, platformInjector, rootComponent, }); } catch (e) { return Promise.reject(e); } }
{ "end_byte": 3143, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/create_application.ts" }
angular/packages/core/src/application/application_ref.ts_0_7132
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import '../util/ng_jit_mode'; import { setActiveConsumer, setThrowInvalidWriteToSignalError, } from '@angular/core/primitives/signals'; import {Observable, Subject, Subscription} from 'rxjs'; import {first, map} from 'rxjs/operators'; import {ZONELESS_ENABLED} from '../change_detection/scheduling/zoneless_scheduling'; import {Console} from '../console'; import {inject} from '../di'; import {Injectable} from '../di/injectable'; import {InjectionToken} from '../di/injection_token'; import {Injector} from '../di/injector'; import {EnvironmentInjector, type R3Injector} from '../di/r3_injector'; import {ErrorHandler, INTERNAL_APPLICATION_ERROR_HANDLER} from '../error_handler'; import {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../errors'; import {Type} from '../interface/type'; import {ComponentFactory, ComponentRef} from '../linker/component_factory'; import {ComponentFactoryResolver} from '../linker/component_factory_resolver'; import {NgModuleRef} from '../linker/ng_module_factory'; import {ViewRef} from '../linker/view_ref'; import {PendingTasksInternal} from '../pending_tasks'; import {RendererFactory2} from '../render/api'; import {AfterRenderManager} from '../render3/after_render/manager'; import {ComponentFactory as R3ComponentFactory} from '../render3/component_ref'; import {isStandalone} from '../render3/def_getters'; import {ChangeDetectionMode, detectChangesInternal} from '../render3/instructions/change_detection'; import {LView} from '../render3/interfaces/view'; import {publishDefaultGlobalUtils as _publishDefaultGlobalUtils} from '../render3/util/global_utils'; import {requiresRefreshOrTraversal} from '../render3/util/view_utils'; import {ViewRef as InternalViewRef} from '../render3/view_ref'; import {TESTABILITY} from '../testability/testability'; import {isPromise} from '../util/lang'; import {NgZone} from '../zone/ng_zone'; import {ApplicationInitStatus} from './application_init'; import {EffectScheduler} from '../render3/reactivity/root_effect_scheduler'; /** * A DI token that provides a set of callbacks to * be called for every component that is bootstrapped. * * Each callback must take a `ComponentRef` instance and return nothing. * * `(componentRef: ComponentRef) => void` * * @publicApi */ export const APP_BOOTSTRAP_LISTENER = new InjectionToken< ReadonlyArray<(compRef: ComponentRef<any>) => void> >(ngDevMode ? 'appBootstrapListener' : ''); export function publishDefaultGlobalUtils() { ngDevMode && _publishDefaultGlobalUtils(); } /** * Sets the error for an invalid write to a signal to be an Angular `RuntimeError`. */ export function publishSignalConfiguration(): void { setThrowInvalidWriteToSignalError(() => { throw new RuntimeError( RuntimeErrorCode.SIGNAL_WRITE_FROM_ILLEGAL_CONTEXT, ngDevMode && 'Writing to signals is not allowed in a `computed`.', ); }); } export function isBoundToModule<C>(cf: ComponentFactory<C>): boolean { return (cf as R3ComponentFactory<C>).isBoundToModule; } /** * A token for third-party components that can register themselves with NgProbe. * * @deprecated * @publicApi */ export class NgProbeToken { constructor( public name: string, public token: any, ) {} } /** * Provides additional options to the bootstrapping process. * * @publicApi */ export interface BootstrapOptions { /** * Optionally specify which `NgZone` should be used when not configured in the providers. * * - Provide your own `NgZone` instance. * - `zone.js` - Use default `NgZone` which requires `Zone.js`. * - `noop` - Use `NoopNgZone` which does nothing. */ ngZone?: NgZone | 'zone.js' | 'noop'; /** * Optionally specify coalescing event change detections or not. * Consider the following case. * * ``` * <div (click)="doSomething()"> * <button (click)="doSomethingElse()"></button> * </div> * ``` * * When button is clicked, because of the event bubbling, both * event handlers will be called and 2 change detections will be * triggered. We can coalesce such kind of events to only trigger * change detection only once. * * By default, this option will be false. So the events will not be * coalesced and the change detection will be triggered multiple times. * And if this option be set to true, the change detection will be * triggered async by scheduling a animation frame. So in the case above, * the change detection will only be triggered once. */ ngZoneEventCoalescing?: boolean; /** * Optionally specify if `NgZone#run()` method invocations should be coalesced * into a single change detection. * * Consider the following case. * ``` * for (let i = 0; i < 10; i ++) { * ngZone.run(() => { * // do something * }); * } * ``` * * This case triggers the change detection multiple times. * With ngZoneRunCoalescing options, all change detections in an event loop trigger only once. * In addition, the change detection executes in requestAnimation. * */ ngZoneRunCoalescing?: boolean; /** * When false, change detection is scheduled when Angular receives * a clear indication that templates need to be refreshed. This includes: * * - calling `ChangeDetectorRef.markForCheck` * - calling `ComponentRef.setInput` * - updating a signal that is read in a template * - attaching a view that is marked dirty * - removing a view * - registering a render hook (templates are only refreshed if render hooks do one of the above) * * @deprecated This option was introduced out of caution as a way for developers to opt out of the * new behavior in v18 which schedule change detection for the above events when they occur * outside the Zone. After monitoring the results post-release, we have determined that this * feature is working as desired and do not believe it should ever be disabled by setting * this option to `true`. */ ignoreChangesOutsideZone?: boolean; } /** Maximum number of times ApplicationRef will refresh all attached views in a single tick. */ const MAXIMUM_REFRESH_RERUNS = 10; export function _callAndReportToErrorHandler( errorHandler: ErrorHandler, ngZone: NgZone, callback: () => any, ): any { try { const result = callback(); if (isPromise(result)) { return result.catch((e: any) => { ngZone.runOutsideAngular(() => errorHandler.handleError(e)); // rethrow as the exception handler might not do it throw e; }); } return result; } catch (e) { ngZone.runOutsideAngular(() => errorHandler.handleError(e)); // rethrow as the exception handler might not do it throw e; } } export function optionsReducer<T extends Object>(dst: T, objs: T | T[]): T { if (Array.isArray(objs)) { return objs.reduce(optionsReducer, dst); } return {...dst, ...objs}; }
{ "end_byte": 7132, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ref.ts" }
angular/packages/core/src/application/application_ref.ts_7134_10112
/** * A reference to an Angular application running on a page. * * @usageNotes * {@a is-stable-examples} * ### isStable examples and caveats * * Note two important points about `isStable`, demonstrated in the examples below: * - the application will never be stable if you start any kind * of recurrent asynchronous task when the application starts * (for example for a polling process, started with a `setInterval`, a `setTimeout` * or using RxJS operators like `interval`); * - the `isStable` Observable runs outside of the Angular zone. * * Let's imagine that you start a recurrent task * (here incrementing a counter, using RxJS `interval`), * and at the same time subscribe to `isStable`. * * ``` * constructor(appRef: ApplicationRef) { * appRef.isStable.pipe( * filter(stable => stable) * ).subscribe(() => console.log('App is stable now'); * interval(1000).subscribe(counter => console.log(counter)); * } * ``` * In this example, `isStable` will never emit `true`, * and the trace "App is stable now" will never get logged. * * If you want to execute something when the app is stable, * you have to wait for the application to be stable * before starting your polling process. * * ``` * constructor(appRef: ApplicationRef) { * appRef.isStable.pipe( * first(stable => stable), * tap(stable => console.log('App is stable now')), * switchMap(() => interval(1000)) * ).subscribe(counter => console.log(counter)); * } * ``` * In this example, the trace "App is stable now" will be logged * and then the counter starts incrementing every second. * * Note also that this Observable runs outside of the Angular zone, * which means that the code in the subscription * to this Observable will not trigger the change detection. * * Let's imagine that instead of logging the counter value, * you update a field of your component * and display it in its template. * * ``` * constructor(appRef: ApplicationRef) { * appRef.isStable.pipe( * first(stable => stable), * switchMap(() => interval(1000)) * ).subscribe(counter => this.value = counter); * } * ``` * As the `isStable` Observable runs outside the zone, * the `value` field will be updated properly, * but the template will not be refreshed! * * You'll have to manually trigger the change detection to update the template. * * ``` * constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) { * appRef.isStable.pipe( * first(stable => stable), * switchMap(() => interval(1000)) * ).subscribe(counter => { * this.value = counter; * cd.detectChanges(); * }); * } * ``` * * Or make the subscription callback run inside the zone. * * ``` * constructor(appRef: ApplicationRef, zone: NgZone) { * appRef.isStable.pipe( * first(stable => stable), * switchMap(() => interval(1000)) * ).subscribe(counter => zone.run(() => this.value = counter)); * } * ``` * * @publicApi */
{ "end_byte": 10112, "start_byte": 7134, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ref.ts" }
angular/packages/core/src/application/application_ref.ts_10113_17956
@Injectable({providedIn: 'root'}) export class ApplicationRef { /** @internal */ private _bootstrapListeners: ((compRef: ComponentRef<any>) => void)[] = []; /** @internal */ _runningTick: boolean = false; private _destroyed = false; private _destroyListeners: Array<() => void> = []; /** @internal */ _views: InternalViewRef<unknown>[] = []; private readonly internalErrorHandler = inject(INTERNAL_APPLICATION_ERROR_HANDLER); private readonly afterRenderManager = inject(AfterRenderManager); private readonly zonelessEnabled = inject(ZONELESS_ENABLED); private readonly rootEffectScheduler = inject(EffectScheduler); /** * Current dirty state of the application across a number of dimensions (views, afterRender hooks, * etc). * * A flag set here means that `tick()` will attempt to resolve the dirtiness when executed. * * @internal */ dirtyFlags = ApplicationRefDirtyFlags.None; /** * Like `dirtyFlags` but don't cause `tick()` to loop. * * @internal */ deferredDirtyFlags = ApplicationRefDirtyFlags.None; // Needed for ComponentFixture temporarily during migration of autoDetect behavior // Eventually the hostView of the fixture should just attach to ApplicationRef. private externalTestViews: Set<InternalViewRef<unknown>> = new Set(); /** @internal */ afterTick = new Subject<void>(); /** @internal */ get allViews(): Array<InternalViewRef<unknown>> { return [...this.externalTestViews.keys(), ...this._views]; } /** * Indicates whether this instance was destroyed. */ get destroyed() { return this._destroyed; } /** * Get a list of component types registered to this application. * This list is populated even before the component is created. */ public readonly componentTypes: Type<any>[] = []; /** * Get a list of components registered to this application. */ public readonly components: ComponentRef<any>[] = []; /** * Returns an Observable that indicates when the application is stable or unstable. */ public readonly isStable: Observable<boolean> = inject(PendingTasksInternal).hasPendingTasks.pipe( map((pending) => !pending), ); /** * @returns A promise that resolves when the application becomes stable */ whenStable(): Promise<void> { let subscription: Subscription; return new Promise<void>((resolve) => { subscription = this.isStable.subscribe({ next: (stable) => { if (stable) { resolve(); } }, }); }).finally(() => { subscription.unsubscribe(); }); } private readonly _injector = inject(EnvironmentInjector); /** * The `EnvironmentInjector` used to create this application. */ get injector(): EnvironmentInjector { return this._injector; } /** * Bootstrap a component onto the element identified by its selector or, optionally, to a * specified element. * * @usageNotes * ### Bootstrap process * * When bootstrapping a component, Angular mounts it onto a target DOM element * and kicks off automatic change detection. The target DOM element can be * provided using the `rootSelectorOrNode` argument. * * If the target DOM element is not provided, Angular tries to find one on a page * using the `selector` of the component that is being bootstrapped * (first matched element is used). * * ### Example * * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`, * but it requires us to know the component while writing the application code. * * Imagine a situation where we have to wait for an API call to decide about the component to * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to * dynamically bootstrap a component. * * {@example core/ts/platform/platform.ts region='componentSelector'} * * Optionally, a component can be mounted onto a DOM element that does not match the * selector of the bootstrapped component. * * In the following example, we are providing a CSS selector to match the target element. * * {@example core/ts/platform/platform.ts region='cssSelector'} * * While in this example, we are providing reference to a DOM node. * * {@example core/ts/platform/platform.ts region='domNode'} */ bootstrap<C>(component: Type<C>, rootSelectorOrNode?: string | any): ComponentRef<C>; /** * Bootstrap a component onto the element identified by its selector or, optionally, to a * specified element. * * @usageNotes * ### Bootstrap process * * When bootstrapping a component, Angular mounts it onto a target DOM element * and kicks off automatic change detection. The target DOM element can be * provided using the `rootSelectorOrNode` argument. * * If the target DOM element is not provided, Angular tries to find one on a page * using the `selector` of the component that is being bootstrapped * (first matched element is used). * * ### Example * * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`, * but it requires us to know the component while writing the application code. * * Imagine a situation where we have to wait for an API call to decide about the component to * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to * dynamically bootstrap a component. * * {@example core/ts/platform/platform.ts region='componentSelector'} * * Optionally, a component can be mounted onto a DOM element that does not match the * selector of the bootstrapped component. * * In the following example, we are providing a CSS selector to match the target element. * * {@example core/ts/platform/platform.ts region='cssSelector'} * * While in this example, we are providing reference to a DOM node. * * {@example core/ts/platform/platform.ts region='domNode'} * * @deprecated Passing Component factories as the `Application.bootstrap` function argument is * deprecated. Pass Component Types instead. */ bootstrap<C>( componentFactory: ComponentFactory<C>, rootSelectorOrNode?: string | any, ): ComponentRef<C>; /** * Bootstrap a component onto the element identified by its selector or, optionally, to a * specified element. * * @usageNotes * ### Bootstrap process * * When bootstrapping a component, Angular mounts it onto a target DOM element * and kicks off automatic change detection. The target DOM element can be * provided using the `rootSelectorOrNode` argument. * * If the target DOM element is not provided, Angular tries to find one on a page * using the `selector` of the component that is being bootstrapped * (first matched element is used). * * ### Example * * Generally, we define the component to bootstrap in the `bootstrap` array of `NgModule`, * but it requires us to know the component while writing the application code. * * Imagine a situation where we have to wait for an API call to decide about the component to * bootstrap. We can use the `ngDoBootstrap` hook of the `NgModule` and call this method to * dynamically bootstrap a component. * * {@example core/ts/platform/platform.ts region='componentSelector'} * * Optionally, a component can be mounted onto a DOM element that does not match the * selector of the bootstrapped component. * * In the following example, we are providing a CSS selector to match the target element. * * {@example core/ts/platform/platform.ts region='cssSelector'} * * While in this example, we are providing reference to a DOM node. * * {@example core/ts/platform/platform.ts region='domNode'} */
{ "end_byte": 17956, "start_byte": 10113, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ref.ts" }
angular/packages/core/src/application/application_ref.ts_17959_26580
bootstrap<C>( componentOrFactory: ComponentFactory<C> | Type<C>, rootSelectorOrNode?: string | any, ): ComponentRef<C> { (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed(); const isComponentFactory = componentOrFactory instanceof ComponentFactory; const initStatus = this._injector.get(ApplicationInitStatus); if (!initStatus.done) { const standalone = !isComponentFactory && isStandalone(componentOrFactory); const errorMessage = (typeof ngDevMode === 'undefined' || ngDevMode) && 'Cannot bootstrap as there are still asynchronous initializers running.' + (standalone ? '' : ' Bootstrap components in the `ngDoBootstrap` method of the root module.'); throw new RuntimeError(RuntimeErrorCode.ASYNC_INITIALIZERS_STILL_RUNNING, errorMessage); } let componentFactory: ComponentFactory<C>; if (isComponentFactory) { componentFactory = componentOrFactory; } else { const resolver = this._injector.get(ComponentFactoryResolver); componentFactory = resolver.resolveComponentFactory(componentOrFactory)!; } this.componentTypes.push(componentFactory.componentType); // Create a factory associated with the current module if it's not bound to some other const ngModule = isBoundToModule(componentFactory) ? undefined : this._injector.get(NgModuleRef); const selectorOrNode = rootSelectorOrNode || componentFactory.selector; const compRef = componentFactory.create(Injector.NULL, [], selectorOrNode, ngModule); const nativeElement = compRef.location.nativeElement; const testability = compRef.injector.get(TESTABILITY, null); testability?.registerApplication(nativeElement); compRef.onDestroy(() => { this.detachView(compRef.hostView); remove(this.components, compRef); testability?.unregisterApplication(nativeElement); }); this._loadComponent(compRef); if (typeof ngDevMode === 'undefined' || ngDevMode) { const _console = this._injector.get(Console); _console.log(`Angular is running in development mode.`); } return compRef; } /** * Invoke this method to explicitly process change detection and its side-effects. * * In development mode, `tick()` also performs a second change detection cycle to ensure that no * further changes are detected. If additional changes are picked up during this second cycle, * bindings in the app have side-effects that cannot be resolved in a single change detection * pass. * In this case, Angular throws an error, since an Angular application can only have one change * detection pass during which all change detection must complete. */ tick(): void { if (!this.zonelessEnabled) { this.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeGlobal; } this._tick(); } /** @internal */ _tick(): void { (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed(); if (this._runningTick) { throw new RuntimeError( RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK, ngDevMode && 'ApplicationRef.tick is called recursively', ); } const prevConsumer = setActiveConsumer(null); try { this._runningTick = true; this.synchronize(); if (typeof ngDevMode === 'undefined' || ngDevMode) { for (let view of this.allViews) { view.checkNoChanges(); } } } catch (e) { // Attention: Don't rethrow as it could cancel subscriptions to Observables! this.internalErrorHandler(e); } finally { this._runningTick = false; setActiveConsumer(prevConsumer); this.afterTick.next(); } } /** * Performs the core work of synchronizing the application state with the UI, resolving any * pending dirtiness (potentially in a loop). */ private synchronize(): void { let rendererFactory: RendererFactory2 | null = null; if (!(this._injector as R3Injector).destroyed) { rendererFactory = this._injector.get(RendererFactory2, null, {optional: true}); } // When beginning synchronization, all deferred dirtiness becomes active dirtiness. this.dirtyFlags |= this.deferredDirtyFlags; this.deferredDirtyFlags = ApplicationRefDirtyFlags.None; let runs = 0; while (this.dirtyFlags !== ApplicationRefDirtyFlags.None && runs++ < MAXIMUM_REFRESH_RERUNS) { this.synchronizeOnce(rendererFactory); } if ((typeof ngDevMode === 'undefined' || ngDevMode) && runs >= MAXIMUM_REFRESH_RERUNS) { throw new RuntimeError( RuntimeErrorCode.INFINITE_CHANGE_DETECTION, ngDevMode && 'Infinite change detection while refreshing application views. ' + 'Ensure views are not calling `markForCheck` on every template execution or ' + 'that afterRender hooks always mark views for check.', ); } } /** * Perform a single synchronization pass. */ private synchronizeOnce(rendererFactory: RendererFactory2 | null): void { // If we happened to loop, deferred dirtiness can be processed as active dirtiness again. this.dirtyFlags |= this.deferredDirtyFlags; this.deferredDirtyFlags = ApplicationRefDirtyFlags.None; // First, process any dirty root effects. if (this.dirtyFlags & ApplicationRefDirtyFlags.RootEffects) { this.dirtyFlags &= ~ApplicationRefDirtyFlags.RootEffects; this.rootEffectScheduler.flush(); } // First check dirty views, if there are any. if (this.dirtyFlags & ApplicationRefDirtyFlags.ViewTreeAny) { // Change detection on views starts in targeted mode (only check components if they're // marked as dirty) unless global checking is specifically requested via APIs like // `ApplicationRef.tick()` and the `NgZone` integration. const useGlobalCheck = Boolean(this.dirtyFlags & ApplicationRefDirtyFlags.ViewTreeGlobal); // Clear the view-related dirty flags. this.dirtyFlags &= ~ApplicationRefDirtyFlags.ViewTreeAny; // Set the AfterRender bit, as we're checking views and will need to run afterRender hooks. this.dirtyFlags |= ApplicationRefDirtyFlags.AfterRender; // Check all potentially dirty views. for (let {_lView, notifyErrorHandler} of this.allViews) { detectChangesInViewIfRequired( _lView, notifyErrorHandler, useGlobalCheck, this.zonelessEnabled, ); } // If `markForCheck()` was called during view checking, it will have set the `ViewTreeCheck` // flag. We clear the flag here because, for backwards compatibility, `markForCheck()` // during view checking doesn't cause the view to be re-checked. this.dirtyFlags &= ~ApplicationRefDirtyFlags.ViewTreeCheck; // Check if any views are still dirty after checking and we need to loop back. this.syncDirtyFlagsWithViews(); if ( this.dirtyFlags & (ApplicationRefDirtyFlags.ViewTreeAny | ApplicationRefDirtyFlags.RootEffects) ) { // If any views or effects are still dirty after checking, loop back before running render // hooks. return; } } else { // If we skipped refreshing views above, there might still be unflushed animations // because we never called `detectChangesInternal` on the views. rendererFactory?.begin?.(); rendererFactory?.end?.(); } // Even if there were no dirty views, afterRender hooks might still be dirty. if (this.dirtyFlags & ApplicationRefDirtyFlags.AfterRender) { this.dirtyFlags &= ~ApplicationRefDirtyFlags.AfterRender; this.afterRenderManager.execute(); // afterRender hooks might influence dirty flags. } this.syncDirtyFlagsWithViews(); } /** * Checks `allViews` for views which require refresh/traversal, and updates `dirtyFlags` * accordingly, with two potential behaviors: * * 1. If any of our views require updating, then this adds the `ViewTreeTraversal` dirty flag. * This _should_ be a no-op, since the scheduler should've added the flag at the same time the * view was marked as needing updating. * * TODO(alxhub): figure out if this behavior is still needed for edge cases. * * 2. If none of our views require updating, then clear the view-related `dirtyFlag`s. This * happens when the scheduler is notified of a view becoming dirty, but the view itself isn't * reachable through traversal from our roots (e.g. it's detached from the CD tree). */
{ "end_byte": 26580, "start_byte": 17959, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ref.ts" }
angular/packages/core/src/application/application_ref.ts_26583_33294
private syncDirtyFlagsWithViews(): void { if (this.allViews.some(({_lView}) => requiresRefreshOrTraversal(_lView))) { // If after running all afterRender callbacks new views are dirty, ensure we loop back. this.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal; return; } else { // Even though this flag may be set, none of _our_ views require traversal, and so the // `ApplicationRef` doesn't require any repeated checking. this.dirtyFlags &= ~ApplicationRefDirtyFlags.ViewTreeAny; } } /** * Attaches a view so that it will be dirty checked. * The view will be automatically detached when it is destroyed. * This will throw if the view is already attached to a ViewContainer. */ attachView(viewRef: ViewRef): void { (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed(); const view = viewRef as InternalViewRef<unknown>; this._views.push(view); view.attachToAppRef(this); } /** * Detaches a view from dirty checking again. */ detachView(viewRef: ViewRef): void { (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed(); const view = viewRef as InternalViewRef<unknown>; remove(this._views, view); view.detachFromAppRef(); } private _loadComponent(componentRef: ComponentRef<any>): void { this.attachView(componentRef.hostView); this.tick(); this.components.push(componentRef); // Get the listeners lazily to prevent DI cycles. const listeners = this._injector.get(APP_BOOTSTRAP_LISTENER, []); if (ngDevMode && !Array.isArray(listeners)) { throw new RuntimeError( RuntimeErrorCode.INVALID_MULTI_PROVIDER, 'Unexpected type of the `APP_BOOTSTRAP_LISTENER` token value ' + `(expected an array, but got ${typeof listeners}). ` + 'Please check that the `APP_BOOTSTRAP_LISTENER` token is configured as a ' + '`multi: true` provider.', ); } [...this._bootstrapListeners, ...listeners].forEach((listener) => listener(componentRef)); } /** @internal */ ngOnDestroy() { if (this._destroyed) return; try { // Call all the lifecycle hooks. this._destroyListeners.forEach((listener) => listener()); // Destroy all registered views. this._views.slice().forEach((view) => view.destroy()); } finally { // Indicate that this instance is destroyed. this._destroyed = true; // Release all references. this._views = []; this._bootstrapListeners = []; this._destroyListeners = []; } } /** * Registers a listener to be called when an instance is destroyed. * * @param callback A callback function to add as a listener. * @returns A function which unregisters a listener. */ onDestroy(callback: () => void): VoidFunction { (typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed(); this._destroyListeners.push(callback); return () => remove(this._destroyListeners, callback); } /** * Destroys an Angular application represented by this `ApplicationRef`. Calling this function * will destroy the associated environment injectors as well as all the bootstrapped components * with their views. */ destroy(): void { if (this._destroyed) { throw new RuntimeError( RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED, ngDevMode && 'This instance of the `ApplicationRef` has already been destroyed.', ); } const injector = this._injector as R3Injector; // Check that this injector instance supports destroy operation. if (injector.destroy && !injector.destroyed) { // Destroying an underlying injector will trigger the `ngOnDestroy` lifecycle // hook, which invokes the remaining cleanup actions. injector.destroy(); } } /** * Returns the number of attached views. */ get viewCount() { return this._views.length; } private warnIfDestroyed() { if ((typeof ngDevMode === 'undefined' || ngDevMode) && this._destroyed) { console.warn( formatRuntimeError( RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED, 'This instance of the `ApplicationRef` has already been destroyed.', ), ); } } } export function remove<T>(list: T[], el: T): void { const index = list.indexOf(el); if (index > -1) { list.splice(index, 1); } } export const enum ApplicationRefDirtyFlags { None = 0, /** * A global change detection round has been requested. */ ViewTreeGlobal = 0b00000001, /** * Part of the view tree is marked for traversal. */ ViewTreeTraversal = 0b00000010, /** * Part of the view tree is marked to be checked (dirty). */ ViewTreeCheck = 0b00000100, /** * Helper for any view tree bit being set. */ ViewTreeAny = ViewTreeGlobal | ViewTreeTraversal | ViewTreeCheck, /** * After render hooks need to run. */ AfterRender = 0b00001000, /** * Effects at the `ApplicationRef` level. */ RootEffects = 0b00010000, } let whenStableStore: WeakMap<ApplicationRef, Promise<void>> | undefined; /** * Returns a Promise that resolves when the application becomes stable after this method is called * the first time. */ export function whenStable(applicationRef: ApplicationRef): Promise<void> { whenStableStore ??= new WeakMap(); const cachedWhenStable = whenStableStore.get(applicationRef); if (cachedWhenStable) { return cachedWhenStable; } const whenStablePromise = applicationRef.isStable .pipe(first((isStable) => isStable)) .toPromise() .then(() => void 0); whenStableStore.set(applicationRef, whenStablePromise); // Be a good citizen and clean the store `onDestroy` even though we are using `WeakMap`. applicationRef.onDestroy(() => whenStableStore?.delete(applicationRef)); return whenStablePromise; } export function detectChangesInViewIfRequired( lView: LView, notifyErrorHandler: boolean, isFirstPass: boolean, zonelessEnabled: boolean, ) { // When re-checking, only check views which actually need it. if (!isFirstPass && !requiresRefreshOrTraversal(lView)) { return; } const mode = isFirstPass && !zonelessEnabled ? // The first pass is always in Global mode, which includes `CheckAlways` views. // When using zoneless, all root views must be explicitly marked for refresh, even if they are // `CheckAlways`. ChangeDetectionMode.Global : // Only refresh views with the `RefreshView` flag or views is a changed signal ChangeDetectionMode.Targeted; detectChangesInternal(lView, notifyErrorHandler, mode); }
{ "end_byte": 33294, "start_byte": 26583, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ref.ts" }
angular/packages/core/src/application/application_tokens.ts_0_6333
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken} from '../di/injection_token'; import {getDocument} from '../render3/interfaces/document'; /** * A DI token representing a string ID, used * primarily for prefixing application attributes and CSS styles when * {@link ViewEncapsulation#Emulated} is being used. * * The token is needed in cases when multiple applications are bootstrapped on a page * (for example, using `bootstrapApplication` calls). In this case, ensure that those applications * have different `APP_ID` value setup. For example: * * ``` * bootstrapApplication(ComponentA, { * providers: [ * { provide: APP_ID, useValue: 'app-a' }, * // ... other providers ... * ] * }); * * bootstrapApplication(ComponentB, { * providers: [ * { provide: APP_ID, useValue: 'app-b' }, * // ... other providers ... * ] * }); * ``` * * By default, when there is only one application bootstrapped, you don't need to provide the * `APP_ID` token (the `ng` will be used as an app ID). * * @publicApi */ export const APP_ID = new InjectionToken<string>(ngDevMode ? 'AppId' : '', { providedIn: 'root', factory: () => DEFAULT_APP_ID, }); /** Default value of the `APP_ID` token. */ const DEFAULT_APP_ID = 'ng'; /** * A function that is executed when a platform is initialized. * * @deprecated from v19.0.0, use providePlatformInitializer instead * * @see {@link providePlatformInitializer} * * @publicApi */ export const PLATFORM_INITIALIZER = new InjectionToken<ReadonlyArray<() => void>>( ngDevMode ? 'Platform Initializer' : '', ); /** * A token that indicates an opaque platform ID. * @publicApi */ export const PLATFORM_ID = new InjectionToken<Object>(ngDevMode ? 'Platform ID' : '', { providedIn: 'platform', factory: () => 'unknown', // set a default platform name, when none set explicitly }); /** * A DI token that indicates the root directory of * the application * @publicApi * @deprecated */ export const PACKAGE_ROOT_URL = new InjectionToken<string>( ngDevMode ? 'Application Packages Root URL' : '', ); // We keep this token here, rather than the animations package, so that modules that only care // about which animations module is loaded (e.g. the CDK) can retrieve it without having to // include extra dependencies. See #44970 for more context. /** * A [DI token](api/core/InjectionToken) that indicates which animations * module has been loaded. * @publicApi */ export const ANIMATION_MODULE_TYPE = new InjectionToken<'NoopAnimations' | 'BrowserAnimations'>( ngDevMode ? 'AnimationModuleType' : '', ); // TODO(crisbeto): link to CSP guide here. /** * Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that * Angular will apply when inserting inline styles. If not provided, Angular will look up its value * from the `ngCspNonce` attribute of the application root node. * * @publicApi */ export const CSP_NONCE = new InjectionToken<string | null>(ngDevMode ? 'CSP nonce' : '', { providedIn: 'root', factory: () => { // Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on // the root node, but because the token value is used in renderers, it has to be available // *very* early in the bootstrapping process. This should be a fairly shallow search, because // the app won't have been added to the DOM yet. Some approaches that were considered: // 1. Find the root node through `ApplicationRef.components[i].location` - normally this would // be enough for our purposes, but the token is injected very early so the `components` array // isn't populated yet. // 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to // creating the `LView`. This means that no `LView` will have been entered when this factory is // invoked for the root component. // 3. Have the token factory return `() => string` which is invoked when a nonce is requested - // the slightly later execution does allow us to get an `LView` reference, but the fact that // it is a function means that it could be executed at *any* time (including immediately) which // may lead to weird bugs. // 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the // hood - has the same problem as #1 and #2 in that the renderer is used to query for the root // node and the nonce value needs to be available when the renderer is created. return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null; }, }); /** * A configuration object for the image-related options. Contains: * - breakpoints: An array of integer breakpoints used to generate * srcsets for responsive images. * - disableImageSizeWarning: A boolean value. Setting this to true will * disable console warnings about oversized images. * - disableImageLazyLoadWarning: A boolean value. Setting this to true will * disable console warnings about LCP images configured with `loading="lazy"`. * Learn more about the responsive image configuration in [the NgOptimizedImage * guide](guide/image-optimization). * Learn more about image warning options in [the related error page](errors/NG0913). * @publicApi */ export type ImageConfig = { breakpoints?: number[]; placeholderResolution?: number; disableImageSizeWarning?: boolean; disableImageLazyLoadWarning?: boolean; }; export const IMAGE_CONFIG_DEFAULTS: ImageConfig = { breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840], placeholderResolution: 30, disableImageSizeWarning: false, disableImageLazyLoadWarning: false, }; /** * Injection token that configures the image optimized image functionality. * See {@link ImageConfig} for additional information about parameters that * can be used. * * @see {@link NgOptimizedImage} * @see {@link ImageConfig} * @publicApi */ export const IMAGE_CONFIG = new InjectionToken<ImageConfig>(ngDevMode ? 'ImageConfig' : '', { providedIn: 'root', factory: () => IMAGE_CONFIG_DEFAULTS, });
{ "end_byte": 6333, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_tokens.ts" }
angular/packages/core/src/application/application_init.ts_0_7747
/** * @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 {Observable} from 'rxjs'; import { EnvironmentProviders, inject, Injectable, InjectionToken, Injector, makeEnvironmentProviders, runInInjectionContext, } from '../di'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import {isPromise, isSubscribable} from '../util/lang'; /** * A DI token that you can use to provide * one or more initialization functions. * * The provided functions are injected at application startup and executed during * app initialization. If any of these functions returns a Promise or an Observable, initialization * does not complete until the Promise is resolved or the Observable is completed. * * You can, for example, create a factory function that loads language data * or an external configuration, and provide that function to the `APP_INITIALIZER` token. * The function is executed during the application bootstrap process, * and the needed data is available on startup. * * Note that the provided initializer is run in the injection context. * * @deprecated from v19.0.0, use provideAppInitializer instead * * @see {@link ApplicationInitStatus} * @see {@link provideAppInitializer} * * @usageNotes * * The following example illustrates how to configure a multi-provider using `APP_INITIALIZER` token * and a function returning a promise. * ### Example with NgModule-based application * ``` * function initializeApp(): Promise<any> { * const http = inject(HttpClient); * return firstValueFrom( * http * .get("https://someUrl.com/api/user") * .pipe(tap(user => { ... })) * ); * } * * @NgModule({ * imports: [BrowserModule], * declarations: [AppComponent], * bootstrap: [AppComponent], * providers: [{ * provide: APP_INITIALIZER, * useValue: initializeApp, * multi: true, * }] * }) * export class AppModule {} * ``` * * ### Example with standalone application * ``` * function initializeApp() { * const http = inject(HttpClient); * return firstValueFrom( * http * .get("https://someUrl.com/api/user") * .pipe(tap(user => { ... })) * ); * } * * bootstrapApplication(App, { * providers: [ * provideHttpClient(), * { * provide: APP_INITIALIZER, * useValue: initializeApp, * multi: true, * }, * ], * }); * ``` * * * It's also possible to configure a multi-provider using `APP_INITIALIZER` token and a function * returning an observable, see an example below. Note: the `HttpClient` in this example is used for * demo purposes to illustrate how the factory function can work with other providers available * through DI. * * ### Example with NgModule-based application * ``` * function initializeApp() { * const http = inject(HttpClient); * return firstValueFrom( * http * .get("https://someUrl.com/api/user") * .pipe(tap(user => { ... })) * ); * } * * @NgModule({ * imports: [BrowserModule, HttpClientModule], * declarations: [AppComponent], * bootstrap: [AppComponent], * providers: [{ * provide: APP_INITIALIZER, * useValue: initializeApp, * multi: true, * }] * }) * export class AppModule {} * ``` * * ### Example with standalone application * ``` * function initializeApp() { * const http = inject(HttpClient); * return firstValueFrom( * http * .get("https://someUrl.com/api/user") * .pipe(tap(user => { ... })) * ); * } * * bootstrapApplication(App, { * providers: [ * provideHttpClient(), * { * provide: APP_INITIALIZER, * useValue: initializeApp, * multi: true, * }, * ], * }); * ``` * * @publicApi */ export const APP_INITIALIZER = new InjectionToken< ReadonlyArray<() => Observable<unknown> | Promise<unknown> | void> >(ngDevMode ? 'Application Initializer' : ''); /** * @description * The provided function is injected at application startup and executed during * app initialization. If the function returns a Promise or an Observable, initialization * does not complete until the Promise is resolved or the Observable is completed. * * You can, for example, create a function that loads language data * or an external configuration, and provide that function using `provideAppInitializer()`. * The function is executed during the application bootstrap process, * and the needed data is available on startup. * * Note that the provided initializer is run in the injection context. * * Previously, this was achieved using the `APP_INITIALIZER` token which is now deprecated. * * @see {@link APP_INITIALIZER} * * @usageNotes * The following example illustrates how to configure an initialization function using * `provideAppInitializer()` * ``` * bootstrapApplication(App, { * providers: [ * provideAppInitializer(() => { * const http = inject(HttpClient); * return firstValueFrom( * http * .get("https://someUrl.com/api/user") * .pipe(tap(user => { ... })) * ); * }), * provideHttpClient(), * ], * }); * ``` * * @publicApi */ export function provideAppInitializer( initializerFn: () => Observable<unknown> | Promise<unknown> | void, ): EnvironmentProviders { return makeEnvironmentProviders([ { provide: APP_INITIALIZER, multi: true, useValue: initializerFn, }, ]); } /** * A class that reflects the state of running {@link APP_INITIALIZER} functions. * * @publicApi */ @Injectable({providedIn: 'root'}) export class ApplicationInitStatus { // Using non null assertion, these fields are defined below // within the `new Promise` callback (synchronously). private resolve!: (...args: any[]) => void; private reject!: (...args: any[]) => void; private initialized = false; public readonly done = false; public readonly donePromise: Promise<any> = new Promise((res, rej) => { this.resolve = res; this.reject = rej; }); private readonly appInits = inject(APP_INITIALIZER, {optional: true}) ?? []; private readonly injector = inject(Injector); constructor() { if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) { throw new RuntimeError( RuntimeErrorCode.INVALID_MULTI_PROVIDER, 'Unexpected type of the `APP_INITIALIZER` token value ' + `(expected an array, but got ${typeof this.appInits}). ` + 'Please check that the `APP_INITIALIZER` token is configured as a ' + '`multi: true` provider.', ); } } /** @internal */ runInitializers() { if (this.initialized) { return; } const asyncInitPromises = []; for (const appInits of this.appInits) { const initResult = runInInjectionContext(this.injector, appInits); if (isPromise(initResult)) { asyncInitPromises.push(initResult); } else if (isSubscribable(initResult)) { const observableAsPromise = new Promise<void>((resolve, reject) => { initResult.subscribe({complete: resolve, error: reject}); }); asyncInitPromises.push(observableAsPromise); } } const complete = () => { // @ts-expect-error overwriting a readonly this.done = true; this.resolve(); }; Promise.all(asyncInitPromises) .then(() => { complete(); }) .catch((e) => { this.reject(e); }); if (asyncInitPromises.length === 0) { complete(); } this.initialized = true; } }
{ "end_byte": 7747, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_init.ts" }
angular/packages/core/src/application/application_ngmodule_factory_compiler.ts_0_3104
/** * @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} from '../compiler/compiler_facade'; import {Injector} from '../di/injector'; import {Type} from '../interface/type'; import {COMPILER_OPTIONS, CompilerOptions} from '../linker/compiler'; import {NgModuleFactory} from '../linker/ng_module_factory'; import { isComponentResourceResolutionQueueEmpty, resolveComponentResources, } from '../metadata/resource_loading'; import {assertNgModuleType} from '../render3/assert'; import {setJitOptions} from '../render3/jit/jit_options'; import {NgModuleFactory as R3NgModuleFactory} from '../render3/ng_module_ref'; export function compileNgModuleFactory<M>( injector: Injector, options: CompilerOptions, moduleType: Type<M>, ): Promise<NgModuleFactory<M>> { ngDevMode && assertNgModuleType(moduleType); const moduleFactory = new R3NgModuleFactory(moduleType); // All of the logic below is irrelevant for AOT-compiled code. if (typeof ngJitMode !== 'undefined' && !ngJitMode) { return Promise.resolve(moduleFactory); } const compilerOptions = injector.get(COMPILER_OPTIONS, []).concat(options); // Configure the compiler to use the provided options. This call may fail when multiple modules // are bootstrapped with incompatible options, as a component can only be compiled according to // a single set of options. setJitOptions({ defaultEncapsulation: _lastDefined(compilerOptions.map((opts) => opts.defaultEncapsulation)), preserveWhitespaces: _lastDefined(compilerOptions.map((opts) => opts.preserveWhitespaces)), }); if (isComponentResourceResolutionQueueEmpty()) { return Promise.resolve(moduleFactory); } const compilerProviders = compilerOptions.flatMap((option) => option.providers ?? []); // In case there are no compiler providers, we just return the module factory as // there won't be any resource loader. This can happen with Ivy, because AOT compiled // modules can be still passed through "bootstrapModule". In that case we shouldn't // unnecessarily require the JIT compiler. if (compilerProviders.length === 0) { return Promise.resolve(moduleFactory); } const compiler = getCompilerFacade({ usage: JitCompilerUsage.Decorator, kind: 'NgModule', type: moduleType, }); const compilerInjector = Injector.create({providers: compilerProviders}); const resourceLoader = compilerInjector.get(compiler.ResourceLoader); // The resource loader can also return a string while the "resolveComponentResources" // always expects a promise. Therefore we need to wrap the returned value in a promise. return resolveComponentResources((url) => Promise.resolve(resourceLoader.get(url))).then( () => moduleFactory, ); } function _lastDefined<T>(args: T[]): T | undefined { for (let i = args.length - 1; i >= 0; i--) { if (args[i] !== undefined) { return args[i]; } } return undefined; }
{ "end_byte": 3104, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_ngmodule_factory_compiler.ts" }
angular/packages/core/src/application/application_config.ts_0_1050
/** * @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 {EnvironmentProviders, Provider} from '../di'; /** * Set of config options available during the application bootstrap operation. * * @publicApi */ export interface ApplicationConfig { /** * List of providers that should be available to the root component and all its children. */ providers: Array<Provider | EnvironmentProviders>; } /** * Merge multiple application configurations from left to right. * * @param configs Two or more configurations to be merged. * @returns A merged [ApplicationConfig](api/core/ApplicationConfig). * * @publicApi */ export function mergeApplicationConfig(...configs: ApplicationConfig[]): ApplicationConfig { return configs.reduce( (prev, curr) => { return Object.assign(prev, curr, {providers: [...prev.providers, ...curr.providers]}); }, {providers: []}, ); }
{ "end_byte": 1050, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_config.ts" }
angular/packages/core/src/application/application_module.ts_0_657
/** * @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 {NgModule} from '../metadata'; import {ApplicationRef} from './application_ref'; /** * Re-exported by `BrowserModule`, which is included automatically in the root * `AppModule` when you create a new app with the CLI `new` command. Eagerly injects * `ApplicationRef` to instantiate it. * * @publicApi */ @NgModule() export class ApplicationModule { // Inject ApplicationRef to make it eager... constructor(appRef: ApplicationRef) {} }
{ "end_byte": 657, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/application/application_module.ts" }
angular/packages/core/src/resource/api.ts_0_4820
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injector} from '../di/injector'; import {Signal, ValueEqualityFn} from '../render3/reactivity/api'; import {WritableSignal} from '../render3/reactivity/signal'; /** * Status of a `Resource`. * * @experimental */ export enum ResourceStatus { /** * The resource has no valid request and will not perform any loading. * * `value()` will be `undefined`. */ Idle, /** * Loading failed with an error. * * `value()` will be `undefined`. */ Error, /** * The resource is currently loading a new value as a result of a change in its `request`. * * `value()` will be `undefined`. */ Loading, /** * The resource is currently reloading a fresh value for the same request. * * `value()` will continue to return the previously fetched value during the reloading operation. */ Reloading, /** * Loading has completed and the resource has the value returned from the loader. */ Resolved, /** * The resource's value was set locally via `.set()` or `.update()`. */ Local, } /** * A Resource is an asynchronous dependency (for example, the results of an API call) that is * managed and delivered through signals. * * The usual way of creating a `Resource` is through the `resource` function, but various other APIs * may present `Resource` instances to describe their own concepts. * * @experimental */ export interface Resource<T> { /** * The current value of the `Resource`, or `undefined` if there is no current value. */ readonly value: Signal<T | undefined>; /** * The current status of the `Resource`, which describes what the resource is currently doing and * what can be expected of its `value`. */ readonly status: Signal<ResourceStatus>; /** * When in the `error` state, this returns the last known error from the `Resource`. */ readonly error: Signal<unknown>; /** * Whether this resource is loading a new value (or reloading the existing one). */ readonly isLoading: Signal<boolean>; /** * Whether this resource has a valid current value. * * This function is reactive. */ hasValue(): this is Resource<T> & {value: Signal<T>}; /** * Instructs the resource to re-load any asynchronous dependency it may have. * * Note that the resource will not enter its reloading state until the actual backend request is * made. * * @returns true if a reload was initiated, false if a reload was unnecessary or unsupported */ reload(): boolean; } /** * A `Resource` with a mutable value. * * Overwriting the value of a resource sets it to the 'local' state. * * @experimental */ export interface WritableResource<T> extends Resource<T> { readonly value: WritableSignal<T | undefined>; hasValue(): this is WritableResource<T> & {value: WritableSignal<T>}; /** * Convenience wrapper for `value.set`. */ set(value: T | undefined): void; /** * Convenience wrapper for `value.update`. */ update(updater: (value: T | undefined) => T | undefined): void; asReadonly(): Resource<T>; } /** * A `WritableResource` created through the `resource` function. * * @experimental */ export interface ResourceRef<T> extends WritableResource<T> { /** * Manually destroy the resource, which cancels pending requests and returns it to `idle` state. */ destroy(): void; } /** * Parameter to a `ResourceLoader` which gives the request and other options for the current loading * operation. * * @experimental */ export interface ResourceLoaderParams<R> { request: Exclude<NoInfer<R>, undefined>; abortSignal: AbortSignal; previous: { status: ResourceStatus; }; } /** * Loading function for a `Resource`. * * @experimental */ export type ResourceLoader<T, R> = (param: ResourceLoaderParams<R>) => PromiseLike<T>; /** * Options to the `resource` function, for creating a resource. * * @experimental */ export interface ResourceOptions<T, R> { /** * A reactive function which determines the request to be made. Whenever the request changes, the * loader will be triggered to fetch a new value for the resource. * * If a request function isn't provided, the loader won't rerun unless the resource is reloaded. */ request?: () => R; /** * Loading function which returns a `Promise` of the resource's value for a given request. */ loader: ResourceLoader<T, R>; /** * Equality function used to compare the return value of the loader. */ equal?: ValueEqualityFn<T>; /** * Overrides the `Injector` used by `resource`. */ injector?: Injector; }
{ "end_byte": 4820, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/resource/api.ts" }
angular/packages/core/src/resource/resource.ts_0_4536
/** * @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 {untracked} from '../render3/reactivity/untracked'; import {computed} from '../render3/reactivity/computed'; import {signal, WritableSignal} from '../render3/reactivity/signal'; import {Signal} from '../render3/reactivity/api'; import {effect, EffectRef} from '../render3/reactivity/effect'; import { ResourceOptions, ResourceStatus, WritableResource, ResourceLoader, Resource, ResourceRef, } from './api'; import {ValueEqualityFn, SIGNAL, SignalNode} from '@angular/core/primitives/signals'; import {Injector} from '../di/injector'; import {assertInInjectionContext} from '../di/contextual'; import {inject} from '../di/injector_compatibility'; import {PendingTasks} from '../pending_tasks'; import {DestroyRef} from '../linker'; /** * Constructs a `Resource` that projects a reactive request to an asynchronous operation defined by * a loader function, which exposes the result of the loading operation via signals. * * Note that `resource` is intended for _read_ operations, not operations which perform mutations. * `resource` will cancel in-progress loads via the `AbortSignal` when destroyed or when a new * request object becomes available, which could prematurely abort mutations. * * @experimental */ export function resource<T, R>(options: ResourceOptions<T, R>): ResourceRef<T> { options?.injector || assertInInjectionContext(resource); const request = (options.request ?? (() => null)) as () => R; return new WritableResourceImpl<T, R>(request, options.loader, options.equal, options.injector); } /** * Base class for `WritableResource` which handles the state operations and is unopinionated on the * actual async operation. * * Mainly factored out for better readability. */ abstract class BaseWritableResource<T> implements WritableResource<T> { readonly value: WritableSignal<T | undefined>; readonly status = signal<ResourceStatus>(ResourceStatus.Idle); readonly error = signal<unknown>(undefined); protected readonly rawSetValue: (value: T | undefined) => void; constructor(equal: ValueEqualityFn<T> | undefined) { this.value = signal<T | undefined>(undefined, { equal: equal ? wrapEqualityFn(equal) : undefined, }); this.rawSetValue = this.value.set; this.value.set = (value: T | undefined) => this.set(value); this.value.update = (fn: (value: T | undefined) => T | undefined) => this.set(fn(untracked(this.value))); } set(value: T | undefined): void { // Set the value signal and check whether its `version` changes. This will tell us // if the value signal actually updated or not. const prevVersion = (this.value[SIGNAL] as SignalNode<T>).version; this.rawSetValue(value); if ((this.value[SIGNAL] as SignalNode<T>).version === prevVersion) { // The value must've been equal to the previous, so no need to change states. return; } // We're departing from whatever state the resource was in previously, and entering // Local state. this.onLocalValue(); this.status.set(ResourceStatus.Local); this.error.set(undefined); } update(updater: (value: T | undefined) => T | undefined): void { this.value.update(updater); } readonly isLoading = computed( () => this.status() === ResourceStatus.Loading || this.status() === ResourceStatus.Reloading, ); hasValue(): this is WritableResource<T> & {value: WritableSignal<T>} { return ( this.status() === ResourceStatus.Resolved || this.status() === ResourceStatus.Local || this.status() === ResourceStatus.Reloading ); } asReadonly(): Resource<T> { return this; } /** * Put the resource in a state with a given value. */ protected setValueState(status: ResourceStatus, value: T | undefined = undefined): void { this.status.set(status); this.rawSetValue(value); this.error.set(undefined); } /** * Put the resource into the error state. */ protected setErrorState(err: unknown): void { this.status.set(ResourceStatus.Error); this.value.set(undefined); this.error.set(err); } /** * Called when the resource is transitioning to local state. * * For example, this can be used to cancel any in-progress loading operations. */ protected abstract onLocalValue(): void; public abstract reload(): boolean; }
{ "end_byte": 4536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/resource/resource.ts" }
angular/packages/core/src/resource/resource.ts_4538_9433
class WritableResourceImpl<T, R> extends BaseWritableResource<T> implements ResourceRef<T> { private readonly request: Signal<{request: R; reload: WritableSignal<number>}>; private readonly pendingTasks: PendingTasks; private readonly effectRef: EffectRef; private pendingController: AbortController | undefined; private resolvePendingTask: (() => void) | undefined = undefined; constructor( requestFn: () => R, private readonly loaderFn: ResourceLoader<T, R>, equal: ValueEqualityFn<T> | undefined, injector: Injector | undefined, ) { super(equal); injector = injector ?? inject(Injector); this.pendingTasks = injector.get(PendingTasks); this.request = computed(() => ({ // The current request as defined for this resource. request: requestFn(), // A counter signal which increments from 0, re-initialized for each request (similar to the // `linkedSignal` pattern). A value other than 0 indicates a refresh operation. reload: signal(0), })); // The actual data-fetching effect. this.effectRef = effect(this.loadEffect.bind(this), {injector, manualCleanup: true}); // Cancel any pending request when the resource itself is destroyed. injector.get(DestroyRef).onDestroy(() => this.destroy()); } override reload(): boolean { // We don't want to restart in-progress loads. const status = untracked(this.status); if ( status === ResourceStatus.Idle || status === ResourceStatus.Loading || status === ResourceStatus.Reloading ) { return false; } untracked(this.request).reload.update((v) => v + 1); return true; } destroy(): void { this.effectRef.destroy(); this.abortInProgressLoad(); this.setValueState(ResourceStatus.Idle); } private async loadEffect(): Promise<void> { // Capture the status before any state transitions. const previousStatus = untracked(this.status); // Cancel any previous loading attempts. this.abortInProgressLoad(); const request = this.request(); if (request.request === undefined) { // An undefined request means there's nothing to load. this.setValueState(ResourceStatus.Idle); return; } // Subscribing here allows us to refresh the load later by updating the refresh signal. At the // same time, we update the status according to whether we're reloading or loading. if (request.reload() === 0) { this.setValueState(ResourceStatus.Loading); // value becomes undefined } else { this.status.set(ResourceStatus.Reloading); // value persists } // Capturing _this_ load's pending task in a local variable is important here. We may attempt to // resolve it twice: // // 1. when the loading function promise resolves/rejects // 2. when cancelling the loading operation // // After the loading operation is cancelled, `this.resolvePendingTask` no longer represents this // particular task, but this `await` may eventually resolve/reject. Thus, when we cancel in // response to (1) below, we need to cancel the locally saved task. const resolvePendingTask = (this.resolvePendingTask = this.pendingTasks.add()); const {signal: abortSignal} = (this.pendingController = new AbortController()); try { // The actual loading is run through `untracked` - only the request side of `resource` is // reactive. This avoids any confusion with signals tracking or not tracking depending on // which side of the `await` they are. const result = await untracked(() => this.loaderFn({ abortSignal, request: request.request as Exclude<R, undefined>, previous: { status: previousStatus, }, }), ); if (abortSignal.aborted) { // This load operation was cancelled. return; } // Success :) this.setValueState(ResourceStatus.Resolved, result); } catch (err) { if (abortSignal.aborted) { // This load operation was cancelled. return; } // Fail :( this.setErrorState(err); } finally { // Resolve the pending task now that loading is done. resolvePendingTask(); } } private abortInProgressLoad(): void { this.pendingController?.abort(); this.pendingController = undefined; // Once the load is aborted, we no longer want to block stability on its resolution. this.resolvePendingTask?.(); this.resolvePendingTask = undefined; } protected override onLocalValue(): void { this.abortInProgressLoad(); } } /** * Wraps an equality function to handle either value being `undefined`. */ function wrapEqualityFn<T>(equal: ValueEqualityFn<T>): ValueEqualityFn<T | undefined> { return (a, b) => (a === undefined || b === undefined ? a === b : equal(a, b)); }
{ "end_byte": 9433, "start_byte": 4538, "url": "https://github.com/angular/angular/blob/main/packages/core/src/resource/resource.ts" }
angular/packages/core/src/resource/index.ts_0_264
/** * @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 * from './api'; export {resource} from './resource';
{ "end_byte": 264, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/resource/index.ts" }
angular/packages/core/src/i18n/locale_en.ts_0_1293
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // THIS CODE IS GENERATED - DO NOT MODIFY. const u = undefined; function plural(val: number): number { const n = val, i = Math.floor(Math.abs(val)), v = val.toString().replace(/^[^.]*\.?/, '').length; if (i === 1 && v === 0) return 1; return 5; } export default ["en",[["a","p"],["AM","PM"],u],[["AM","PM"],u,u],[["S","M","T","W","T","F","S"],["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],["Su","Mo","Tu","We","Th","Fr","Sa"]],u,[["J","F","M","A","M","J","J","A","S","O","N","D"],["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],["January","February","March","April","May","June","July","August","September","October","November","December"]],u,[["B","A"],["BC","AD"],["Before Christ","Anno Domini"]],0,[6,0],["M/d/yy","MMM d, y","MMMM d, y","EEEE, MMMM d, y"],["h:mm a","h:mm:ss a","h:mm:ss a z","h:mm:ss a zzzz"],["{1}, {0}",u,"{1} 'at' {0}",u],[".",",",";","%","+","-","E","×","‰","∞","NaN",":"],["#,##0.###","#,##0%","¤#,##0.00","#E0"],"USD","$","US Dollar",{},"ltr", plural];
{ "end_byte": 1293, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/i18n/locale_en.ts" }
angular/packages/core/src/i18n/utils.ts_0_597
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {TNode, TNodeFlags} from '../render3/interfaces/node'; /** * Checks whether a TNode is considered detached, i.e. not present in the * translated i18n template. We should not attempt hydration for such nodes * and instead, use a regular "creation mode". */ export function isDetachedByI18n(tNode: TNode) { return (tNode.flags & TNodeFlags.isDetached) === TNodeFlags.isDetached; }
{ "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/i18n/utils.ts" }
angular/packages/core/src/i18n/locale_data_api.ts_0_4466
/** * @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 {global} from '../util/global'; import localeEn from './locale_en'; /** * This const is used to store the locale data registered with `registerLocaleData` */ let LOCALE_DATA: {[localeId: string]: any} = {}; /** * Register locale data to be used internally by Angular. See the * ["I18n guide"](guide/i18n/format-data-locale) to know how to import additional locale * data. * * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1 */ export function registerLocaleData(data: any, localeId?: string | any, extraData?: any): void { if (typeof localeId !== 'string') { extraData = localeId; localeId = data[LocaleDataIndex.LocaleId]; } localeId = localeId.toLowerCase().replace(/_/g, '-'); LOCALE_DATA[localeId] = data; if (extraData) { LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData; } } /** * Finds the locale data for a given locale. * * @param locale The locale code. * @returns The locale data. * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n) */ export function findLocaleData(locale: string): any { const normalizedLocale = normalizeLocale(locale); let match = getLocaleData(normalizedLocale); if (match) { return match; } // let's try to find a parent locale const parentLocale = normalizedLocale.split('-')[0]; match = getLocaleData(parentLocale); if (match) { return match; } if (parentLocale === 'en') { return localeEn; } throw new RuntimeError( RuntimeErrorCode.MISSING_LOCALE_DATA, ngDevMode && `Missing locale data for the locale "${locale}".`, ); } /** * Retrieves the default currency code for the given locale. * * The default is defined as the first currency which is still in use. * * @param locale The code of the locale whose currency code we want. * @returns The code of the default currency for the given locale. * */ export function getLocaleCurrencyCode(locale: string): string | null { const data = findLocaleData(locale); return data[LocaleDataIndex.CurrencyCode] || null; } /** * Retrieves the plural function used by ICU expressions to determine the plural case to use * for a given locale. * @param locale A locale code for the locale format rules to use. * @returns The plural function for the locale. * @see {@link NgPlural} * @see [Internationalization (i18n) Guide](guide/i18n) */ export function getLocalePluralCase(locale: string): (value: number) => number { const data = findLocaleData(locale); return data[LocaleDataIndex.PluralCase]; } /** * Helper function to get the given `normalizedLocale` from `LOCALE_DATA` * or from the global `ng.common.locale`. */ export function getLocaleData(normalizedLocale: string): any { if (!(normalizedLocale in LOCALE_DATA)) { LOCALE_DATA[normalizedLocale] = global.ng && global.ng.common && global.ng.common.locales && global.ng.common.locales[normalizedLocale]; } return LOCALE_DATA[normalizedLocale]; } /** * Helper function to remove all the locale data from `LOCALE_DATA`. */ export function unregisterAllLocaleData() { LOCALE_DATA = {}; } /** * Index of each type of locale data from the locale data array */ export enum LocaleDataIndex { LocaleId = 0, DayPeriodsFormat, DayPeriodsStandalone, DaysFormat, DaysStandalone, MonthsFormat, MonthsStandalone, Eras, FirstDayOfWeek, WeekendRange, DateFormat, TimeFormat, DateTimeFormat, NumberSymbols, NumberFormats, CurrencyCode, CurrencySymbol, CurrencyName, Currencies, Directionality, PluralCase, ExtraData, } /** * Index of each type of locale data from the extra locale data array */ export const enum ExtraLocaleDataIndex { ExtraDayPeriodFormats = 0, ExtraDayPeriodStandalone, ExtraDayPeriodsRules, } /** * Index of each value in currency data (used to describe CURRENCIES_EN in currencies.ts) */ export const enum CurrencyIndex { Symbol = 0, SymbolNarrow, NbOfDigits, } /** * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`. */ function normalizeLocale(locale: string): string { return locale.toLowerCase().replace(/_/g, '-'); }
{ "end_byte": 4466, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/i18n/locale_data_api.ts" }
angular/packages/core/src/i18n/localization.ts_0_926
/** * @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 {getLocalePluralCase} from './locale_data_api'; const pluralMapping = ['zero', 'one', 'two', 'few', 'many']; /** * Returns the plural case based on the locale */ export function getPluralCase(value: string, locale: string): string { const plural = getLocalePluralCase(locale)(parseInt(value, 10)); const result = pluralMapping[plural]; return result !== undefined ? result : 'other'; } /** * The locale id that the application is using by default (for translations and ICU expressions). */ export const DEFAULT_LOCALE_ID = 'en-US'; /** * USD currency code that the application uses by default for CurrencyPipe when no * DEFAULT_CURRENCY_CODE is provided. */ export const USD_CURRENCY_CODE = 'USD';
{ "end_byte": 926, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/i18n/localization.ts" }
angular/packages/core/src/i18n/tokens.ts_0_6258
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken} from '../di/injection_token'; import {inject} from '../di/injector_compatibility'; import {InjectFlags} from '../di/interface/injector'; import {DEFAULT_LOCALE_ID, USD_CURRENCY_CODE} from './localization'; declare const $localize: {locale?: string}; /** * Work out the locale from the potential global properties. * * * Closure Compiler: use `goog.LOCALE`. * * Ivy enabled: use `$localize.locale` */ export function getGlobalLocale(): string { if ( typeof ngI18nClosureMode !== 'undefined' && ngI18nClosureMode && typeof goog !== 'undefined' && goog.LOCALE !== 'en' ) { // * The default `goog.LOCALE` value is `en`, while Angular used `en-US`. // * In order to preserve backwards compatibility, we use Angular default value over // Closure Compiler's one. return goog.LOCALE; } else { // KEEP `typeof $localize !== 'undefined' && $localize.locale` IN SYNC WITH THE LOCALIZE // COMPILE-TIME INLINER. // // * During compile time inlining of translations the expression will be replaced // with a string literal that is the current locale. Other forms of this expression are not // guaranteed to be replaced. // // * During runtime translation evaluation, the developer is required to set `$localize.locale` // if required, or just to provide their own `LOCALE_ID` provider. return (typeof $localize !== 'undefined' && $localize.locale) || DEFAULT_LOCALE_ID; } } /** * Provide this token to set the locale of your application. * It is used for i18n extraction, by i18n pipes (DatePipe, I18nPluralPipe, CurrencyPipe, * DecimalPipe and PercentPipe) and by ICU expressions. * * See the [i18n guide](guide/i18n/locale-id) for more information. * * @usageNotes * ### Example * * ```typescript * import { LOCALE_ID } from '@angular/core'; * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; * import { AppModule } from './app/app.module'; * * platformBrowserDynamic().bootstrapModule(AppModule, { * providers: [{provide: LOCALE_ID, useValue: 'en-US' }] * }); * ``` * * @publicApi */ export const LOCALE_ID: InjectionToken<string> = new InjectionToken(ngDevMode ? 'LocaleId' : '', { providedIn: 'root', factory: () => inject(LOCALE_ID, InjectFlags.Optional | InjectFlags.SkipSelf) || getGlobalLocale(), }); /** * Provide this token to set the default currency code your application uses for * CurrencyPipe when there is no currency code passed into it. This is only used by * CurrencyPipe and has no relation to locale currency. Defaults to USD if not configured. * * See the [i18n guide](guide/i18n/locale-id) for more information. * * <div class="alert is-helpful"> * * **Deprecation notice:** * * The default currency code is currently always `USD` but this is deprecated from v9. * * **In v10 the default currency code will be taken from the current locale.** * * If you need the previous behavior then set it by creating a `DEFAULT_CURRENCY_CODE` provider in * your application `NgModule`: * * ```ts * {provide: DEFAULT_CURRENCY_CODE, useValue: 'USD'} * ``` * * </div> * * @usageNotes * ### Example * * ```typescript * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; * import { AppModule } from './app/app.module'; * * platformBrowserDynamic().bootstrapModule(AppModule, { * providers: [{provide: DEFAULT_CURRENCY_CODE, useValue: 'EUR' }] * }); * ``` * * @publicApi */ export const DEFAULT_CURRENCY_CODE = new InjectionToken<string>( ngDevMode ? 'DefaultCurrencyCode' : '', { providedIn: 'root', factory: () => USD_CURRENCY_CODE, }, ); /** * Use this token at bootstrap to provide the content of your translation file (`xtb`, * `xlf` or `xlf2`) when you want to translate your application in another language. * * See the [i18n guide](guide/i18n/merge) for more information. * * @usageNotes * ### Example * * ```typescript * import { TRANSLATIONS } from '@angular/core'; * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; * import { AppModule } from './app/app.module'; * * // content of your translation file * const translations = '....'; * * platformBrowserDynamic().bootstrapModule(AppModule, { * providers: [{provide: TRANSLATIONS, useValue: translations }] * }); * ``` * * @publicApi */ export const TRANSLATIONS = new InjectionToken<string>(ngDevMode ? 'Translations' : ''); /** * Provide this token at bootstrap to set the format of your {@link TRANSLATIONS}: `xtb`, * `xlf` or `xlf2`. * * See the [i18n guide](guide/i18n/merge) for more information. * * @usageNotes * ### Example * * ```typescript * import { TRANSLATIONS_FORMAT } from '@angular/core'; * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; * import { AppModule } from './app/app.module'; * * platformBrowserDynamic().bootstrapModule(AppModule, { * providers: [{provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }] * }); * ``` * * @publicApi */ export const TRANSLATIONS_FORMAT = new InjectionToken<string>( ngDevMode ? 'TranslationsFormat' : '', ); /** * Use this enum at bootstrap as an option of `bootstrapModule` to define the strategy * that the compiler should use in case of missing translations: * - Error: throw if you have missing translations. * - Warning (default): show a warning in the console and/or shell. * - Ignore: do nothing. * * See the [i18n guide](guide/i18n/merge#report-missing-translations) for more information. * * @usageNotes * ### Example * ```typescript * import { MissingTranslationStrategy } from '@angular/core'; * import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; * import { AppModule } from './app/app.module'; * * platformBrowserDynamic().bootstrapModule(AppModule, { * missingTranslation: MissingTranslationStrategy.Error * }); * ``` * * @publicApi */ export enum MissingTranslationStrategy { Error = 0, Warning = 1, Ignore = 2, }
{ "end_byte": 6258, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/i18n/tokens.ts" }
angular/packages/core/src/sanitization/sanitization.ts_0_8384
/** * @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 {XSS_SECURITY_URL} from '../error_details_base_url'; import {RuntimeError, RuntimeErrorCode} from '../errors'; import {getDocument} from '../render3/interfaces/document'; import {ENVIRONMENT} from '../render3/interfaces/view'; import {getLView} from '../render3/state'; import {renderStringify} from '../render3/util/stringify_utils'; import {TrustedHTML, TrustedScript, TrustedScriptURL} from '../util/security/trusted_type_defs'; import {trustedHTMLFromString, trustedScriptURLFromString} from '../util/security/trusted_types'; import { trustedHTMLFromStringBypass, trustedScriptFromStringBypass, trustedScriptURLFromStringBypass, } from '../util/security/trusted_types_bypass'; import {allowSanitizationBypassAndThrow, BypassType, unwrapSafeValue} from './bypass'; import {_sanitizeHtml as _sanitizeHtml} from './html_sanitizer'; import {Sanitizer} from './sanitizer'; import {SecurityContext} from './security'; import {_sanitizeUrl as _sanitizeUrl} from './url_sanitizer'; /** * An `html` sanitizer which converts untrusted `html` **string** into trusted string by removing * dangerous content. * * This method parses the `html` and locates potentially dangerous content (such as urls and * javascript) and removes it. * * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustHtml}. * * @param unsafeHtml untrusted `html`, typically from the user. * @returns `html` string which is safe to display to user, because all of the dangerous javascript * and urls have been removed. * * @codeGenApi */ export function ɵɵsanitizeHtml(unsafeHtml: any): TrustedHTML | string { const sanitizer = getSanitizer(); if (sanitizer) { return trustedHTMLFromStringBypass(sanitizer.sanitize(SecurityContext.HTML, unsafeHtml) || ''); } if (allowSanitizationBypassAndThrow(unsafeHtml, BypassType.Html)) { return trustedHTMLFromStringBypass(unwrapSafeValue(unsafeHtml)); } return _sanitizeHtml(getDocument(), renderStringify(unsafeHtml)); } /** * A `style` sanitizer which converts untrusted `style` **string** into trusted string by removing * dangerous content. * * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustStyle}. * * @param unsafeStyle untrusted `style`, typically from the user. * @returns `style` string which is safe to bind to the `style` properties. * * @codeGenApi */ export function ɵɵsanitizeStyle(unsafeStyle: any): string { const sanitizer = getSanitizer(); if (sanitizer) { return sanitizer.sanitize(SecurityContext.STYLE, unsafeStyle) || ''; } if (allowSanitizationBypassAndThrow(unsafeStyle, BypassType.Style)) { return unwrapSafeValue(unsafeStyle); } return renderStringify(unsafeStyle); } /** * A `url` sanitizer which converts untrusted `url` **string** into trusted string by removing * dangerous * content. * * This method parses the `url` and locates potentially dangerous content (such as javascript) and * removes it. * * It is possible to mark a string as trusted by calling {@link bypassSanitizationTrustUrl}. * * @param unsafeUrl untrusted `url`, typically from the user. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because * all of the dangerous javascript has been removed. * * @codeGenApi */ export function ɵɵsanitizeUrl(unsafeUrl: any): string { const sanitizer = getSanitizer(); if (sanitizer) { return sanitizer.sanitize(SecurityContext.URL, unsafeUrl) || ''; } if (allowSanitizationBypassAndThrow(unsafeUrl, BypassType.Url)) { return unwrapSafeValue(unsafeUrl); } return _sanitizeUrl(renderStringify(unsafeUrl)); } /** * A `url` sanitizer which only lets trusted `url`s through. * * This passes only `url`s marked trusted by calling {@link bypassSanitizationTrustResourceUrl}. * * @param unsafeResourceUrl untrusted `url`, typically from the user. * @returns `url` string which is safe to bind to the `src` properties such as `<img src>`, because * only trusted `url`s have been allowed to pass. * * @codeGenApi */ export function ɵɵsanitizeResourceUrl(unsafeResourceUrl: any): TrustedScriptURL | string { const sanitizer = getSanitizer(); if (sanitizer) { return trustedScriptURLFromStringBypass( sanitizer.sanitize(SecurityContext.RESOURCE_URL, unsafeResourceUrl) || '', ); } if (allowSanitizationBypassAndThrow(unsafeResourceUrl, BypassType.ResourceUrl)) { return trustedScriptURLFromStringBypass(unwrapSafeValue(unsafeResourceUrl)); } throw new RuntimeError( RuntimeErrorCode.UNSAFE_VALUE_IN_RESOURCE_URL, ngDevMode && `unsafe value used in a resource URL context (see ${XSS_SECURITY_URL})`, ); } /** * A `script` sanitizer which only lets trusted javascript through. * * This passes only `script`s marked trusted by calling {@link * bypassSanitizationTrustScript}. * * @param unsafeScript untrusted `script`, typically from the user. * @returns `url` string which is safe to bind to the `<script>` element such as `<img src>`, * because only trusted `scripts` have been allowed to pass. * * @codeGenApi */ export function ɵɵsanitizeScript(unsafeScript: any): TrustedScript | string { const sanitizer = getSanitizer(); if (sanitizer) { return trustedScriptFromStringBypass( sanitizer.sanitize(SecurityContext.SCRIPT, unsafeScript) || '', ); } if (allowSanitizationBypassAndThrow(unsafeScript, BypassType.Script)) { return trustedScriptFromStringBypass(unwrapSafeValue(unsafeScript)); } throw new RuntimeError( RuntimeErrorCode.UNSAFE_VALUE_IN_SCRIPT, ngDevMode && 'unsafe value used in a script context', ); } /** * A template tag function for promoting the associated constant literal to a * TrustedHTML. Interpolation is explicitly not allowed. * * @param html constant template literal containing trusted HTML. * @returns TrustedHTML wrapping `html`. * * @security This is a security-sensitive function and should only be used to * convert constant values of attributes and properties found in * application-provided Angular templates to TrustedHTML. * * @codeGenApi */ export function ɵɵtrustConstantHtml(html: TemplateStringsArray): TrustedHTML | string { // The following runtime check ensures that the function was called as a // template tag (e.g. ɵɵtrustConstantHtml`content`), without any interpolation // (e.g. not ɵɵtrustConstantHtml`content ${variable}`). A TemplateStringsArray // is an array with a `raw` property that is also an array. The associated // template literal has no interpolation if and only if the length of the // TemplateStringsArray is 1. if (ngDevMode && (!Array.isArray(html) || !Array.isArray(html.raw) || html.length !== 1)) { throw new Error(`Unexpected interpolation in trusted HTML constant: ${html.join('?')}`); } return trustedHTMLFromString(html[0]); } /** * A template tag function for promoting the associated constant literal to a * TrustedScriptURL. Interpolation is explicitly not allowed. * * @param url constant template literal containing a trusted script URL. * @returns TrustedScriptURL wrapping `url`. * * @security This is a security-sensitive function and should only be used to * convert constant values of attributes and properties found in * application-provided Angular templates to TrustedScriptURL. * * @codeGenApi */ export function ɵɵtrustConstantResourceUrl(url: TemplateStringsArray): TrustedScriptURL | string { // The following runtime check ensures that the function was called as a // template tag (e.g. ɵɵtrustConstantResourceUrl`content`), without any // interpolation (e.g. not ɵɵtrustConstantResourceUrl`content ${variable}`). A // TemplateStringsArray is an array with a `raw` property that is also an // array. The associated template literal has no interpolation if and only if // the length of the TemplateStringsArray is 1. if (ngDevMode && (!Array.isArray(url) || !Array.isArray(url.raw) || url.length !== 1)) { throw new Error(`Unexpected interpolation in trusted URL constant: ${url.join('?')}`); } return trustedScriptURLFromString(url[0]); } /** * Detects which
{ "end_byte": 8384, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/sanitization.ts" }
angular/packages/core/src/sanitization/sanitization.ts_8386_10747
anitizer to use for URL property, based on tag name and prop name. * * The rules are based on the RESOURCE_URL context config from * `packages/compiler/src/schema/dom_security_schema.ts`. * If tag and prop names don't match Resource URL schema, use URL sanitizer. */ export function getUrlSanitizer(tag: string, prop: string) { if ( (prop === 'src' && (tag === 'embed' || tag === 'frame' || tag === 'iframe' || tag === 'media' || tag === 'script')) || (prop === 'href' && (tag === 'base' || tag === 'link')) ) { return ɵɵsanitizeResourceUrl; } return ɵɵsanitizeUrl; } /** * Sanitizes URL, selecting sanitizer function based on tag and property names. * * This function is used in case we can't define security context at compile time, when only prop * name is available. This happens when we generate host bindings for Directives/Components. The * host element is unknown at compile time, so we defer calculation of specific sanitizer to * runtime. * * @param unsafeUrl untrusted `url`, typically from the user. * @param tag target element tag name. * @param prop name of the property that contains the value. * @returns `url` string which is safe to bind. * * @codeGenApi */ export function ɵɵsanitizeUrlOrResourceUrl(unsafeUrl: any, tag: string, prop: string): any { return getUrlSanitizer(tag, prop)(unsafeUrl); } export function validateAgainstEventProperties(name: string) { if (name.toLowerCase().startsWith('on')) { const errorMessage = `Binding to event property '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...` + `\nIf '${name}' is a directive input, make sure the directive is imported by the` + ` current module.`; throw new RuntimeError(RuntimeErrorCode.INVALID_EVENT_BINDING, errorMessage); } } export function validateAgainstEventAttributes(name: string) { if (name.toLowerCase().startsWith('on')) { const errorMessage = `Binding to event attribute '${name}' is disallowed for security reasons, ` + `please use (${name.slice(2)})=...`; throw new RuntimeError(RuntimeErrorCode.INVALID_EVENT_BINDING, errorMessage); } } function getSanitizer(): Sanitizer | null { const lView = getLView(); return lView && lView[ENVIRONMENT].sanitizer; }
{ "end_byte": 10747, "start_byte": 8386, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/sanitization.ts" }
angular/packages/core/src/sanitization/html_sanitizer.ts_0_5081
/** * @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 {XSS_SECURITY_URL} from '../error_details_base_url'; import {TrustedHTML} from '../util/security/trusted_type_defs'; import {trustedHTMLFromString} from '../util/security/trusted_types'; import {getInertBodyHelper, InertBodyHelper} from './inert_body'; import {_sanitizeUrl} from './url_sanitizer'; function tagSet(tags: string): {[k: string]: boolean} { const res: {[k: string]: boolean} = {}; for (const t of tags.split(',')) res[t] = true; return res; } function merge(...sets: {[k: string]: boolean}[]): {[k: string]: boolean} { const res: {[k: string]: boolean} = {}; for (const s of sets) { for (const v in s) { if (s.hasOwnProperty(v)) res[v] = true; } } return res; } // Good source of info about elements and attributes // https://html.spec.whatwg.org/#semantics // https://simon.html5.org/html-elements // Safe Void Elements - HTML5 // https://html.spec.whatwg.org/#void-elements const VOID_ELEMENTS = tagSet('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // https://html.spec.whatwg.org/#optional-tags const OPTIONAL_END_TAG_BLOCK_ELEMENTS = tagSet('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'); const OPTIONAL_END_TAG_INLINE_ELEMENTS = tagSet('rp,rt'); const OPTIONAL_END_TAG_ELEMENTS = merge( OPTIONAL_END_TAG_INLINE_ELEMENTS, OPTIONAL_END_TAG_BLOCK_ELEMENTS, ); // Safe Block Elements - HTML5 const BLOCK_ELEMENTS = merge( OPTIONAL_END_TAG_BLOCK_ELEMENTS, tagSet( 'address,article,' + 'aside,blockquote,caption,center,del,details,dialog,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,main,map,menu,nav,ol,pre,section,summary,table,ul', ), ); // Inline Elements - HTML5 const INLINE_ELEMENTS = merge( OPTIONAL_END_TAG_INLINE_ELEMENTS, tagSet( 'a,abbr,acronym,audio,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,picture,q,ruby,rp,rt,s,' + 'samp,small,source,span,strike,strong,sub,sup,time,track,tt,u,var,video', ), ); export const VALID_ELEMENTS = merge( VOID_ELEMENTS, BLOCK_ELEMENTS, INLINE_ELEMENTS, OPTIONAL_END_TAG_ELEMENTS, ); // Attributes that have href and hence need to be sanitized export const URI_ATTRS = tagSet('background,cite,href,itemtype,longdesc,poster,src,xlink:href'); const HTML_ATTRS = tagSet( 'abbr,accesskey,align,alt,autoplay,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,' + 'compact,controls,coords,datetime,default,dir,download,face,headers,height,hidden,hreflang,hspace,' + 'ismap,itemscope,itemprop,kind,label,lang,language,loop,media,muted,nohref,nowrap,open,preload,rel,rev,role,rows,rowspan,rules,' + 'scope,scrolling,shape,size,sizes,span,srclang,srcset,start,summary,tabindex,target,title,translate,type,usemap,' + 'valign,value,vspace,width', ); // Accessibility attributes as per WAI-ARIA 1.1 (W3C Working Draft 14 December 2018) const ARIA_ATTRS = tagSet( 'aria-activedescendant,aria-atomic,aria-autocomplete,aria-busy,aria-checked,aria-colcount,aria-colindex,' + 'aria-colspan,aria-controls,aria-current,aria-describedby,aria-details,aria-disabled,aria-dropeffect,' + 'aria-errormessage,aria-expanded,aria-flowto,aria-grabbed,aria-haspopup,aria-hidden,aria-invalid,' + 'aria-keyshortcuts,aria-label,aria-labelledby,aria-level,aria-live,aria-modal,aria-multiline,' + 'aria-multiselectable,aria-orientation,aria-owns,aria-placeholder,aria-posinset,aria-pressed,aria-readonly,' + 'aria-relevant,aria-required,aria-roledescription,aria-rowcount,aria-rowindex,aria-rowspan,aria-selected,' + 'aria-setsize,aria-sort,aria-valuemax,aria-valuemin,aria-valuenow,aria-valuetext', ); // NB: This currently consciously doesn't support SVG. SVG sanitization has had several security // issues in the past, so it seems safer to leave it out if possible. If support for binding SVG via // innerHTML is required, SVG attributes should be added here. // NB: Sanitization does not allow <form> elements or other active elements (<button> etc). Those // can be sanitized, but they increase security surface area without a legitimate use case, so they // are left out here. export const VALID_ATTRS = merge(URI_ATTRS, HTML_ATTRS, ARIA_ATTRS); // Elements whose content should not be traversed/preserved, if the elements themselves are invalid. // // Typically, `<invalid>Some content</invalid>` would traverse (and in this case preserve) // `Some content`, but strip `invalid-element` opening/closing tags. For some elements, though, we // don't want to preserve the content, if the elements themselves are going to be removed. const SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS = tagSet('script,style,template'); /** * SanitizingHtmlSerializer serializes a DOM fragment, stripping out any unsafe elements and unsafe * attributes. */
{ "end_byte": 5081, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/html_sanitizer.ts" }
angular/packages/core/src/sanitization/html_sanitizer.ts_5082_13334
class SanitizingHtmlSerializer { // Explicitly track if something was stripped, to avoid accidentally warning of sanitization just // because characters were re-encoded. public sanitizedSomething = false; private buf: string[] = []; sanitizeChildren(el: Element): string { // This cannot use a TreeWalker, as it has to run on Angular's various DOM adapters. // However this code never accesses properties off of `document` before deleting its contents // again, so it shouldn't be vulnerable to DOM clobbering. let current: Node = el.firstChild!; let traverseContent = true; let parentNodes = []; while (current) { if (current.nodeType === Node.ELEMENT_NODE) { traverseContent = this.startElement(current as Element); } else if (current.nodeType === Node.TEXT_NODE) { this.chars(current.nodeValue!); } else { // Strip non-element, non-text nodes. this.sanitizedSomething = true; } if (traverseContent && current.firstChild) { // Push current node to the parent stack before entering its content. parentNodes.push(current); current = getFirstChild(current)!; continue; } while (current) { // Leaving the element. // Walk up and to the right, closing tags as we go. if (current.nodeType === Node.ELEMENT_NODE) { this.endElement(current as Element); } let next = getNextSibling(current)!; if (next) { current = next; break; } // There was no next sibling, walk up to the parent node (extract it from the stack). current = parentNodes.pop()!; } } return this.buf.join(''); } /** * Sanitizes an opening element tag (if valid) and returns whether the element's contents should * be traversed. Element content must always be traversed (even if the element itself is not * valid/safe), unless the element is one of `SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS`. * * @param element The element to sanitize. * @return True if the element's contents should be traversed. */ private startElement(element: Element): boolean { const tagName = getNodeName(element).toLowerCase(); if (!VALID_ELEMENTS.hasOwnProperty(tagName)) { this.sanitizedSomething = true; return !SKIP_TRAVERSING_CONTENT_IF_INVALID_ELEMENTS.hasOwnProperty(tagName); } this.buf.push('<'); this.buf.push(tagName); const elAttrs = element.attributes; for (let i = 0; i < elAttrs.length; i++) { const elAttr = elAttrs.item(i); const attrName = elAttr!.name; const lower = attrName.toLowerCase(); if (!VALID_ATTRS.hasOwnProperty(lower)) { this.sanitizedSomething = true; continue; } let value = elAttr!.value; // TODO(martinprobst): Special case image URIs for data:image/... if (URI_ATTRS[lower]) value = _sanitizeUrl(value); this.buf.push(' ', attrName, '="', encodeEntities(value), '"'); } this.buf.push('>'); return true; } private endElement(current: Element) { const tagName = getNodeName(current).toLowerCase(); if (VALID_ELEMENTS.hasOwnProperty(tagName) && !VOID_ELEMENTS.hasOwnProperty(tagName)) { this.buf.push('</'); this.buf.push(tagName); this.buf.push('>'); } } private chars(chars: string) { this.buf.push(encodeEntities(chars)); } } /** * Verifies whether a given child node is a descendant of a given parent node. * It may not be the case when properties like `.firstChild` are clobbered and * accessing `.firstChild` results in an unexpected node returned. */ function isClobberedElement(parentNode: Node, childNode: Node): boolean { return ( (parentNode.compareDocumentPosition(childNode) & Node.DOCUMENT_POSITION_CONTAINED_BY) !== Node.DOCUMENT_POSITION_CONTAINED_BY ); } /** * Retrieves next sibling node and makes sure that there is no * clobbering of the `nextSibling` property happening. */ function getNextSibling(node: Node): Node | null { const nextSibling = node.nextSibling; // Make sure there is no `nextSibling` clobbering: navigating to // the next sibling and going back to the previous one should result // in the original node. if (nextSibling && node !== nextSibling.previousSibling) { throw clobberedElementError(nextSibling); } return nextSibling; } /** * Retrieves first child node and makes sure that there is no * clobbering of the `firstChild` property happening. */ function getFirstChild(node: Node): Node | null { const firstChild = node.firstChild; if (firstChild && isClobberedElement(node, firstChild)) { throw clobberedElementError(firstChild); } return firstChild; } /** Gets a reasonable nodeName, even for clobbered nodes. */ export function getNodeName(node: Node): string { const nodeName = node.nodeName; // If the property is clobbered, assume it is an `HTMLFormElement`. return typeof nodeName === 'string' ? nodeName : 'FORM'; } function clobberedElementError(node: Node) { return new Error( `Failed to sanitize html because the element is clobbered: ${(node as Element).outerHTML}`, ); } // Regular Expressions for parsing tags and attributes const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // ! to ~ is the ASCII range. const NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g; /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value */ function encodeEntities(value: string) { return value .replace(/&/g, '&amp;') .replace(SURROGATE_PAIR_REGEXP, function (match: string) { const hi = match.charCodeAt(0); const low = match.charCodeAt(1); return '&#' + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ';'; }) .replace(NON_ALPHANUMERIC_REGEXP, function (match: string) { return '&#' + match.charCodeAt(0) + ';'; }) .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } let inertBodyHelper: InertBodyHelper; /** * Sanitizes the given unsafe, untrusted HTML fragment, and returns HTML text that is safe to add to * the DOM in a browser environment. */ export function _sanitizeHtml(defaultDoc: any, unsafeHtmlInput: string): TrustedHTML | string { let inertBodyElement: HTMLElement | null = null; try { inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc); // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime). let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : ''; inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml); // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous. let mXSSAttempts = 5; let parsedHtml = unsafeHtml; do { if (mXSSAttempts === 0) { throw new Error('Failed to sanitize html because the input is unstable'); } mXSSAttempts--; unsafeHtml = parsedHtml; parsedHtml = inertBodyElement!.innerHTML; inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml); } while (unsafeHtml !== parsedHtml); const sanitizer = new SanitizingHtmlSerializer(); const safeHtml = sanitizer.sanitizeChildren( (getTemplateContent(inertBodyElement!) as Element) || inertBodyElement, ); if ((typeof ngDevMode === 'undefined' || ngDevMode) && sanitizer.sanitizedSomething) { console.warn(`WARNING: sanitizing HTML stripped some content, see ${XSS_SECURITY_URL}`); } return trustedHTMLFromString(safeHtml); } finally { // In case anything goes wrong, clear out inertElement to reset the entire DOM structure. if (inertBodyElement) { const parent = getTemplateContent(inertBodyElement) || inertBodyElement; while (parent.firstChild) { parent.firstChild.remove(); } } } } export function getTemplateContent(el: Node): Node | null { return 'content' in (el as any) /** Microsoft/TypeScript#21517 */ && isTemplateElement(el) ? el.content : null; }
{ "end_byte": 13334, "start_byte": 5082, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/html_sanitizer.ts" }
angular/packages/core/src/sanitization/html_sanitizer.ts_13335_13476
function isTemplateElement(el: Node): el is HTMLTemplateElement { return el.nodeType === Node.ELEMENT_NODE && el.nodeName === 'TEMPLATE'; }
{ "end_byte": 13476, "start_byte": 13335, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/html_sanitizer.ts" }
angular/packages/core/src/sanitization/url_sanitizer.ts_0_2040
/** * @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 {XSS_SECURITY_URL} from '../error_details_base_url'; /** * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation * contexts. * * This regular expression matches a subset of URLs that will not cause script * execution if used in URL context within a HTML document. Specifically, this * regular expression matches if: * (1) Either a protocol that is not javascript:, and that has valid characters * (alphanumeric or [+-.]). * (2) or no protocol. A protocol must be followed by a colon. The below * allows that by allowing colons only after one of the characters [/?#]. * A colon after a hash (#) must be in the fragment. * Otherwise, a colon after a (?) must be in a query. * Otherwise, a colon after a single solidus (/) must be in a path. * Otherwise, a colon after a double solidus (//) must be in the authority * (before port). * * The pattern disallows &, used in HTML entity declarations before * one of the characters in [/?#]. This disallows HTML entities used in the * protocol name, which should never happen, e.g. "h&#116;tp" for "http". * It also disallows HTML entities in the first path part of a relative path, * e.g. "foo&lt;bar/baz". Our existing escaping functions should not produce * that. More importantly, it disallows masking of a colon, * e.g. "javascript&#58;...". * * This regular expression was taken from the Closure sanitization library. */ const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:\/?#]*(?:[\/?#]|$))/i; export function _sanitizeUrl(url: string): string { url = String(url); if (url.match(SAFE_URL_PATTERN)) return url; if (typeof ngDevMode === 'undefined' || ngDevMode) { console.warn(`WARNING: sanitizing unsafe URL value ${url} (see ${XSS_SECURITY_URL})`); } return 'unsafe:' + url; }
{ "end_byte": 2040, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/url_sanitizer.ts" }
angular/packages/core/src/sanitization/readme.md_0_548
# Sanitization This folder contains sanitization related code. ## History It used to be that sanitization related code used to be in `@angular/platform-browser` since it is platform related. While this is true, in practice the compiler schema is permanently tied to the DOM and hence the fact that sanitizer could in theory be replaced is not used in practice. In order to better support tree shaking we need to be able to refer to the sanitization functions from the Ivy code. For this reason the code has been moved into the `@angular/core`.
{ "end_byte": 548, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/readme.md" }
angular/packages/core/src/sanitization/inert_body.ts_0_3422
/** * @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 {trustedHTMLFromString} from '../util/security/trusted_types'; /** * This helper is used to get hold of an inert tree of DOM elements containing dirty HTML * that needs sanitizing. * Depending upon browser support we use one of two strategies for doing this. * Default: DOMParser strategy * Fallback: InertDocument strategy */ export function getInertBodyHelper(defaultDoc: Document): InertBodyHelper { const inertDocumentHelper = new InertDocumentHelper(defaultDoc); return isDOMParserAvailable() ? new DOMParserHelper(inertDocumentHelper) : inertDocumentHelper; } export interface InertBodyHelper { /** * Get an inert DOM element containing DOM created from the dirty HTML string provided. */ getInertBodyElement: (html: string) => HTMLElement | null; } /** * Uses DOMParser to create and fill an inert body element. * This is the default strategy used in browsers that support it. */ class DOMParserHelper implements InertBodyHelper { constructor(private inertDocumentHelper: InertBodyHelper) {} getInertBodyElement(html: string): HTMLElement | null { // We add these extra elements to ensure that the rest of the content is parsed as expected // e.g. leading whitespace is maintained and tags like `<meta>` do not get hoisted to the // `<head>` tag. Note that the `<body>` tag is closed implicitly to prevent unclosed tags // in `html` from consuming the otherwise explicit `</body>` tag. html = '<body><remove></remove>' + html; try { const body = new window.DOMParser().parseFromString( trustedHTMLFromString(html) as string, 'text/html', ).body as HTMLBodyElement; if (body === null) { // In some browsers (e.g. Mozilla/5.0 iPad AppleWebKit Mobile) the `body` property only // becomes available in the following tick of the JS engine. In that case we fall back to // the `inertDocumentHelper` instead. return this.inertDocumentHelper.getInertBodyElement(html); } body.firstChild?.remove(); return body; } catch { return null; } } } /** * Use an HTML5 `template` element to create and fill an inert DOM element. * This is the fallback strategy if the browser does not support DOMParser. */ class InertDocumentHelper implements InertBodyHelper { private inertDocument: Document; constructor(private defaultDoc: Document) { this.inertDocument = this.defaultDoc.implementation.createHTMLDocument('sanitization-inert'); } getInertBodyElement(html: string): HTMLElement | null { const templateEl = this.inertDocument.createElement('template'); templateEl.innerHTML = trustedHTMLFromString(html) as string; return templateEl; } } /** * We need to determine whether the DOMParser exists in the global context and * supports parsing HTML; HTML parsing support is not as wide as other formats, see * https://developer.mozilla.org/en-US/docs/Web/API/DOMParser#Browser_compatibility. * * @suppress {uselessCode} */ export function isDOMParserAvailable() { try { return !!new window.DOMParser().parseFromString( trustedHTMLFromString('') as string, 'text/html', ); } catch { return false; } }
{ "end_byte": 3422, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/inert_body.ts" }
angular/packages/core/src/sanitization/security.ts_0_626
/** * @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 */ /** * A SecurityContext marks a location that has dangerous security implications, e.g. a DOM property * like `innerHTML` that could cause Cross Site Scripting (XSS) security bugs when improperly * handled. * * See DomSanitizer for more details on security in Angular applications. * * @publicApi */ export enum SecurityContext { NONE = 0, HTML = 1, STYLE = 2, SCRIPT = 3, URL = 4, RESOURCE_URL = 5, }
{ "end_byte": 626, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/security.ts" }
angular/packages/core/src/sanitization/bypass.ts_0_6279
/** * @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 {XSS_SECURITY_URL} from '../error_details_base_url'; export const enum BypassType { Url = 'URL', Html = 'HTML', ResourceUrl = 'ResourceURL', Script = 'Script', Style = 'Style', } /** * Marker interface for a value that's safe to use in a particular context. * * @publicApi */ export interface SafeValue {} /** * Marker interface for a value that's safe to use as HTML. * * @publicApi */ export interface SafeHtml extends SafeValue {} /** * Marker interface for a value that's safe to use as style (CSS). * * @publicApi */ export interface SafeStyle extends SafeValue {} /** * Marker interface for a value that's safe to use as JavaScript. * * @publicApi */ export interface SafeScript extends SafeValue {} /** * Marker interface for a value that's safe to use as a URL linking to a document. * * @publicApi */ export interface SafeUrl extends SafeValue {} /** * Marker interface for a value that's safe to use as a URL to load executable code from. * * @publicApi */ export interface SafeResourceUrl extends SafeValue {} abstract class SafeValueImpl implements SafeValue { constructor(public changingThisBreaksApplicationSecurity: string) {} abstract getTypeName(): string; toString() { return ( `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` + ` (see ${XSS_SECURITY_URL})` ); } } class SafeHtmlImpl extends SafeValueImpl implements SafeHtml { override getTypeName() { return BypassType.Html; } } class SafeStyleImpl extends SafeValueImpl implements SafeStyle { override getTypeName() { return BypassType.Style; } } class SafeScriptImpl extends SafeValueImpl implements SafeScript { override getTypeName() { return BypassType.Script; } } class SafeUrlImpl extends SafeValueImpl implements SafeUrl { override getTypeName() { return BypassType.Url; } } class SafeResourceUrlImpl extends SafeValueImpl implements SafeResourceUrl { override getTypeName() { return BypassType.ResourceUrl; } } export function unwrapSafeValue(value: SafeValue): string; export function unwrapSafeValue<T>(value: T): T; export function unwrapSafeValue<T>(value: T | SafeValue): T { return value instanceof SafeValueImpl ? (value.changingThisBreaksApplicationSecurity as any as T) : (value as any as T); } export function allowSanitizationBypassAndThrow( value: any, type: BypassType.Html, ): value is SafeHtml; export function allowSanitizationBypassAndThrow( value: any, type: BypassType.ResourceUrl, ): value is SafeResourceUrl; export function allowSanitizationBypassAndThrow( value: any, type: BypassType.Script, ): value is SafeScript; export function allowSanitizationBypassAndThrow( value: any, type: BypassType.Style, ): value is SafeStyle; export function allowSanitizationBypassAndThrow(value: any, type: BypassType.Url): value is SafeUrl; export function allowSanitizationBypassAndThrow(value: any, type: BypassType): boolean; export function allowSanitizationBypassAndThrow(value: any, type: BypassType): boolean { const actualType = getSanitizationBypassType(value); if (actualType != null && actualType !== type) { // Allow ResourceURLs in URL contexts, they are strictly more trusted. if (actualType === BypassType.ResourceUrl && type === BypassType.Url) return true; throw new Error(`Required a safe ${type}, got a ${actualType} (see ${XSS_SECURITY_URL})`); } return actualType === type; } export function getSanitizationBypassType(value: any): BypassType | null { return (value instanceof SafeValueImpl && (value.getTypeName() as BypassType)) || null; } /** * Mark `html` string as trusted. * * This function wraps the trusted string in `String` and brands it in a way which makes it * recognizable to {@link htmlSanitizer} to be trusted implicitly. * * @param trustedHtml `html` string which needs to be implicitly trusted. * @returns a `html` which has been branded to be implicitly trusted. */ export function bypassSanitizationTrustHtml(trustedHtml: string): SafeHtml { return new SafeHtmlImpl(trustedHtml); } /** * Mark `style` string as trusted. * * This function wraps the trusted string in `String` and brands it in a way which makes it * recognizable to {@link styleSanitizer} to be trusted implicitly. * * @param trustedStyle `style` string which needs to be implicitly trusted. * @returns a `style` hich has been branded to be implicitly trusted. */ export function bypassSanitizationTrustStyle(trustedStyle: string): SafeStyle { return new SafeStyleImpl(trustedStyle); } /** * Mark `script` string as trusted. * * This function wraps the trusted string in `String` and brands it in a way which makes it * recognizable to {@link scriptSanitizer} to be trusted implicitly. * * @param trustedScript `script` string which needs to be implicitly trusted. * @returns a `script` which has been branded to be implicitly trusted. */ export function bypassSanitizationTrustScript(trustedScript: string): SafeScript { return new SafeScriptImpl(trustedScript); } /** * Mark `url` string as trusted. * * This function wraps the trusted string in `String` and brands it in a way which makes it * recognizable to {@link urlSanitizer} to be trusted implicitly. * * @param trustedUrl `url` string which needs to be implicitly trusted. * @returns a `url` which has been branded to be implicitly trusted. */ export function bypassSanitizationTrustUrl(trustedUrl: string): SafeUrl { return new SafeUrlImpl(trustedUrl); } /** * Mark `url` string as trusted. * * This function wraps the trusted string in `String` and brands it in a way which makes it * recognizable to {@link resourceUrlSanitizer} to be trusted implicitly. * * @param trustedResourceUrl `url` string which needs to be implicitly trusted. * @returns a `url` which has been branded to be implicitly trusted. */ export function bypassSanitizationTrustResourceUrl(trustedResourceUrl: string): SafeResourceUrl { return new SafeResourceUrlImpl(trustedResourceUrl); }
{ "end_byte": 6279, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/bypass.ts" }
angular/packages/core/src/sanitization/sanitizer.ts_0_715
/** * @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 {SecurityContext} from './security'; /** * Sanitizer is used by the views to sanitize potentially dangerous values. * * @publicApi */ export abstract class Sanitizer { abstract sanitize(context: SecurityContext, value: {} | string | null): string | null; /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: Sanitizer, providedIn: 'root', factory: () => null, }); }
{ "end_byte": 715, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/sanitizer.ts" }