Commit graph

61 commits

Author SHA1 Message Date
Gerald Monaco
cdfcb779df refactor(core): add internal API to enable i18n hydration (#54784)
Add an internal API to enable and use i18n hydration for testing and development. This helps ensure that we don't accidentally break the current behavior until we are completely ready to roll out i18n support.

PR Close #54784
2024-03-12 11:39:03 -07:00
Matthieu Riegler
b560e02cdf refactor(devtools): Add hydration informations (#53910)
This commit adds hydration informations to the devtools.
* List of hydrated/hydrated components
* Shows hydration overlays
* Shows hydration errors for NG0500, 501 & 502

PR Close #53910
2024-01-30 20:03:14 +00:00
Andrew Kushnir
596b43d631 refactor(core): skip disconnected nodes while computing node path for hydration (#53317)
In certain cases Angular hydration logic can not rely on the order in which elements are present in a template (for example, in content-projection use-cases) and there is a need to serialize a path from one node to another, so that hydration can locate an element on a page. The logic attempts to use an immediate parent element as an anchor and compute the path from it. If it fails - the path is computed starting from the <body> (this is a fallback).

This commit updates the logic to walk up the parents tree if an immediate parent (from a template) is disconnected from the DOM. This helps to shorten the lookup path and make it more stable.

PR Close #53317
2023-12-04 21:44:08 -08:00
Andrew Kushnir
82609d471c fix(core): support swapping hydrated views in @for loops (#53274)
This commit fixes an issue where swapping hydrated views was not possible in the new control flow repeater. The problem was caused by the fact that an internal representation of a view had no indication that hydration is completed and further detaching/attaching should work in a regular (non-hydration) mode. This commit adds a logic that resets a pointer to a dehydrated content and we use this as an indication that the view is swtiched to a regular mode.

Resolves #53163.

PR Close #53274
2023-12-01 10:35:36 -08:00
Andrew Kushnir
4b23221b4e fix(core): support hydration for cases when content is re-projected using ng-template (#53304)
This commit fixes an issue with hydration, which happens when a content is projected in a certain way, leaving host elements non-projected, but the child content projected.

The fix is to detect such situations and add extra annotations to help runtime logic locate those elements at the right locations.

Resolves #53276.

PR Close #53304
2023-12-01 09:12:54 -08:00
Andrew Kushnir
899f6c4a12 fix(core): handle hydration of multiple nodes projected in a single slot (#53270)
This commit updates the logic to handle hydration of multiple nodes projected in a single slot. Currently, in case component nodes are content-projected and their order is changed during the projection, hydration can not find the correct element. With this fix, extra annotation info would be included for such nodes and hydration logic at runtime will use it to locate the right element.

Resolves #53246.

PR Close #53270
2023-11-30 09:16:23 -08:00
Andrew Kushnir
666853f7c2 refactor(core): avoid invoking IntersectionObserver in defer triggers on the server (#52306)
This commit updates the logic to make sure that DOM-specific triggers do not produce errors on the server.

Resolves #52304.

PR Close #52306
2023-10-23 09:28:15 -07:00
Andrew Kushnir
4e4ad5ab2e refactor(core): simplify hydration annotation key (#52207)
This commit drops the `ɵ` symbol from hydration annotation key: `__ɵnghData__` -> `__nghData__`. This helps ensure that there are no UTF8 symbols that might be damaged in case a web server is misconfigured.

Noticed while working on https://github.com/angular/angular/pull/52206.

PR Close #52207
2023-10-16 11:25:57 +02:00
Andrew Kushnir
dbc14eb41d refactor(platform-browser): remove withNoDomReuse function (#52057)
This commit removes the `withNoDomReuse` function to minimize public API. The `withNoDomReuse` function used to disable DOM reuse, which is the main feature of the `provideClientHydration()`.

The `withNoDomReuse()` function was in the "developer preview" mode, so the removal happens without prior deprecation.

BREAKING CHANGE:

The `withNoDomReuse()` function was removed from the public API. If you need to disable hydration, you can exclude the `provideClientHydration()` call from provider list in your application (which would disable hydration features for the entire application) or use `ngSkipHydration` attribute to disable hydration for particular components. See this guide for additional information: https://angular.io/guide/hydration#how-to-skip-hydration-for-particular-components.

PR Close #52057
2023-10-09 13:36:16 -07:00
Kristiyan Kostadinov
43e6fb0606 feat(core): enable block syntax (#51994)
Enables the new `@` block syntax by default by removing the `enabledBlockTypes` flags. There are still some internal flags that allow special use cases to opt out of the block syntax, like during XML parsing and when compiling older libraries (see #51979).

PR Close #51994
2023-10-03 15:26:05 -07:00
Andrew Kushnir
6b6a44c473 refactor(core): add hydration support for built-in for (#51920)
This commit adds hydration support for repeaters (for loops) and empty blocks. The logic looks up a dehydrated view and use this information for hydration. Otherwise, DOM elements for a view are created from scratch.

PR Close #51920
2023-09-29 15:21:21 -07:00
Alan Agius
8413b64a6b refactor(core): add whenStable private API (#51807)
Prior to this change `this.isStable.pipe(first((isStable) => isStable)).toPromise()` had to be done in multiple places across the framework and the Angular CLI see https://github.com/angular/angular-cli/pull/25856#discussion_r1328158846. In the majority of cases an Observable based `isStable` API is not needed. This also removes the need for RXJS operator imports.

PR Close #51807
2023-09-27 10:31:56 -07:00
Andrew Kushnir
7a731c9536 refactor(core): add hydration support for built-in if and switch (#51915)
This commit updates the `if` and `switch` logic to support hydration. The logic attempts to find dehydrated views in containers while processing `if` and `switch` instructions. If a dehydrated is found, its used to further match elements. Otherwise, DOM elements for a view are created from scratch.

PR Close #51915
2023-09-27 10:29:07 -07:00
Kristiyan Kostadinov
8be2c48b7c feat(core): implement new block syntax (#51891)
Switches the syntax for blocks from `{#block}{/block}` to `@block {}` based on the feedback from the community.

Read more about the decision-making process in our blog: https://blog.angular.io/meet-angulars-new-control-flow-a02c6eee7843

The existing block types changed in the following ways:

**Conditional blocks:**
```html
<!-- Before -->
{#if cond}
  Main content
  {:else if otherCond}
    Else if content
  {:else}
    Else content
{/if}

<!-- After -->
@if (cond) {
  Main content
} @else if (otherCond) {
  Else if content
} @else {
  Else content
}
```

**Deferred blocks**
```html
<!-- Before -->
{#defer when isLoaded}
  Main content
  {:loading} Loading...
  {:placeholder} <icon>pending</icon>
  {:error} Failed to load
{/defer}

<!-- After -->
@defer (when isLoaded) {
  Main content
} @loading {
  Loading...
} @placeholder {
  <icon>pending</icon>
} @error {
  Failed to load
}
```

**Switch blocks:**
```html
<!-- Before -->
{#switch value}
  {:case 1}
    One
  {:case 2}
    Two
  {:default}
    Default
{/switch}

<!-- After -->
@switch (value) {
  @case (1) {
    One
  }

  @case (2) {
    Two
  }

  @default {
    Default
  }
}
```

**For loops**
```html
<!-- Before -->
{#for item of items; track item}
  {{item.name}}
  {:empty} No items
{/for}

<!-- After -->
@for (item of items; track item) {
  {{item.name}}
} @empty {
  No items
}
```

PR Close #51891
2023-09-26 09:10:04 -07:00
Andrew Kushnir
1aff106a87 refactor(core): adjust defer block behavior on the server (#51530)
This commit updates the runtime implementation of defer blocks to avoid their triggering on the server. This behavior was described in the RFC (https://github.com/angular/angular/discussions/50716, see "Server Side Rendering Behavior" section): only a placeholder is rendered on the server at this moment. This commit also updates the logic to make sure that the placeholder content is hydrated after SSR.

PR Close #51530
2023-09-01 19:15:16 +00:00
Andrew Kushnir
006577f39c fix(core): handle hydration of view containers that use component hosts as anchors (#51456)
This commit fixes an issue where serialization of a view container fails in case it uses a component host as an anchor. This fix is similar to the fix from #51247, but for cases when we insert a component (that acts as a host for a view container) deeper in a hierarchy.

Resolves #51318.

PR Close #51456
2023-08-29 16:37:50 +00:00
Andrew Kushnir
55965cbf8c fix(core): handle hydration of view containers for root components (#51247)
For cases when a root component also acts as an anchor node for a ViewContainerRef (for example, when ViewContainerRef is injected in a root component), there is a need to serialize information about the component itself, as well as an LContainer that represents this ViewContainerRef. Effectively, we need to serialize 2 pieces of info: (1) hydration info for the root component itself and (2) hydration info for the ViewContainerRef instance (an LContainer). Each piece of information is included into the hydration data (in the TransferState object) separately, thus we end up with 2 ids. Since we only have 1 root element, we encode both bits of info into a single string: ids are separated by the `|` char (e.g. `10|25`, where `10` is the ngh for a component view and 25 is the `ngh` for a root view which holds LContainer).

Previously, we were only including component-related information, thus all the views in the view container remained dehydrated and duplicated (client-rendered from scratch) on the client.

Resolves #51157.

PR Close #51247
2023-08-07 09:24:26 -07:00
Matthieu Riegler
0a38dc3c26 refactor(core): throw an error when hydration marker is missing from DOM (#51170)
non-destructive hydration expects the DOM tree to have the same structure in both places.
With this commit, the app will throw an error if comments are stripped out by the http server (eg by some CDNs).

fixes #51160

PR Close #51170
2023-08-04 11:31:49 -04:00
Gerald Monaco
e53d4ecf4c feat(core): add afterRender and afterNextRender (#50607)
Add and expose the after*Render functions as developer preview

PR Close #50607
2023-08-01 13:02:27 -07:00
Andrew Kushnir
307f8eee2c fix(core): avoid duplicated content during hydration while processing a component with i18n (#50644)
This commit updates an internal hydration logic to make sure that the content of components with i18n blocks is cleaned up before we start rendering it.

Resolves #50627.

PR Close #50644
2023-06-13 13:12:07 +02:00
Alan Agius
0875b519b9 fix(platform-server): surface errors during rendering (#50587)
Prior to this change in some cases errors tht happen during routing were not being surfaced. This is due to the fact that the router has floating promises, and the platform was being destroyed prior to these being settled.

PR Close #50587
2023-06-07 12:44:08 -07:00
Alan Agius
28c68f709c fix(core): update ApplicationRef.isStable to account for rendering pending tasks (#50425)
This commit updates the `ApplicationRef.isStable` API to account for
pending rendering task. This is needed as once a pending rendering task
is done, new macrotask and microtask could be created which previously caused these not
to be intercepted and thus ignored when doing SSR.

PR Close #50425
2023-05-30 12:58:22 -07:00
Alan Agius
02437224f5 refactor(core): simplify state transfer escaping (#50201)
This commit removes unnecessary transfer state escaping and updates this process to be done by the means of a `replacer` and `reviver` method as this removes the need to export the escaping and unescaping methods.

The only thing that we need to escape is `<script` and `</script` which are done by the browsers, but not Node.js.

PR Close #50201
2023-05-10 11:31:34 -07:00
Andrew Kushnir
822b3079ae fix(core): handle projection of hydrated containters into components that skip hydration (#50199)
This commit updates hydration logic to support a scenario where a view container that was hydrated and later on projected to a component that skips hydration. Currently, such projected content is extracted from the DOM (since a component that skips hydration needs to be re-created), but never added back, since the current logic treats such content as "already inserted".

Closes #50175.

PR Close #50199
2023-05-09 14:46:03 -07:00
Andrew Kushnir
d5d760045e fix(core): handle hydration of root components with injected ViewContainerRef (#50136)
This commit fixes an issue where a root component with an injected ViewContainerRef (for ex. `inject(ViewContainerRef)`) was triggering a certain code path during hydration which didn't handle this case correctly.

Resolves #50133.

PR Close #50136
2023-05-09 14:43:45 -07:00
Jessica Janiuk
1090bf870f refactor(core): improve error message when dom node is not found (#49977)
This adds context to the error message in the case that a DOM node is not found during the hydration process. It outputs the expected DOM structure based on the lView and tNode rather than an unhelpful text message.

PR Close #49977
2023-04-25 09:29:47 -07:00
Andrew Kushnir
3bcbfecb78 refactor(platform-browser): log a warning when a custom or a noop ZoneJS is used with hydration (#49944)
Hydration relies on a signal from ZoneJS when it becomes stable inside an application, so that Angular can start serialization process on the server or post-hydration cleanup on the client (to remove DOM nodes that remained unclaimed).

Providing a custom or a "noop" ZoneJS implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration.

This commit adds a warning (non-blocking) for those cases.

PR Close #49944
2023-04-23 18:23:28 -07:00
Andrew Kushnir
bbc2efcda2 refactor(core): hydrate components of the same type used with and without ngSkipHydration (#49943)
This commit updates hydration logic to hanlde a case when the same component is used multiple times in a template and in some of those cases, component is opted-out of hydration, for example:

```
<cmp ngSkipHydration />
<cmp />
```

Previously, the first occurrence of the `<cmp>` would result in storing the `ssrId` on a TView as `null` (since hydration is disabled for the component) and the second component instance reused the `null` as a value, thus also skipping hydration.

With the changes from this commit, the `ssrId` would be set when we come across a hydratable instance. We also make sure that the `ssrId` value never changes after we first set it to a non-`null` value.

PR Close #49943
2023-04-20 14:50:32 -07:00
Andrew Kushnir
338c7d9125 test(core): adding extra tests for hydration of view containers located after <ng-content> slots (#49920)
This commit adds extra tests to verify a couple additional use-cases related to view containers located after <ng-content> slots.

PR Close #49920
2023-04-19 14:26:43 +00:00
Andrew Kushnir
81ef9c327d refactor(core): handle empty projection slots within <ng-container> during hydration (#49920)
This commit updates hydration logic to handle cases when there are projection slots present in a template inside of an `<ng-container>` and when there are regular elements follow an <ng-content> slot (see tests for additional information). With this combination, the logic that annotates regular element locations should fallback to calculating a path from a reference node to that node. In case of an <ng-container>, the comment node is located *after* the node that needs an annotation. An existing logic was mistakenly returning an empty path, which was represented as a pointer to teh reference node. This commit fixes that and triggers a fallback to using a component host node as a reference in this case.

Resolves #49918.

PR Close #49920
2023-04-19 14:26:43 +00:00
Andrew Kushnir
5efd4fff57 refactor(core): insert special marker only when text node content is an empty string (#49877)
Empty text nodes are not present in the server-rendered HTML output, thus we inject a special marker
at a text node location to later restore an empty text node at the client. Currently, we treat text nodes with spaces as "empty" as well, however those spaces are present in the HTML and text nodes are created in a browser. Adding extra annotation in this case results in extra text nodes created on the client and may trigger hydration issues. This commit updates the code to avoid treating text nodes with spaces as "empty".

PR Close #49877
2023-04-18 19:04:28 +00:00
Andrew Kushnir
d994f8520c fix(core): include inner ViewContainerRef anchor nodes into ViewRef.rootNodes output (#49867)
Currently, the `ViewRef.rootNodes` output is missing anchor (comment) nodes for inner `ViewContainerRef`s,
when an achor node was created for that instance of a `ViewContainerRef` (which happens in all cases except
when an <ng-container> was used as a host for a view container).

This issue affects hydration logic, which relies on the number of root nodes within a view to properly determine
segments in DOM that belong to a particular view.

Resolves #49849.

PR Close #49867
2023-04-17 13:35:58 +00:00
Andrew Kushnir
83262dc0f9 refactor(core): do not enable hydration when server response was incorrect (#49750)
This commit updates the logic to avoid enabling hydration in case server response doesn't contain hydration-related info serialized. It can happen when `provideClientHydration()` call only happens on the client, but not on the server.

PR Close #49750
2023-04-10 09:03:20 -07:00
Andrew Kushnir
fe34de47bf refactor(core): add a warning when hydration annotation is missing in server response (#49743)
This commit updates the logic to detect a situation when hydration support was enabled only on the client. If that happens, Angular produces a warning in a console with a link to the error guide.

PR Close #49743
2023-04-07 09:41:55 -07:00
Andrew Kushnir
e08d6797ad refactor(core): skip hydration for components that use ShadowDom encapsulation (#49722)
The Domino DOM emulation library doesn't support shadow DOM. For such components we can not guarantee that client and server representations would match perfectly. To avoid hydration mismatch errors, such components are opted out of hydration.

PR Close #49722
2023-04-06 10:59:26 -07:00
Andrew Kushnir
5bf2b7da6f refactor(core): skip hydration for components that use i18n (instead of throwing an error) (#49722)
Currently, non-destructive hydration for i18n blocks is not supported (but support is coming!).
This commit updates the serialization logic from throwing an error when it comes across an i18n
block to annotating a component with a skip hydration flag.

PR Close #49722
2023-04-06 10:59:26 -07:00
Alan Agius
81e7d15ef6 feat(platform-browser): enable HTTP request caching when using provideClientHydration (#49699)
This commit adds support by default for HTTP caching when using `provideClientHydration`. Users can opt-out of this behaviour by using the `withoutHttpTransferCache` feature.

```ts
import {
  bootstrapApplication,
  provideClientHydration,
  withNoHttpTransferCache,
} from '@angular/platform-browser';
// ...
bootstrapApplication(RootCmp, {
  providers: [provideClientHydration(withNoHttpTransferCache())]
});
```

PR Close #49699
2023-04-04 15:04:03 -07:00
Andrew Kushnir
761e02d912 feat(platform-browser): add a public API function to enable non-destructive hydration (#49666)
This commit adds the `provideClientHydration` function to the public API. This function can be used to enable the non-destructive Angular hydration.

Important note: the non-destructive hydration feature is in Developer Preview mode, learn more about it at https://angular.io/guide/releases#developer-preview.

Before you can get started with hydration, you must have a server side rendered (SSR) application. Follow the [Angular Universal Guide](https://angular.io/guide/universal) to enable server side rendering first. Once you have SSR working with your application, you can enable hydration by visiting your main app component or module and importing `provideClientHydration` from `@angular/platform-browser`. You'll then add that provider to your app's bootstrapping providers list.

```typescript
import {
  bootstrapApplication,
  provideClientHydration,
} from '@angular/platform-browser';
// ...
bootstrapApplication(RootCmp, {
  providers: [provideClientHydration()]
});
```

Alternatively if you are using NgModules, you would add `provideClientHydration` to your root app module's provider list.

```typescript
import {provideClientHydration} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

@NgModule({
  declarations: [RootCmp],
  exports: [RootCmp],
  bootstrap: [RootCmp],
  providers: [provideClientHydration()],
})
export class AppModule {}
```

You can confirm hydration is enabled by opening Developer Tools in your browser and viewing the console. You should see a message that includes hydration-related stats, such as the number of components and nodes hydrated.

Co-authored-by: jessicajaniuk <72768744+jessicajaniuk@users.noreply.github.com>
Co-authored-by: alan-agius4 <17563226+alan-agius4@users.noreply.github.com>

PR Close #49666
2023-04-03 22:13:47 -07:00
Andrew Kushnir
61bedaf930 refactor(core): handle a case when ngSkipHydration is applied to the root node of an application (#49675)
This commit updates the logic to handle a case when the `ngSkipHydration` attribute is applied to the root node of an app. In this case, the hydration info should not be serialized and the contents of the app on the client should be cleared up before initial rendering.

PR Close #49675
2023-04-03 19:11:47 -07:00
Alan Agius
7870fb07fe feat(platform-server): rename provideServerSupport to provideServerRendering (#49678)
This commit renames `provideServerSupport` to `provideServerRendering`.

PR Close #49678
2023-04-03 15:00:13 -07:00
Andrew Kushnir
d786856c46 refactor(core): output hydration stats into a console in dev mode (#49617)
This commit adds a logic to output basic hydration stats into a console. This is also helpful to ensure that hydration is enabled and works.

PR Close #49617
2023-03-30 09:42:05 -07:00
Andrew Kushnir
478c5ac150 refactor(core): internal tracker of pending tasks during initial rendering (#49576)
This commit implements a simple tracker of the pending tasks during initial rendering. The class allows adding and removing tasks from the set. The class also exposes a promise that gets resolved once the last task is removed.

This tracker is needed to keep track of ongoing processes like Router navigation (and potentially HTTP requests) and acts as a signaling mechanism to SSR and hydration that the application is in the "stable" state and a serialization can be performed.

This class would also act as a future replacement for the `ApplicationRef.isStable` for zoneless applications.

PR Close #49576
2023-03-28 16:19:31 -07:00
Andrew Kushnir
22688b8ff3 refactor(core): handle <ng-content> with *ngIf during hydration (#49590)
This commit updates the serialization logic to avoid serializing a path for a node that was content projected (based on template information), but is not present in the DOM. This can happen if a <ng-content> is used with the *ngIf="false", for example: `<ng-content *ngIf="false" />`.

PR Close #49590
2023-03-27 12:53:12 -07:00
Andrew Kushnir
f1d3be3dee refactor(core): only annotate disconnected nodes in content projection (#49549)
Previously, we've annotated all disconnected DOM nodes, even if they are not used in content projection. However, this situation is only possible in content projection and if it happens in other cases (for example, when a node was removed using direct DOM manipulations), this should be a mismatch error.

PR Close #49549
2023-03-23 13:55:38 -07:00
Jessica Janiuk
0851bd5283 refactor(core): Improve hydration error handling (#49502)
This adds user friendly error messages outlining exactly where hydration
mismatches occur and what was expected with easy to read stringified
DOM. It also includes a pointer to exactly where the mismatch happened
and lets the user know what was expected.

PR Close #49502
2023-03-22 11:47:41 -07:00
Andrew Kushnir
8ea1fb7396 refactor(core): exclude disconnected nodes from hydration (#49471)
This commit updates the hydration logic to handle situations where DOM nodes might end up
being disconnected from the DOM tree. We serialize ids of those nodes into the hydration
state transfer data and use the information to switch from hydration to the regular "creation
mode" at runtime.

This situation may happen during the content projection, when some nodes don't make it
into one of the content projection slots (for example, when there is no default
<ng-content /> slot in projector component's template).

Note: we leverage the fact that we have this information available in the DOM emulation
layer (in Domino) for now. Longer-term solution should not rely on the DOM emulation and
only use internal data structures and state to compute this information.

PR Close #49471
2023-03-22 10:04:56 -07:00
Alan Agius
41f27ad086 refactor(platform-server): remove renderApplication overload that accepts a component (#49463)
This commit removes the `renderApplication` overload that accepts a root component as the first parameter.

BREAKING CHANGE:

`renderApplication` method no longer accepts a root component as first argument. Instead, provide a bootstrapping function that returns a `Promise<ApplicationRef>`.

Before
```ts
const output: string = await renderApplication(RootComponent, options);
```

Now
```ts
const bootstrap = () => bootstrapApplication(RootComponent, appConfig);
const output: string = await renderApplication(bootstrap, options);
```

PR Close #49463
2023-03-22 16:40:31 +01:00
Andrew Kushnir
504bd992ce refactor(core): add a note that hydration for i18n blocks is not yet supported (#49497)
This commit updates the serialization logic to detect a situation when i18n was used for a template and throw an error to indicate that hydration for i18n blocks is not yet supported.

Hydration for i18n blocks will be added in follow up versions.

PR Close #49497
2023-03-21 19:28:41 +01:00
Andrew Kushnir
a94b66f432 refactor(core): avoid ngSkipHydration on nodes other than component host ones (#49500)
Angular Hydration uses Components as a hydration boundary, i.e. you can enable/disable hydration on per-component basis. This commit enforces that the `ngSkipHydration` can only be applied on component host nodes (an error if thrown otherwise).

PR Close #49500
2023-03-21 18:59:25 +01:00
Andrew Kushnir
a0c289cbac refactor(core): avoid repeated views in serialized data (#49475)
This commit updates the serialization logic to recognized similar repeated views and instead of including the same info over and over again, a special field is added to the serialized view object with a number of repetitions. The hydration logic also recognizes the flag and creates the necessary number of dehydrated views in a container.

This optimization should help minimize the amount of extra annotations required for cases like *ngFor with large number of items.

PR Close #49475
2023-03-21 18:40:29 +01:00