Commit graph

672 commits

Author SHA1 Message Date
Miles Malerba
00938699b8 refactor(compiler-cli): handle parentheses in the template pipeline (#60169)
Now that the expression AST contains parenthesized expressions, this
refactors the template pipeline to strip out the ones we don't need.

PR Close #60169
2025-03-10 09:53:10 -07:00
Miles Malerba
d4cfeb0a86 refactor(compiler): add parenthesized expressions to experssion ast (#60169)
Following up on #60127 which added the concept of a parenthesized
expression to the output AST, this does the same for the expression AST.

PR Close #60169
2025-03-10 09:53:10 -07:00
Miles Malerba
51b8ff23ce feat(compiler): support tagged template literals in expressions (#59947)
Adds support for using tagged template literals in Angular templates.

Ex:
```
@Component({
  template: '{{ greet`Hello, ${name()}` }}'
})
export class MyComp {
  name = input();

  greet(strings: TemplateStringsArray, name: string) {
    return strings[0] + name + strings[1] + '!';
  }
}
```

PR Close #59947
2025-02-28 19:53:33 +00:00
Miles Malerba
f2d5cf7edd feat(compiler): support exponentiation operator in templates (#59894)
Adds support for the exponentiation (`**`) operator in templates

Ex:
```
@Component {
  template: '{{2 ** 3}}'
}
```

PR Close #59894
2025-02-25 11:03:37 -05:00
Miles Malerba
0361c2d81f feat(compiler): support void operator in templates (#59894)
Add support for the `void` operator in templates and host bindings.

This is useful when binding a listener that may return `false` and
unintentionally prevent the default event behavior.

Ex:
```
@Directive({
  host: { '(mousedown)': 'void handleMousedown()' }
})
```

BREAKING CHANGE: `void` in an expression now refers to the operator

Previously an expression in the template like `{{void}}` referred to a
property on the component class. After this change it now refers to the
`void` operator, which would make the above example invalid. If you have
existing expressions that need to refer to a property named `void`,
change the expression to use `this.void` instead: `{{this.void}}`.

PR Close #59894
2025-02-25 11:03:37 -05:00
Kristiyan Kostadinov
eb7e765e2f refactor(compiler): produce AST for template literals (#59230)
Updates the compiler to parse the template literal tokens into the new `TemplateLiteral` and `TemplateLiteralElement` AST nodes.

PR Close #59230
2025-01-21 12:04:52 -08:00
Kristiyan Kostadinov
353005b97f refactor(compiler): tokenize template literals (#59230)
Reworks the lexer to produce tokens for template literal expressions.

PR Close #59230
2025-01-21 12:04:52 -08:00
Kristiyan Kostadinov
98f820737b fix(compiler): handle :host-context with comma-separated child selector (#59276)
Both `:host` and `:host-context` work by looking for a specific character sequence that is terminated by `,` or `{` and replacing selectors inside of it with scoped versions. This is implemented as a regex which isn't aware of things like nested selectors. Normally this is fine for `:host`, because each `:host` produces one scoped selector which doesn't affect any child selectors, however it breaks down with `:host-context` which replaces each instance with two selectors. For example, if we have a selector in the form of `:host-context(.foo) a:not(.a, .b)`, the compiler ends up determining that `.a,` is the end selector and produces `.foo[a-host] a[contenta]:not(.a, .foo [a-host] a[contenta]:not(.a, .b) {}`.

These changes resolve the issue by splitting the CSS alogn top-level commas, processing the `:host-context` in them individually, and stiching the CSS back together.

PR Close #59276
2025-01-21 09:11:16 -08:00
Kristiyan Kostadinov
915593ad25 refactor(compiler): fix typo in method name (#59479)
Fixes a typo in the `AstVisitor.visitTypeofExpresion` method's name.

PR Close #59479
2025-01-13 10:57:51 -05:00
Kristiyan Kostadinov
ceadd28ea1 fix(compiler): allow $any in two-way bindings (#59362)
Some time ago we narrowed down the expressions we support in two-way bindings, because in most cases any apart from property reads doesn't make sense. This ended up preventing users from using `$any` in the binding since it's considered a function call.

These changes update the validation logic to allow `$any`.

Fixes #51165.

PR Close #59362
2025-01-06 17:25:25 +00:00
Sandor Drieënhuizen
e5866eed2e refactor(compiler): incorrect spelling in for loop parse error message (#59289)
'parameter' was spelled as 'paramater'.

Fix spelling error in Update r3_control_flow.ts

'parameter' was spelled as 'paramater'.

Fix spelling error in r3_template_transform_spec.ts

'parameter' was spelled as 'paramater'.

PR Close #59289
2025-01-06 16:18:15 +00:00
hawkgs
0513fbc9fc docs: set syntax highlighting of code examples MD code blocks (#59026)
Set the syntax highlighting based on the code examples' language.

PR Close #59026
2024-12-04 17:30:28 +01:00
Georgy Serga
549a00d18b fix(compiler): fix multiline selectors (#58681)
multiline selectors where not correctly recognized by the regexp, fix it to fetch newlines as well

Fixes #58399

PR Close #58681
2024-11-15 11:30:27 +01:00
Georgy Serga
58a84b2f79 fix(compiler): resolve :host:host-context(.foo) (#58681)
fix results which had to parse several `-shadowcsshost-no-combinator` occurrences in a single selector

PR Close #58681
2024-11-15 11:30:27 +01:00
Georgy Serga
9587437e60 fix(compiler): transform chained pseudo-selectors (#58681)
fix transformation logic for `:where` and `:is` pseudo-selectors
when these selectors were used in a chain. results were often broken,
the last letter of the selector was incorrectly trimmed.
see tests for examples

Fixes #58226

PR Close #58681
2024-11-15 11:30:27 +01:00
Georgy Serga
70e800ecec fix(compiler): fix :host parsing in pseudo-selectors (#58681)
fix several use-cases where `:host` was used in or around pseudo-selectors
- `:host` followed by a comma inside pseudo-selectors
- `:host` outside of pseudo-selectors when another `:host` is present within
see tests for examples

PR Close #58681
2024-11-15 11:30:27 +01:00
Kristiyan Kostadinov
5ca48e802b refactor(compiler): remove unused field from output AST (#58444)
The `ExternalReference.runtime` field wasn't being used anywhere.

PR Close #58444
2024-11-01 14:32:57 +00:00
Brandon Roberts
992410e928 fix(compiler): add more specific matcher for hydrate never block (#58360)
Fixes an issue where additional characters were allowed afte the "hydrate never" block.

Closes #58358

PR Close #58360
2024-10-28 12:35:11 -07:00
Kristiyan Kostadinov
5971037613 test(compiler): update failing tests (#58217)
Fixes some tests that started failing, because #58154 made it so placeholder-only messages are extracted while #58176 added some tests that only contain placeholders.

PR Close #58217
2024-10-16 09:47:10 +00:00
Matthieu Riegler
0c9d721ac1 feat(compiler): add support for the typeof keyword in template expressions. (#58183)
This commit adds the support for `typeof` in template expressions like interpolation, bindings, control flow blocks etc.

PR Close #58183
2024-10-16 07:31:00 +00:00
Doug Parker
6d33ab5afe refactor(compiler): remove preservePlaceholders (#58176)
While effective, `preservePlaceholders` unfortunately is not viable in google3 at the moment due to some complexities with how TC extracts messages. Therefore this feature is being removed in favor of whitespace trimming of expressions, which is viable for TC and provides most of the same benefit.

This is a partial revert of dab722f9c8.

PR Close #58176
2024-10-16 06:42:37 +00:00
Doug Parker
6c126d5c5d refactor(compiler): trim insignificant whitespace in expressions when preserveSignificantWhitespace === false. (#58176)
This parses and reserializes expressions to normalize their whitespace formatting and make them more durable to insignificant changes in whitespace which might otherwise alter message IDs despite no translator-meaningful change being made.

PR Close #58176
2024-10-16 06:42:37 +00:00
Doug Parker
474163cd1d refactor(compiler): add expression serializer (#58176)
This serializes the expression AST back into a string. This is useful to normalize whitespace in expressions so i18n messages are not affected by insignificant changes (such as going from `{{ foo }}` to `{{\n  foo\n}}`).

PR Close #58176
2024-10-16 06:42:37 +00:00
Matthieu Riegler
09df589e31 refactor(core): Migrate all packages with the explicit-standalone-flag schematic. (#58160)
All components, directives and pipes will now use standalone as default.
Non-standalone decorators have now `standalone: false`.

PR Close #58160
2024-10-14 14:58:57 +00:00
Doug Parker
ba4340875a fix(compiler): ignore placeholder-only i18n messages (#58154)
Message which only contain a single placeholder cannot be translated, there is no static text to be translated. Therefore these messages can be skipped and shouldn't be extracted at all.

Ideally, Angular would throw an error if a message is only a placeholder, since it should not contain an `i18n` attribute at all. However this would be a breaking change and require a migration which isn't in scope right now. We can explore converting this to a hard error sometime in the future.

PR Close #58154
2024-10-13 16:48:34 +00:00
Georgy Serga
46a6324c82 fix(compiler): scope :host-context inside pseudo selectors, do not decrease specificity (#57796)
parse constructions like `:where(:host-context(.foo))` correctly
revert logic which lead to decreased specificity if `:where` was applied
to another selector, for example `div` is transformed to `div[contenta]`
with specificity of (0,1,1) so `div:where(.foo)` should not decrease it
leading to `div[contenta]:where(.foo)` with the same specificity (0,1,1)
instead of `div:where(.foo[contenta])` with specificity equal to (0,0,1)

PR Close #57796
2024-10-10 08:13:22 +00:00
Georgy Serga
69529d8873 fix(compiler): fix parsing of the :host-context with pseudo selectors (#57796)
fix regexp which is used to test for host inside pseudo selectors

PR Close #57796
2024-10-10 08:13:22 +00:00
Georgy Serga
2374b87b64 fix(compiler): preserve attributes attached to :host selector (#57796)
keep attributes used to scope :host selectors

PR Close #57796
2024-10-10 08:13:22 +00:00
Georgy Serga
e8d1944999 fix(compiler): add multiple :host and nested selectors support (#57796)
add support for nested and deeply nested (up to three levels) selectors,
parse multiple :host selectors, scope selectors within pseudo functions

PR Close #57796
2024-10-10 08:13:22 +00:00
Georgy Serga
82144b6d63 fix(compiler): allow combinators inside pseudo selectors (#57796)
allow css combinators within pseudo selector functions, parsing those
correctly. Similarly to previous version, don't break selectors
into part if combinators are within parenthesis, for example
`:where(.one > .two)`

PR Close #57796
2024-10-10 08:13:22 +00:00
Georgy Serga
bc5f1175e9 fix(compiler): transform pseudo selectors correctly for the encapsulated view (#57796)
fix scoping and transforming logic of the `shimCssText` for the
components with encapsulated view:
- add support for pseudo selector functions
- apply content scoping for inner selectors of `:is()` and `:where()`
- allow multiple comma separated selectors inside pseudo selectors

Fixes #45686

PR Close #57796
2024-10-10 08:13:21 +00:00
Dylan Hunn
09f589f000 fix(compiler): this.a should always refer to class property a (#55183)
Consider a template with a context variable `a`:
```
<ng-template let-a>{{this.a}}</ng-template>
```

t push -fAn interpolation inside that template to `this.a` should intuitively read the class variable `a`. However, today, it refers to the context variable `a`, both in the TCB and the generated code.

In this commit, the above interpolation now refers to the class field `a`.

BREAKING CHANGE: `this.foo` property reads no longer refer to template context variables. If you intended to read the template variable, do not use `this.`.
Fixes #55115

PR Close #55183
2024-10-08 16:02:18 +00:00
Joey Perrott
9dbe6fc18b refactor: update license text to point to angular.dev (#57901)
Update license text to point to angular.dev instead of angular.io

PR Close #57901
2024-09-24 15:33:00 +02:00
Kristiyan Kostadinov
39098f3a9b refactor(compiler): finalize hydrate syntax (#57831)
Finalizes compiler implementation of the new `hydrate` triggers by:
* Reworking the logic that was depending on the `hydrateSpan` to distinguish hydrate triggers from non-hydrate triggers.
* Fixing that the `hydrate when` trigger didn't have a `hydrateSpan`.
* Adding an error if a parameter is passed into a `hydrate` trigger.
* Add an error if other `hydrate` triggers are used with `hydrate never`.
* Replacing the `prefetch` and `hydrate` flags in the template pipeline with a `modifiers` field.
* Fixing an error that was being thrown when reifying `hydrate` triggers in the pipeline.
* Adding quick info support for the `hydrate` keyword in the language service.
* Adding some tests for the new logic.

PR Close #57831
2024-09-17 11:05:17 +02:00
Jessica Janiuk
79b54bba9c refactor(compiler): initial integration of hydrate triggers into the compiler (#57831)
Sets up the AST for hydrate triggers.

PR Close #57831
2024-09-17 11:05:17 +02:00
Andrew Kushnir
ca2610fb93 refactor(compiler): extend directive mock to avoid failing at matching logic (#57537)
This commit updates a directive mock instance to include an extra field that a compiler code was expecting, which caused issues while processing elements with local refs and exported directives.

PR Close #57537
2024-08-27 13:23:30 -07:00
Doug Parker
5a0ff41f75 refactor(compiler): ensure context is always provided for WhitespaceVisitor (#56507)
When disabling `i18nPreserveSignificantWhitespaceForLegacyExtraction` I was looking at a test case with ICU messages containing leading and trailing whitespace:

```angular
<div i18n>
  {apples, plural, =other {I have many apples.}}
</div>
```

This would historically generate two messages:

```javascript
const MSG_TMP = goog.getMsg('{apples, plural, =other {I have many apples.}}');
const MSG_FOO = goog.getMsg(' {$ICU} ', { 'ICU': MSG_TMP });
```

But I found that I was getting just one message:

```javascript
const MSG_TMP = goog.getMsg(' {apples, plural, =other {I have many apples.}} ');
```

This is arguably an improvement, but changed the messages and message IDs, which isn't desirable with this option. I eventually traced this back to the `isIcu` initialization in [`i18n_parser.ts`](/packages/compiler/src/i18n/i18n_parser.ts):

```typescript
const context: I18nMessageVisitorContext = {
  isIcu: nodes.length == 1 && nodes[0] instanceof html.Expansion,
  // ...
};
```

[`_I18nVisitor.prototype.visitExpansion`](/packages/compiler/src/i18n/i18n_parser.ts) uses this to decide whether or not to generate a sub-message for a given ICU expansion:

```typescript
if (context.isIcu || context.icuDepth > 0) {
  // Returns an ICU node when:
  // - the message (vs a part of the message) is an ICU message, or
  // - the ICU message is nested.
  const expPh = context.placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
  i18nIcu.expressionPlaceholder = expPh;
  context.placeholderToContent[expPh] = {
    text: icu.switchValue,
    sourceSpan: icu.switchValueSourceSpan,
  };
  return context.visitNodeFn(icu, i18nIcu);
}

// Else returns a placeholder
// ICU placeholders should not be replaced with their original content but with the their
// translations.
// TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
const phName = context.placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
context.placeholderToMessage[phName] = this.toI18nMessage([icu], '', '', '', undefined);
const node = new i18n.IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
return context.visitNodeFn(icu, node);
```

Note that `isIcu` is the key condition between these two cases and depends on whether or not the ICU expansion has any siblings. The introduction of `WhitespaceVisitor` to `I18nMetaVisitor` trims insignificant whitespace, including empty text nodes not adjacent to an ICU expansion (from [`WhitespaceVisitor.prototype.visitText`](/packages/compiler/src/ml_parser/html_whitespaces.ts)):

```typescript
const isNotBlank = text.value.match(NO_WS_REGEXP);
const hasExpansionSibling =
  context && (context.prev instanceof html.Expansion || context.next instanceof html.Expansion);

if (isNotBlank || hasExpansionSibling) {
  // Transform node by trimming it...
  return trimmedNode;
}

return null; // Drop node which is empty and has no ICU expansion sibling.
```

`hasExpansionSibling` was intended to retain empty text nodes leading or trailing an ICU expansion, however `context` was `undefined`, so this check failed and the leading / trailing text nodes were dropped. This resulted in trimming the ICU text by dropping the leading / trailing whitespace nodes. Having only a single ICU expansion with no leading / trailing text nodes caused `_I18nVisitor` to initialize `isIcu` incorrectly and caused it to generate one message instead of two.

`WhitespaceVisitor` is supposed to get this context from `visitAllWithSiblings`. So the fix here is to make sure `WhitespaceVisitor` is always visited via this function which provides the required context. I updated all usage sites to make sure this context is use consistently and implemented the `WhitespaceVisitor.prototype.visit` method to throw when the context is missing to make sure we don't encounter a similar mistake in the future.

Unfortunately this broke one compliance test. Specifically the [`icu_logic/icu_only.js`](/home/douglasparker/Source/ng/packages/compiler-cli/test/compliance/test_cases/r3_view_compiler_i18n/icu_logic/icu_only.js) test which changed from generating:

```javascript
function MyComponent_Template(rf, ctx) {
  if (rf & 1) {
    i0.ɵɵi18n(0, 0);
  }
  // ...
}
```

To now generating:

```javascript
function MyComponent_Template(rf, ctx) {
  if (rf & 1) {
    i0.ɵɵtext(0, " ");
    i0.ɵɵi18n(1, 0);
    i0.ɵɵtext(2, "\n");
  }
  // ...
}
```

This test uses the default value `preserveWhitespaces: false` (`i18nPreserveSignificantWhitespaceForLegacyExtraction` should not affect compiled JS output, we already retain significant whitespace there). So what this indicates to me is that ICU logic is already broken because it's not preserving significant whitespace in this case. My change is probably a bug fix, but one which would affect the compiled runtime, which is not in scope here. The root cause is because using `visitAllWithSiblings` everywhere means the context is retained correctly in this case and the whitespace is leading/trailing an ICU message, therefore it is retained per the logic of `WhitespaceVisitor.prototype.visitText` I mentioned eariler.

To address this, I left one usage of `WhitespaceVisitor` using `html.visitAll` instead of `visitAllWithSiblings` to retain this bug. I has to lossen the assertion I put in `WhitespaceVisitor.prototype.visit` to make this possible, but it should still throw by default when misused, which is the important part.

PR Close #56507
2024-08-27 13:13:56 -07:00
Doug Parker
dab722f9c8 refactor(compiler): add i18nPreserveWhitespaceForLegacyExtraction (#56507)
This configures whether or not to preserve whitespace content when extracting messages from Angular templates in the legacy (View Engine) extraction pipeline.

This includes several bug fixes which unfortunately cannot be landed without changing message IDs in a breaking fashion and are necessary to properly trim whitespace. Instead these bug fixes are included only when the new flag is disabled.

PR Close #56507
2024-08-27 13:13:56 -07:00
Andrew Kushnir
e75e61a637 refactor(compiler): create an internal util method to detect matching directives and pipes (#57466)
This commit adds an internal util method that allows to detect:

* which selectors are matching nodes in a template
* which pipes are present in a template

Both directives and pipes are split into 2 buckets: eagerly used and the ones that might potentially be defer-loaded.

PR Close #57466
2024-08-22 09:04:04 -07:00
Daniel Puckowski
387e1cbf89 fix(compiler): fix CSS animation rule scope (#56800)
It is valid CSS to list keyframe names in an animation declaration only
separating the names with a comma and no whitespace. This is typical of
production builds. Updated a couple of regexes and added a couple of
tests to account for this scenario.

Fixes #53038

PR Close #56800
2024-07-09 09:44:50 +02:00
Kristiyan Kostadinov
0a48d584f2 feat(core): add support for let syntax (#56715)
Enables the new `@let` syntax by default.

`@let` declarations are defined as:
1. The `@let` keyword.
2. Followed by one or more whitespaces.
3. Followed by a valid JavaScript name and zero or more whitespaces.
4. Followed by the `=` symbol and zero or more whitespaces.
5. Followed by an Angular expression which can be multi-line.
6. Terminated by the `;` symbol.

Example usage:
```
@let user = user$ | async;
@let greeting = user ? 'Hello, ' + user.name : 'Loading';
<h1>{{greeting}}</h1>
```

Fixes #15280.

PR Close #56715
2024-06-26 12:37:02 -07:00
Paul Gschwendtner
5162a32de8 refactor(compiler): expose shorthand object metadata in expression AST (#56405)
Whenever we parse object property assignment shorthands in expression
ASTs, the AST will have no information about whether the property read
for the `LiteralMap` is built based on the shorthand or not.

Exposing this information in the AST is useful for migrations as those
might need to decompose the shorthand into its longer form to e.g.
invoke a signal read.

PR Close #56405
2024-06-13 10:12:52 -07:00
Kristiyan Kostadinov
b7fc7fdba9 refactor(compiler): integrate let declarations into the template binder (#56199)
Integrates the let declarations into the template binder which will be used to power the scoping behavior of the new syntax.

PR Close #56199
2024-06-04 17:28:03 +00:00
Kristiyan Kostadinov
9eef041211 refactor(compiler): implement let declarations in render3 ast (#55848)
Introduces a new `LetDeclaration` into the Render3 AST, simiarly to the HTML AST, and adds an initial integration into the various visitors.

PR Close #55848
2024-05-30 14:55:36 +00:00
Kristiyan Kostadinov
1ae06e4fc6 refactor(compiler): implement let declarations in html ast (#55848)
Adds a new `LetDeclaration` node to the AST that captures the `LetStart`, `LetValue` and `LetEnd` tokens into a single node.

PR Close #55848
2024-05-30 14:55:36 +00:00
Kristiyan Kostadinov
62c5b66b41 refactor(compiler): add support for tokenizing let declarations (#55848)
Updates the lexer to produce tokens for `let` declarations. Currently it' behind a flag while the feature is being worked on.

PR Close #55848
2024-05-30 14:55:36 +00:00
Kristiyan Kostadinov
08523ec650 fix(compiler): allow comments between connected blocks (#55966)
Fixes that the logic which looks for connected blocks didn't allow for comments between them.

Fixes #55954.

PR Close #55966
2024-05-21 10:37:58 -07:00
Kristiyan Kostadinov
aa8df1d029 refactor(core): clean up clang comments and workarounds (#55750)
Since we aren't using clang anymore, we can remove the comments and the workarounds that were in place to prevent it from doing the wrong thing.

PR Close #55750
2024-05-13 11:10:36 -07:00
Alan Agius
3e1d6e9d6e fix(compiler): maintain multiline CSS selectors during CSS scoping (#55509)
Previously, multiline selectors were being converted into single lines, resulting in sourcemap disruptions due to shifts in line numbers.

Closes #55508

PR Close #55509
2024-05-06 12:39:50 -07:00
Kristiyan Kostadinov
2e891ad72a fix(compiler): add math elements to schema (#55631)
Fixes that we didn't have the MathML elements in the schema. Note that we can't discover which tag names are available by looking at globally-available classes, because all MathML elements are `MathMLElement` rather than something like `SVGCircleElement`. As such, I ended up having to hardcode the currently-available tags.

Fixes #55608.

PR Close #55631
2024-05-02 11:12:14 -07:00