_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/src/sanitization/iframe_attrs_validation.ts_0_2510 | /**
* @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 {getTemplateLocationDetails} from '../render3/instructions/element_validation';
import {TNodeType} from '../render3/interfaces/node';
import {RComment, RElement} from '../render3/interfaces/renderer_dom';
import {RENDERER} from '../render3/interfaces/view';
import {nativeRemoveNode} from '../render3/node_manipulation';
import {getLView, getSelectedTNode} from '../render3/state';
import {getNativeByTNode} from '../render3/util/view_utils';
import {trustedHTMLFromString} from '../util/security/trusted_types';
/**
* Validation function invoked at runtime for each binding that might potentially
* represent a security-sensitive attribute of an <iframe>.
* See `IFRAME_SECURITY_SENSITIVE_ATTRS` in the
* `packages/compiler/src/schema/dom_security_schema.ts` script for the full list
* of such attributes.
*
* @codeGenApi
*/
export function ɵɵvalidateIframeAttribute(attrValue: any, tagName: string, attrName: string) {
const lView = getLView();
const tNode = getSelectedTNode()!;
const element = getNativeByTNode(tNode, lView) as RElement | RComment;
// Restrict any dynamic bindings of security-sensitive attributes/properties
// on an <iframe> for security reasons.
if (tNode.type === TNodeType.Element && tagName.toLowerCase() === 'iframe') {
const iframe = element as HTMLIFrameElement;
// Unset previously applied `src` and `srcdoc` if we come across a situation when
// a security-sensitive attribute is set later via an attribute/property binding.
iframe.src = '';
iframe.srcdoc = trustedHTMLFromString('') as unknown as string;
// Also remove the <iframe> from the document.
nativeRemoveNode(lView[RENDERER], iframe);
const errorMessage =
ngDevMode &&
`Angular has detected that the \`${attrName}\` was applied ` +
`as a binding to an <iframe>${getTemplateLocationDetails(lView)}. ` +
`For security reasons, the \`${attrName}\` can be set on an <iframe> ` +
`as a static attribute only. \n` +
`To fix this, switch the \`${attrName}\` binding to a static attribute ` +
`in a template or in host bindings section.`;
throw new RuntimeError(RuntimeErrorCode.UNSAFE_IFRAME_ATTRS, errorMessage);
}
return attrValue;
}
| {
"end_byte": 2510,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/sanitization/iframe_attrs_validation.ts"
} |
angular/packages/core/src/metadata/schema.ts_0_1297 | /**
* @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 schema definition associated with an NgModule.
*
* @see {@link NgModule}
* @see {@link CUSTOM_ELEMENTS_SCHEMA}
* @see {@link NO_ERRORS_SCHEMA}
*
* @param name The name of a defined schema.
*
* @publicApi
*/
export interface SchemaMetadata {
name: string;
}
/**
* Defines a schema that allows an NgModule to contain the following:
* - Non-Angular elements named with dash case (`-`).
* - Element properties named with dash case (`-`).
* Dash case is the naming convention for custom elements.
*
* @publicApi
*/
export const CUSTOM_ELEMENTS_SCHEMA: SchemaMetadata = {
name: 'custom-elements',
};
/**
* Defines a schema that allows any property on any element.
*
* This schema allows you to ignore the errors related to any unknown elements or properties in a
* template. The usage of this schema is generally discouraged because it prevents useful validation
* and may hide real errors in your template. Consider using the `CUSTOM_ELEMENTS_SCHEMA` instead.
*
* @publicApi
*/
export const NO_ERRORS_SCHEMA: SchemaMetadata = {
name: 'no-errors-schema',
};
| {
"end_byte": 1297,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/schema.ts"
} |
angular/packages/core/src/metadata/ng_module_def.ts_0_2673 | /**
* @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 {SchemaMetadata} from './schema';
export interface NgModuleType<T = any> extends Type<T> {
ɵmod: NgModuleDef<T>;
}
/**
* Represents the expansion of an `NgModule` into its scopes.
*
* A scope is a set of directives and pipes that are visible in a particular context. Each
* `NgModule` has two scopes. The `compilation` scope is the set of directives and pipes that will
* be recognized in the templates of components declared by the module. The `exported` scope is the
* set of directives and pipes exported by a module (that is, module B's exported scope gets added
* to module A's compilation scope when module A imports B).
*/
export interface NgModuleTransitiveScopes {
compilation: {directives: Set<any>; pipes: Set<any>};
exported: {directives: Set<any>; pipes: Set<any>};
schemas: SchemaMetadata[] | null;
}
/**
* Runtime link information for NgModules.
*
* This is the internal data structure used by the runtime to assemble components, directives,
* pipes, and injectors.
*
* NOTE: Always use `ɵɵdefineNgModule` function to create this object,
* never create the object directly since the shape of this object
* can change between versions.
*/
export interface NgModuleDef<T> {
/** Token representing the module. Used by DI. */
type: T;
/**
* List of components to bootstrap.
*
* @see {NgModuleScopeInfoFromDecorator} This field is only used in global compilation mode. In local compilation mode the bootstrap info is computed and added in runtime.
*/
bootstrap: Type<any>[] | (() => Type<any>[]);
/** List of components, directives, and pipes declared by this module. */
declarations: Type<any>[] | (() => Type<any>[]);
/** List of modules or `ModuleWithProviders` imported by this module. */
imports: Type<any>[] | (() => Type<any>[]);
/**
* List of modules, `ModuleWithProviders`, components, directives, or pipes exported by this
* module.
*/
exports: Type<any>[] | (() => Type<any>[]);
/**
* Cached value of computed `transitiveCompileScopes` for this module.
*
* This should never be read directly, but accessed via `transitiveScopesFor`.
*/
transitiveCompileScopes: NgModuleTransitiveScopes | null;
/** The set of schemas that declare elements to be allowed in the NgModule. */
schemas: SchemaMetadata[] | null;
/** Unique ID for the module with which it should be registered. */
id: string | null;
}
| {
"end_byte": 2673,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/ng_module_def.ts"
} |
angular/packages/core/src/metadata/ng_module.ts_0_6878 | /**
* @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, ModuleWithProviders, Provider} from '../di/interface/provider';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {compileNgModule} from '../render3/jit/module';
import {makeDecorator, TypeDecorator} from '../util/decorators';
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/di/dependency-injection
* @see [NgModule guide](guide/ngmodules/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Array<Provider | EnvironmentProviders>;
/**
* The set of components, directives, and pipes (declarables
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any> | any[]>;
/**
* The set of NgModules whose exported declarables
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any> | ModuleWithProviders<{}> | any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any> | any[]>;
/**
* The set of components that are bootstrapped when this module is bootstrapped.
*/
bootstrap?: Array<Type<any> | any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata | any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getNgModuleById`.
* If left `undefined`, the NgModule is not registered with `getNgModuleById`.
*/
id?: string;
/**
* When present, this module is ignored by the AOT compiler.
* It remains in distributed code, and the JIT compiler attempts to compile it
* at run time, in the browser.
* To ensure the correct behavior, the app must import `@angular/compiler`.
*/
jit?: true;
}
/**
* @Annotation
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule',
(ngModule: NgModule) => ngModule,
undefined,
undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` option configures the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => compileNgModule(type, meta),
);
| {
"end_byte": 6878,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/ng_module.ts"
} |
angular/packages/core/src/metadata/do_bootstrap.ts_0_1026 | /**
* @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 {ApplicationRef} from '../application/application_ref';
/**
* @description
* Hook for manual bootstrapping of the application instead of using `bootstrap` array in @NgModule
* annotation. This hook is invoked only when the `bootstrap` array is empty or not provided.
*
* Reference to the current application is provided as a parameter.
*
* See ["Bootstrapping"](guide/ngmodules/bootstrapping).
*
* @usageNotes
* The example below uses `ApplicationRef.bootstrap()` to render the
* `AppComponent` on the page.
*
* ```typescript
* class AppModule implements DoBootstrap {
* ngDoBootstrap(appRef: ApplicationRef) {
* appRef.bootstrap(AppComponent); // Or some other component
* }
* }
* ```
*
* @publicApi
*/
export interface DoBootstrap {
ngDoBootstrap(appRef: ApplicationRef): void;
}
| {
"end_byte": 1026,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/do_bootstrap.ts"
} |
angular/packages/core/src/metadata/view.ts_0_1672 | /**
* @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
*/
/**
* Defines the CSS styles encapsulation policies for the {@link Component} decorator's
* `encapsulation` option.
*
* See {@link Component#encapsulation encapsulation}.
*
* @usageNotes
* ### Example
*
* {@example core/ts/metadata/encapsulation.ts region='longform'}
*
* @publicApi
*/
export enum ViewEncapsulation {
// TODO: consider making `ViewEncapsulation` a `const enum` instead. See
// https://github.com/angular/angular/issues/44119 for additional information.
/**
* Emulates a native Shadow DOM encapsulation behavior by adding a specific attribute to the
* component's host element and applying the same attribute to all the CSS selectors provided
* via {@link Component#styles styles} or {@link Component#styleUrls styleUrls}.
*
* This is the default option.
*/
Emulated = 0,
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
/**
* Doesn't provide any sort of CSS style encapsulation, meaning that all the styles provided
* via {@link Component#styles styles} or {@link Component#styleUrls styleUrls} are applicable
* to any HTML element of the application regardless of their host Component.
*/
None = 2,
/**
* Uses the browser's native Shadow DOM API to encapsulate CSS styles, meaning that it creates
* a ShadowRoot for the component's host element which is then used to encapsulate
* all the Component's styling.
*/
ShadowDom = 3,
}
| {
"end_byte": 1672,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/view.ts"
} |
angular/packages/core/src/metadata/directives.ts_0_3414 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy} from '../change_detection/constants';
import {Provider} from '../di/interface/provider';
import {Type} from '../interface/type';
import {compileComponent, compileDirective} from '../render3/jit/directive';
import {compilePipe} from '../render3/jit/pipe';
import {makeDecorator, makePropDecorator, TypeDecorator} from '../util/decorators';
import {SchemaMetadata} from './schema';
import {ViewEncapsulation} from './view';
/**
* Type of the Directive decorator / constructor function.
* @publicApi
*/
export interface DirectiveDecorator {
/**
* Decorator that marks a class as an Angular directive.
* You can define your own directives to attach custom behavior to elements in the DOM.
*
* The options provide configuration metadata that determines
* how the directive should be processed, instantiated and used at
* runtime.
*
* Directive classes, like component classes, can implement
* [life-cycle hooks](guide/components/lifecycle) to influence their configuration and behavior.
*
*
* @usageNotes
* To define a directive, mark the class with the decorator and provide metadata.
*
* ```ts
* import {Directive} from '@angular/core';
*
* @Directive({
* selector: 'my-directive',
* })
* export class MyDirective {
* ...
* }
* ```
*
* ### Declaring directives
*
* In order to make a directive available to other components in your application, you should do
* one of the following:
* - either mark the directive as [standalone](guide/components/importing),
* - or declare it in an NgModule by adding it to the `declarations` and `exports` fields.
*
* ** Marking a directive as standalone **
*
* You can add the `standalone: true` flag to the Directive decorator metadata to declare it as
* [standalone](guide/components/importing):
*
* ```ts
* @Directive({
* standalone: true,
* selector: 'my-directive',
* })
* class MyDirective {}
* ```
*
* When marking a directive as standalone, please make sure that the directive is not already
* declared in an NgModule.
*
*
* ** Declaring a directive in an NgModule **
*
* Another approach is to declare a directive in an NgModule:
*
* ```ts
* @Directive({
* selector: 'my-directive',
* })
* class MyDirective {}
*
* @NgModule({
* declarations: [MyDirective, SomeComponent],
* exports: [MyDirective], // making it available outside of this module
* })
* class SomeNgModule {}
* ```
*
* When declaring a directive in an NgModule, please make sure that:
* - the directive is declared in exactly one NgModule.
* - the directive is not standalone.
* - you do not re-declare a directive imported from another module.
* - the directive is included into the `exports` field as well if you want this directive to be
* accessible for components outside of the NgModule.
*
*
* @Annotation
*/
(obj?: Directive): TypeDecorator;
/**
* See the `Directive` decorator.
*/
new (obj?: Directive): Directive;
}
/**
* Directive decorator and metadata.
*
* @Annotation
* @publicApi
*/ | {
"end_byte": 3414,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/directives.ts_3415_11441 | export interface Directive {
/**
* The CSS selector that identifies this directive in a template
* and triggers instantiation of the directive.
*
* Declare as one of the following:
*
* - `element-name`: Select by element name.
* - `.class`: Select by class name.
* - `[attribute]`: Select by attribute name.
* - `[attribute=value]`: Select by attribute name and value.
* - `:not(sub_selector)`: Select only if the element does not match the `sub_selector`.
* - `selector1, selector2`: Select if either `selector1` or `selector2` matches.
*
* Angular only allows directives to apply on CSS selectors that do not cross
* element boundaries.
*
* For the following template HTML, a directive with an `input[type=text]` selector,
* would be instantiated only on the `<input type="text">` element.
*
* ```html
* <form>
* <input type="text">
* <input type="radio">
* <form>
* ```
*
*/
selector?: string;
/**
* Enumerates the set of data-bound input properties for a directive
*
* Angular automatically updates input properties during change detection.
* The `inputs` property accepts either strings or object literals that configure the directive
* properties that should be exposed as inputs.
*
* When an object literal is passed in, the `name` property indicates which property on the
* class the input should write to, while the `alias` determines the name under
* which the input will be available in template bindings. The `required` property indicates that
* the input is required which will trigger a compile-time error if it isn't passed in when the
* directive is used.
*
* When a string is passed into the `inputs` array, it can have a format of `'name'` or
* `'name: alias'` where `name` is the property on the class that the directive should write
* to, while the `alias` determines the name under which the input will be available in
* template bindings. String-based input definitions are assumed to be optional.
*
* @usageNotes
*
* The following example creates a component with two data-bound properties.
*
* ```typescript
* @Component({
* selector: 'bank-account',
* inputs: ['bankName', {name: 'id', alias: 'account-id'}],
* template: `
* Bank Name: {{bankName}}
* Account Id: {{id}}
* `
* })
* class BankAccount {
* bankName: string;
* id: string;
* }
* ```
*
*/
inputs?: (
| {
name: string;
alias?: string;
required?: boolean;
transform?: (value: any) => any;
}
| string
)[];
/**
* Enumerates the set of event-bound output properties.
*
* When an output property emits an event, an event handler attached to that event
* in the template is invoked.
*
* The `outputs` property defines a set of `directiveProperty` to `alias`
* configuration:
*
* - `directiveProperty` specifies the component property that emits events.
* - `alias` specifies the DOM property the event handler is attached to.
*
* @usageNotes
*
* ```typescript
* @Component({
* selector: 'child-dir',
* outputs: [ 'bankNameChange' ],
* template: `<input (input)="bankNameChange.emit($event.target.value)" />`
* })
* class ChildDir {
* bankNameChange: EventEmitter<string> = new EventEmitter<string>();
* }
*
* @Component({
* selector: 'main',
* template: `
* {{ bankName }} <child-dir (bankNameChange)="onBankNameChange($event)"></child-dir>
* `
* })
* class MainComponent {
* bankName: string;
*
* onBankNameChange(bankName: string) {
* this.bankName = bankName;
* }
* }
* ```
*
*/
outputs?: string[];
/**
* Configures the injector of this
* directive or component with a token
* that maps to a provider of a dependency.
*/
providers?: Provider[];
/**
* Defines the name that can be used in the template to assign this directive to a variable.
*
* @usageNotes
*
* ```ts
* @Directive({
* selector: 'child-dir',
* exportAs: 'child'
* })
* class ChildDir {
* }
*
* @Component({
* selector: 'main',
* template: `<child-dir #c="child"></child-dir>`
* })
* class MainComponent {
* }
* ```
*
*/
exportAs?: string;
/**
* Configures the queries that will be injected into the directive.
*
* Content queries are set before the `ngAfterContentInit` callback is called.
* View queries are set before the `ngAfterViewInit` callback is called.
*
* @usageNotes
*
* The following example shows how queries are defined
* and when their results are available in lifecycle hooks:
*
* ```ts
* @Component({
* selector: 'someDir',
* queries: {
* contentChildren: new ContentChildren(ChildDirective),
* viewChildren: new ViewChildren(ChildDirective)
* },
* template: '<child-directive></child-directive>'
* })
* class SomeDir {
* contentChildren: QueryList<ChildDirective>,
* viewChildren: QueryList<ChildDirective>
*
* ngAfterContentInit() {
* // contentChildren is set
* }
*
* ngAfterViewInit() {
* // viewChildren is set
* }
* }
* ```
*
* @Annotation
*/
queries?: {[key: string]: any};
/**
* Maps class properties to host element bindings for properties,
* attributes, and events, using a set of key-value pairs.
*
* Angular automatically checks host property bindings during change detection.
* If a binding changes, Angular updates the directive's host element.
*
* When the key is a property of the host element, the property value is
* propagated to the specified DOM property.
*
* When the key is a static attribute in the DOM, the attribute value
* is propagated to the specified property in the host element.
*
* For event handling:
* - The key is the DOM event that the directive listens to.
* To listen to global events, add the target to the event name.
* The target can be `window`, `document` or `body`.
* - The value is the statement to execute when the event occurs. If the
* statement evaluates to `false`, then `preventDefault` is applied on the DOM
* event. A handler method can refer to the `$event` local variable.
*
*/
host?: {[key: string]: string};
/**
* When present, this directive/component is ignored by the AOT compiler.
* It remains in distributed code, and the JIT compiler attempts to compile it
* at run time, in the browser.
* To ensure the correct behavior, the app must import `@angular/compiler`.
*/
jit?: true;
/**
* Angular directives marked as `standalone` do not need to be declared in an NgModule. Such
* directives don't depend on any "intermediate context" of an NgModule (ex. configured
* providers).
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
standalone?: boolean;
/**
* // TODO(signals): Remove internal and add public documentation
*
* @internal
*/
signals?: boolean;
/**
* Standalone directives that should be applied to the host whenever the directive is matched.
* By default, none of the inputs or outputs of the host directives will be available on the host,
* unless they are specified in the `inputs` or `outputs` properties.
*
* You can additionally alias inputs and outputs by putting a colon and the alias after the
* original input or output name. For example, if a directive applied via `hostDirectives`
* defines an input named `menuDisabled`, you can alias this to `disabled` by adding
* `'menuDisabled: disabled'` as an entry to `inputs`.
*/
hostDirectives?: (
| Type<unknown>
| {
directive: Type<unknown>;
inputs?: string[];
outputs?: string[];
}
)[];
} | {
"end_byte": 11441,
"start_byte": 3415,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/directives.ts_11443_16843 | /**
* Type of the Directive metadata.
*
* @publicApi
*/
export const Directive: DirectiveDecorator = makeDecorator(
'Directive',
(dir: Directive = {}) => dir,
undefined,
undefined,
(type: Type<any>, meta: Directive) => compileDirective(type, meta),
);
/**
* Component decorator interface
*
* @publicApi
*/
export interface ComponentDecorator {
/**
* Decorator that marks a class as an Angular component and provides configuration
* metadata that determines how the component should be processed,
* instantiated, and used at runtime.
*
* Components are the most basic UI building block of an Angular app.
* An Angular app contains a tree of Angular components.
*
* Angular components are a subset of directives, always associated with a template.
* Unlike other directives, only one component can be instantiated for a given element in a
* template.
*
* Standalone components can be directly imported in any other standalone component or NgModule.
* NgModule based apps on the other hand require components to belong to an NgModule in
* order for them to be available to another component or application. To make a component a
* member of an NgModule, list it in the `declarations` field of the `NgModule` metadata.
*
* Note that, in addition to these options for configuring a directive,
* you can control a component's runtime behavior by implementing
* life-cycle hooks. For more information, see the
* [Lifecycle Hooks](guide/components/lifecycle) guide.
*
* @usageNotes
*
* ### Setting component inputs
*
* The following example creates a component with two data-bound properties,
* specified by the `inputs` value.
*
* <code-example path="core/ts/metadata/directives.ts" region="component-input"></code-example>
*
*
* ### Setting component outputs
*
* The following example shows two event emitters that emit on an interval. One
* emits an output every second, while the other emits every five seconds.
*
* {@example core/ts/metadata/directives.ts region='component-output-interval'}
*
* ### Injecting a class with a view provider
*
* The following simple example injects a class into a component
* using the view provider specified in component metadata:
*
* ```ts
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @Directive({
* selector: 'needs-greeter'
* })
* class NeedsGreeter {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
*
* @Component({
* selector: 'greet',
* viewProviders: [
* Greeter
* ],
* template: `<needs-greeter></needs-greeter>`
* })
* class HelloWorld {
* }
*
* ```
*
* ### Preserving whitespace
*
* Removing whitespace can greatly reduce AOT-generated code size and speed up view creation.
* As of Angular 6, the default for `preserveWhitespaces` is false (whitespace is removed).
* To change the default setting for all components in your application, set
* the `preserveWhitespaces` option of the AOT compiler.
*
* By default, the AOT compiler removes whitespace characters as follows:
* * Trims all whitespaces at the beginning and the end of a template.
* * Removes whitespace-only text nodes. For example,
*
* ```html
* <button>Action 1</button> <button>Action 2</button>
* ```
*
* becomes:
*
* ```html
* <button>Action 1</button><button>Action 2</button>
* ```
*
* * Replaces a series of whitespace characters in text nodes with a single space.
* For example, `<span>\n some text\n</span>` becomes `<span> some text </span>`.
* * Does NOT alter text nodes inside HTML tags such as `<pre>` or `<textarea>`,
* where whitespace characters are significant.
*
* Note that these transformations can influence DOM nodes layout, although impact
* should be minimal.
*
* You can override the default behavior to preserve whitespace characters
* in certain fragments of a template. For example, you can exclude an entire
* DOM sub-tree by using the `ngPreserveWhitespaces` attribute:
*
* ```html
* <div ngPreserveWhitespaces>
* whitespaces are preserved here
* <span> and here </span>
* </div>
* ```
*
* You can force a single space to be preserved in a text node by using `&ngsp;`,
* which is replaced with a space character by Angular's template
* compiler:
*
* ```html
* <a>Spaces</a>&ngsp;<a>between</a>&ngsp;<a>links.</a>
* <!-- compiled to be equivalent to:
* <a>Spaces</a> <a>between</a> <a>links.</a> -->
* ```
*
* Note that sequences of `&ngsp;` are still collapsed to just one space character when
* the `preserveWhitespaces` option is set to `false`.
*
* ```html
* <a>before</a>&ngsp;&ngsp;&ngsp;<a>after</a>
* <!-- compiled to be equivalent to:
* <a>before</a> <a>after</a> -->
* ```
*
* To preserve sequences of whitespace characters, use the
* `ngPreserveWhitespaces` attribute.
*
* @Annotation
*/
(obj: Component): TypeDecorator;
/**
* See the `Component` decorator.
*/
new (obj: Component): Component;
}
/**
* Supplies configuration metadata for an Angular component.
*
* @publicApi
*/ | {
"end_byte": 16843,
"start_byte": 11443,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/directives.ts_16844_25018 | export interface Component extends Directive {
/**
* The change-detection strategy to use for this component.
*
* When a component is instantiated, Angular creates a change detector,
* which is responsible for propagating the component's bindings.
* The strategy is one of:
* - `ChangeDetectionStrategy#OnPush` sets the strategy to `CheckOnce` (on demand).
* - `ChangeDetectionStrategy#Default` sets the strategy to `CheckAlways`.
*/
changeDetection?: ChangeDetectionStrategy;
/**
* Defines the set of injectable objects that are visible to its view DOM children.
* See [example](#injecting-a-class-with-a-view-provider).
*
*/
viewProviders?: Provider[];
/**
* The module ID of the module that contains the component.
* The component must be able to resolve relative URLs for templates and styles.
* SystemJS exposes the `__moduleName` variable within each module.
* In CommonJS, this can be set to `module.id`.
*
* @deprecated This option does not have any effect. Will be removed in Angular v17.
*/
moduleId?: string;
/**
* The relative path or absolute URL of a template file for an Angular component.
* If provided, do not supply an inline template using `template`.
*
*/
templateUrl?: string;
/**
* An inline template for an Angular component. If provided,
* do not supply a template file using `templateUrl`.
*
*/
template?: string;
/**
* One relative paths or an absolute URL for files containing CSS stylesheet to use
* in this component.
*/
styleUrl?: string;
/**
* Relative paths or absolute URLs for files containing CSS stylesheets to use in this component.
*/
styleUrls?: string[];
/**
* One or more inline CSS stylesheets to use
* in this component.
*/
styles?: string | string[];
/**
* One or more animation `trigger()` calls, containing
* [`state()`](api/animations/state) and `transition()` definitions.
* See the [Animations guide](guide/animations) and animations API documentation.
*
*/
animations?: any[];
/**
* An encapsulation policy for the component's styling.
* Possible values:
* - `ViewEncapsulation.Emulated`: Apply modified component styles in order to emulate
* a native Shadow DOM CSS encapsulation behavior.
* - `ViewEncapsulation.None`: Apply component styles globally without any sort of encapsulation.
* - `ViewEncapsulation.ShadowDom`: Use the browser's native Shadow DOM API to encapsulate styles.
*
* If not supplied, the value is taken from the `CompilerOptions`
* which defaults to `ViewEncapsulation.Emulated`.
*
* If the policy is `ViewEncapsulation.Emulated` and the component has no
* {@link Component#styles styles} nor {@link Component#styleUrls styleUrls},
* the policy is automatically switched to `ViewEncapsulation.None`.
*/
encapsulation?: ViewEncapsulation;
/**
* Overrides the default interpolation start and end delimiters (`{{` and `}}`).
*
* @deprecated use Angular's default interpolation delimiters instead.
*/
interpolation?: [string, string];
/**
* True to preserve or false to remove potentially superfluous whitespace characters
* from the compiled template. Whitespace characters are those matching the `\s`
* character class in JavaScript regular expressions. Default is false, unless
* overridden in compiler options.
*/
preserveWhitespaces?: boolean;
/**
* Angular components marked as `standalone` do not need to be declared in an NgModule. Such
* components directly manage their own template dependencies (components, directives, and pipes
* used in a template) via the imports property.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
standalone?: boolean;
/**
* The imports property specifies the standalone component's template dependencies — those
* directives, components, and pipes that can be used within its template. Standalone components
* can import other standalone components, directives, and pipes as well as existing NgModules.
*
* This property is only available for standalone components - specifying it for components
* declared in an NgModule generates a compilation error.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
imports?: (Type<any> | ReadonlyArray<any>)[];
/**
* The `deferredImports` property specifies a standalone component's template dependencies,
* which should be defer-loaded as a part of the `@defer` block. Angular *always* generates
* dynamic imports for such symbols and removes the regular/eager import. Make sure that imports
* which bring symbols used in the `deferredImports` don't contain other symbols.
*
* Note: this is an internal-only field, use regular `@Component.imports` field instead.
* @internal
*/
deferredImports?: (Type<any> | ReadonlyArray<any>)[];
/**
* The set of schemas that declare elements to be allowed in a standalone component. Elements and
* properties that are neither Angular components nor directives must be declared in a schema.
*
* This property is only available for standalone components - specifying it for components
* declared in an NgModule generates a compilation error.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
schemas?: SchemaMetadata[];
}
/**
* Component decorator and metadata.
*
* @Annotation
* @publicApi
*/
export const Component: ComponentDecorator = makeDecorator(
'Component',
(c: Component = {}) => ({changeDetection: ChangeDetectionStrategy.Default, ...c}),
Directive,
undefined,
(type: Type<any>, meta: Component) => compileComponent(type, meta),
);
/**
* Type of the Pipe decorator / constructor function.
*
* @publicApi
*/
export interface PipeDecorator {
/**
*
* Decorator that marks a class as pipe and supplies configuration metadata.
*
* A pipe class must implement the `PipeTransform` interface.
* For example, if the name is "myPipe", use a template binding expression
* such as the following:
*
* ```
* {{ exp | myPipe }}
* ```
*
* The result of the expression is passed to the pipe's `transform()` method.
*
* A pipe must belong to an NgModule in order for it to be available
* to a template. To make it a member of an NgModule,
* list it in the `declarations` field of the `NgModule` metadata.
*
* @see [Style Guide: Pipe Names](style-guide#02-09)
*
*/
(obj: Pipe): TypeDecorator;
/**
* See the `Pipe` decorator.
*/
new (obj: Pipe): Pipe;
}
/**
* Type of the Pipe metadata.
*
* @publicApi
*/
export interface Pipe {
/**
* The pipe name to use in template bindings.
* Typically uses lowerCamelCase
* because the name cannot contain hyphens.
*/
name: string;
/**
* When true, the pipe is pure, meaning that the
* `transform()` method is invoked only when its input arguments
* change. Pipes are pure by default.
*
* If the pipe has internal state (that is, the result
* depends on state other than its arguments), set `pure` to false.
* In this case, the pipe is invoked on each change-detection cycle,
* even if the arguments have not changed.
*/
pure?: boolean;
/**
* Angular pipes marked as `standalone` do not need to be declared in an NgModule. Such
* pipes don't depend on any "intermediate context" of an NgModule (ex. configured providers).
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
standalone?: boolean;
}
/**
* @Annotation
* @publicApi
*/
export const Pipe: PipeDecorator = makeDecorator(
'Pipe',
(p: Pipe) => ({pure: true, ...p}),
undefined,
undefined,
(type: Type<any>, meta: Pipe) => compilePipe(type, meta),
);
/**
* @publicApi
*/
e | {
"end_byte": 25018,
"start_byte": 16844,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/directives.ts_25019_32007 | port interface InputDecorator {
/**
* Decorator that marks a class field as an input property and supplies configuration metadata.
* The input property is bound to a DOM property in the template. During change detection,
* Angular automatically updates the data property with the DOM property's value.
*
* @usageNotes
*
* You can supply an optional name to use in templates when the
* component is instantiated, that maps to the
* name of the bound property. By default, the original
* name of the bound property is used for input binding.
*
* The following example creates a component with two input properties,
* one of which is given a special binding name.
*
* ```typescript
* import { Component, Input, numberAttribute, booleanAttribute } from '@angular/core';
* @Component({
* selector: 'bank-account',
* template: `
* Bank Name: {{bankName}}
* Account Id: {{id}}
* Account Status: {{status ? 'Active' : 'InActive'}}
* `
* })
* class BankAccount {
* // This property is bound using its original name.
* // Defining argument required as true inside the Input Decorator
* // makes this property deceleration as mandatory
* @Input({ required: true }) bankName!: string;
* // Argument alias makes this property value is bound to a different property name
* // when this component is instantiated in a template.
* // Argument transform convert the input value from string to number
* @Input({ alias:'account-id', transform: numberAttribute }) id: number;
* // Argument transform the input value from string to boolean
* @Input({ transform: booleanAttribute }) status: boolean;
* // this property is not bound, and is not automatically updated by Angular
* normalizedBankName: string;
* }
*
* @Component({
* selector: 'app',
* template: `
* <bank-account bankName="RBC" account-id="4747" status="true"></bank-account>
* `
* })
* class App {}
* ```
*
* @see [Input properties](guide/components/inputs)
* @see [Output properties](guide/components/outputs)
*/
(arg?: string | Input): any;
new (arg?: string | Input): any;
}
/**
* Type of metadata for an `Input` property.
*
* @publicApi
*/
export interface Input {
/**
* The name of the DOM property to which the input property is bound.
*/
alias?: string;
/**
* Whether the input is required for the directive to function.
*/
required?: boolean;
/**
* Function with which to transform the input value before assigning it to the directive instance.
*/
transform?: (value: any) => any;
/**
* @internal
*
* Whether the input is a signal input.
*
* This option exists for JIT compatibility. Users are not expected to use this.
* Angular needs a way to capture inputs from classes so that the internal data
* structures can be set up. This needs to happen before the component is instantiated.
* Due to this, for JIT compilation, signal inputs need an additional decorator
* declaring the input. Angular provides a TS transformer to automatically handle this
* for JIT usage (e.g. in tests).
*/
isSignal?: boolean;
}
/**
* @Annotation
* @publicApi
*/
export const Input: InputDecorator = makePropDecorator(
'Input',
(arg?: string | {alias?: string; required?: boolean}) => {
if (!arg) {
return {};
}
return typeof arg === 'string' ? {alias: arg} : arg;
},
);
/**
* Type of the Output decorator / constructor function.
*
* @publicApi
*/
export interface OutputDecorator {
/**
* Decorator that marks a class field as an output property and supplies configuration metadata.
* The DOM property bound to the output property is automatically updated during change detection.
*
* @usageNotes
*
* You can supply an optional name to use in templates when the
* component is instantiated, that maps to the
* name of the bound property. By default, the original
* name of the bound property is used for output binding.
*
* See `Input` decorator for an example of providing a binding name.
*
* @see [Input properties](guide/components/inputs)
* @see [Output properties](guide/components/outputs)
*
*/
(alias?: string): any;
new (alias?: string): any;
}
/**
* Type of the Output metadata.
*
* @publicApi
*/
export interface Output {
/**
* The name of the DOM property to which the output property is bound.
*/
alias?: string;
}
/**
* @Annotation
* @publicApi
*/
export const Output: OutputDecorator = makePropDecorator('Output', (alias?: string) => ({alias}));
/**
* Type of the HostBinding decorator / constructor function.
*
* @publicApi
*/
export interface HostBindingDecorator {
/**
* Decorator that marks a DOM property or an element class, style or attribute as a host-binding
* property and supplies configuration metadata. Angular automatically checks host bindings during
* change detection, and if a binding changes it updates the host element of the directive.
*
* @usageNotes
*
* The following example creates a directive that sets the `valid` and `invalid`
* class, a style color, and an id on the DOM element that has an `ngModel` directive on it.
*
* ```typescript
* @Directive({selector: '[ngModel]'})
* class NgModelStatus {
* constructor(public control: NgModel) {}
* // class bindings
* @HostBinding('class.valid') get valid() { return this.control.valid; }
* @HostBinding('class.invalid') get invalid() { return this.control.invalid; }
*
* // style binding
* @HostBinding('style.color') get color() { return this.control.valid ? 'green': 'red'; }
*
* // style binding also supports a style unit extension
* @HostBinding('style.width.px') @Input() width: number = 500;
*
* // attribute binding
* @HostBinding('attr.aria-required')
* @Input() required: boolean = false;
*
* // property binding
* @HostBinding('id') get id() { return this.control.value?.length ? 'odd': 'even'; }
*
* @Component({
* selector: 'app',
* template: `<input [(ngModel)]="prop">`,
* })
* class App {
* prop;
* }
* ```
*
*/
(hostPropertyName?: string): any;
new (hostPropertyName?: string): any;
}
/**
* Type of the HostBinding metadata.
*
* @publicApi
*/
export interface HostBinding {
/**
* The DOM property that is bound to a data property.
* This field also accepts:
* * classes, prefixed by `class.`
* * styles, prefixed by `style.`
* * attributes, prefixed by `attr.`
*/
hostPropertyName?: string;
}
/**
* @Annotation
* @publicApi
*/
export const HostBinding: HostBindingDecorator = makePropDecorator(
'HostBinding',
(hostPropertyName?: string) => ({hostPropertyName}),
);
/**
* Type of the HostListener decorator / constructor function.
*
* @publicApi
*/
e | {
"end_byte": 32007,
"start_byte": 25019,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/directives.ts_32008_34659 | port interface HostListenerDecorator {
/**
* Decorator that declares a DOM event to listen for,
* and provides a handler method to run when that event occurs.
*
* Angular invokes the supplied handler method when the host element emits the specified event,
* and updates the bound element with the result.
*
* If the handler method returns false, applies `preventDefault` on the bound element.
*
* @usageNotes
*
* The following example declares a directive
* that attaches a click listener to a button and counts clicks.
*
* ```ts
* @Directive({selector: 'button[counting]'})
* class CountClicks {
* numberOfClicks = 0;
*
* @HostListener('click', ['$event.target'])
* onClick(btn) {
* console.log('button', btn, 'number of clicks:', this.numberOfClicks++);
* }
* }
*
* @Component({
* selector: 'app',
* template: '<button counting>Increment</button>',
* })
* class App {}
* ```
*
* The following example registers another DOM event handler that listens for `Enter` key-press
* events on the global `window`.
* ```ts
* import { HostListener, Component } from "@angular/core";
*
* @Component({
* selector: 'app',
* template: `<h1>Hello, you have pressed enter {{counter}} number of times!</h1> Press enter
* key to increment the counter. <button (click)="resetCounter()">Reset Counter</button>`
* })
* class AppComponent {
* counter = 0;
* @HostListener('window:keydown.enter', ['$event'])
* handleKeyDown(event: KeyboardEvent) {
* this.counter++;
* }
* resetCounter() {
* this.counter = 0;
* }
* }
* ```
* The list of valid key names for `keydown` and `keyup` events
* can be found here:
* https://www.w3.org/TR/DOM-Level-3-Events-key/#named-key-attribute-values
*
* Note that keys can also be combined, e.g. `@HostListener('keydown.shift.a')`.
*
* The global target names that can be used to prefix an event name are
* `document:`, `window:` and `body:`.
*
*/
(eventName: string, args?: string[]): any;
new (eventName: string, args?: string[]): any;
}
/**
* Type of the HostListener metadata.
*
* @publicApi
*/
export interface HostListener {
/**
* The DOM event to listen for.
*/
eventName?: string;
/**
* A set of arguments to pass to the handler method when the event occurs.
*/
args?: string[];
}
/**
* @Annotation
* @publicApi
*/
export const HostListener: HostListenerDecorator = makePropDecorator(
'HostListener',
(eventName?: string, args?: string[]) => ({eventName, args}),
);
| {
"end_byte": 34659,
"start_byte": 32008,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/directives.ts"
} |
angular/packages/core/src/metadata/resource_loading.ts_0_5583 | /**
* @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 {Component} from './directives';
/**
* Used to resolve resource URLs on `@Component` when used with JIT compilation.
*
* Example:
* ```
* @Component({
* selector: 'my-comp',
* templateUrl: 'my-comp.html', // This requires asynchronous resolution
* })
* class MyComponent{
* }
*
* // Calling `renderComponent` will fail because `renderComponent` is a synchronous process
* // and `MyComponent`'s `@Component.templateUrl` needs to be resolved asynchronously.
*
* // Calling `resolveComponentResources()` will resolve `@Component.templateUrl` into
* // `@Component.template`, which allows `renderComponent` to proceed in a synchronous manner.
*
* // Use browser's `fetch()` function as the default resource resolution strategy.
* resolveComponentResources(fetch).then(() => {
* // After resolution all URLs have been converted into `template` strings.
* renderComponent(MyComponent);
* });
*
* ```
*
* NOTE: In AOT the resolution happens during compilation, and so there should be no need
* to call this method outside JIT mode.
*
* @param resourceResolver a function which is responsible for returning a `Promise` to the
* contents of the resolved URL. Browser's `fetch()` method is a good default implementation.
*/
export function resolveComponentResources(
resourceResolver: (url: string) => Promise<string | {text(): Promise<string>}>,
): Promise<void> {
// Store all promises which are fetching the resources.
const componentResolved: Promise<void>[] = [];
// Cache so that we don't fetch the same resource more than once.
const urlMap = new Map<string, Promise<string>>();
function cachedResourceResolve(url: string): Promise<string> {
let promise = urlMap.get(url);
if (!promise) {
const resp = resourceResolver(url);
urlMap.set(url, (promise = resp.then(unwrapResponse)));
}
return promise;
}
componentResourceResolutionQueue.forEach((component: Component, type: Type<any>) => {
const promises: Promise<void>[] = [];
if (component.templateUrl) {
promises.push(
cachedResourceResolve(component.templateUrl).then((template) => {
component.template = template;
}),
);
}
const styles =
typeof component.styles === 'string' ? [component.styles] : component.styles || [];
component.styles = styles;
if (component.styleUrl && component.styleUrls?.length) {
throw new Error(
'@Component cannot define both `styleUrl` and `styleUrls`. ' +
'Use `styleUrl` if the component has one stylesheet, or `styleUrls` if it has multiple',
);
} else if (component.styleUrls?.length) {
const styleOffset = component.styles.length;
const styleUrls = component.styleUrls;
component.styleUrls.forEach((styleUrl, index) => {
styles.push(''); // pre-allocate array.
promises.push(
cachedResourceResolve(styleUrl).then((style) => {
styles[styleOffset + index] = style;
styleUrls.splice(styleUrls.indexOf(styleUrl), 1);
if (styleUrls.length == 0) {
component.styleUrls = undefined;
}
}),
);
});
} else if (component.styleUrl) {
promises.push(
cachedResourceResolve(component.styleUrl).then((style) => {
styles.push(style);
component.styleUrl = undefined;
}),
);
}
const fullyResolved = Promise.all(promises).then(() => componentDefResolved(type));
componentResolved.push(fullyResolved);
});
clearResolutionOfComponentResourcesQueue();
return Promise.all(componentResolved).then(() => undefined);
}
let componentResourceResolutionQueue = new Map<Type<any>, Component>();
// Track when existing ɵcmp for a Type is waiting on resources.
const componentDefPendingResolution = new Set<Type<any>>();
export function maybeQueueResolutionOfComponentResources(type: Type<any>, metadata: Component) {
if (componentNeedsResolution(metadata)) {
componentResourceResolutionQueue.set(type, metadata);
componentDefPendingResolution.add(type);
}
}
export function isComponentDefPendingResolution(type: Type<any>): boolean {
return componentDefPendingResolution.has(type);
}
export function componentNeedsResolution(component: Component): boolean {
return !!(
(component.templateUrl && !component.hasOwnProperty('template')) ||
(component.styleUrls && component.styleUrls.length) ||
component.styleUrl
);
}
export function clearResolutionOfComponentResourcesQueue(): Map<Type<any>, Component> {
const old = componentResourceResolutionQueue;
componentResourceResolutionQueue = new Map();
return old;
}
export function restoreComponentResolutionQueue(queue: Map<Type<any>, Component>): void {
componentDefPendingResolution.clear();
queue.forEach((_, type) => componentDefPendingResolution.add(type));
componentResourceResolutionQueue = queue;
}
export function isComponentResourceResolutionQueueEmpty() {
return componentResourceResolutionQueue.size === 0;
}
function unwrapResponse(response: string | {text(): Promise<string>}): string | Promise<string> {
return typeof response == 'string' ? response : response.text();
}
function componentDefResolved(type: Type<any>): void {
componentDefPendingResolution.delete(type);
}
| {
"end_byte": 5583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/resource_loading.ts"
} |
angular/packages/core/src/metadata/di.ts_0_6461 | /**
* @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 {makePropDecorator} from '../util/decorators';
/**
* Type of the `Attribute` decorator / constructor function.
*
* @publicApi
*/
export interface AttributeDecorator {
/**
* Specifies that a constant attribute value should be injected.
*
* The directive can inject constant string literals of host element attributes.
*
* @usageNotes
*
* Suppose we have an `<input>` element and want to know its `type`.
*
* ```html
* <input type="text">
* ```
*
* A decorator can inject string literal `text` as in the following example.
*
* {@example core/ts/metadata/metadata.ts region='attributeMetadata'}
*
* @publicApi
*/
(name: string): any;
new (name: string): Attribute;
}
/**
* Type of the Attribute metadata.
*
* @publicApi
*/
export interface Attribute {
/**
* The name of the attribute to be injected into the constructor.
*/
attributeName?: string;
}
/**
* Type of the Query metadata.
*
* @publicApi
*/
export interface Query {
descendants: boolean;
emitDistinctChangesOnly: boolean;
first: boolean;
read: any;
isViewQuery: boolean;
selector: any;
static?: boolean;
/**
* @internal
*
* Whether the query is a signal query.
*
* This option exists for JIT compatibility. Users are not expected to use this.
* Angular needs a way to capture queries from classes so that the internal query
* functions can be generated. This needs to happen before the component is instantiated.
* Due to this, for JIT compilation, signal queries need an additional decorator
* declaring the query. Angular provides a TS transformer to automatically handle this
* for JIT usage (e.g. in tests).
*/
isSignal?: boolean;
}
// Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
// explicitly set.
export const emitDistinctChangesOnlyDefaultValue = true;
/**
* Base class for query metadata.
*
* @see {@link ContentChildren}
* @see {@link ContentChild}
* @see {@link ViewChildren}
* @see {@link ViewChild}
*
* @publicApi
*/
export abstract class Query {}
/**
* Type of the ContentChildren decorator / constructor function.
*
* @see {@link ContentChildren}
* @publicApi
*/
export interface ContentChildrenDecorator {
/**
* @description
* Property decorator that configures a content query.
*
* Use to get the `QueryList` of elements or directives from the content DOM.
* Any time a child element is added, removed, or moved, the query list will be
* updated, and the changes observable of the query list will emit a new value.
*
* Content queries are set before the `ngAfterContentInit` callback is called.
*
* Does not retrieve elements or directives that are in other components' templates,
* since a component's template is always a black box to its ancestors.
*
* **Metadata Properties**:
*
* * **selector** - The directive type or the name used for querying.
* * **descendants** - If `true` include all descendants of the element. If `false` then only
* query direct children of the element.
* * **emitDistinctChangesOnly** - The ` QueryList#changes` observable will emit new values only
* if the QueryList result has changed. When `false` the `changes` observable might emit even
* if the QueryList has not changed.
* ** Note: *** This config option is **deprecated**, it will be permanently set to `true` and
* removed in future versions of Angular.
* * **read** - Used to read a different token from the queried elements.
*
* The following selectors are supported.
* * Any class with the `@Component` or `@Directive` decorator
* * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>`
* with `@ContentChildren('cmp')`)
* * Any provider defined in the child component tree of the current component (e.g.
* `@ContentChildren(SomeService) someService: SomeService`)
* * Any provider defined through a string token (e.g. `@ContentChildren('someToken')
* someTokenVal: any`)
* * A `TemplateRef` (e.g. query `<ng-template></ng-template>` with
* `@ContentChildren(TemplateRef) template;`)
*
* In addition, multiple string selectors can be separated with a comma (e.g.
* `@ContentChildren('cmp1,cmp2')`)
*
* The following values are supported by `read`:
* * Any class with the `@Component` or `@Directive` decorator
* * Any provider defined on the injector of the component that is matched by the `selector` of
* this query
* * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`)
* * `TemplateRef`, `ElementRef`, and `ViewContainerRef`
*
* @usageNotes
*
* Here is a simple demonstration of how the `ContentChildren` decorator can be used.
*
* {@example core/di/ts/contentChildren/content_children_howto.ts region='HowTo'}
*
* ### Tab-pane example
*
* Here is a slightly more realistic example that shows how `ContentChildren` decorators
* can be used to implement a tab pane component.
*
* {@example core/di/ts/contentChildren/content_children_example.ts region='Component'}
*
* @Annotation
*/
(
selector: ProviderToken<unknown> | Function | string,
opts?: {
descendants?: boolean;
emitDistinctChangesOnly?: boolean;
read?: any;
},
): any;
new (
selector: ProviderToken<unknown> | Function | string,
opts?: {descendants?: boolean; emitDistinctChangesOnly?: boolean; read?: any},
): Query;
}
/**
* Type of the ContentChildren metadata.
*
*
* @Annotation
* @publicApi
*/
export type ContentChildren = Query;
/**
* ContentChildren decorator and metadata.
*
*
* @Annotation
* @publicApi
*/
export const ContentChildren: ContentChildrenDecorator = makePropDecorator(
'ContentChildren',
(selector?: any, opts: any = {}) => ({
selector,
first: false,
isViewQuery: false,
descendants: false,
emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
...opts,
}),
Query,
);
/**
* Type of the ContentChild decorator / constructor function.
*
* @publicApi
*/ | {
"end_byte": 6461,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/di.ts"
} |
angular/packages/core/src/metadata/di.ts_6462_13537 | export interface ContentChildDecorator {
/**
* @description
* Property decorator that configures a content query.
*
* Use to get the first element or the directive matching the selector from the content DOM.
* If the content DOM changes, and a new child matches the selector,
* the property will be updated.
*
* Does not retrieve elements or directives that are in other components' templates,
* since a component's template is always a black box to its ancestors.
*
* **Metadata Properties**:
*
* * **selector** - The directive type or the name used for querying.
* * **descendants** - If `true` (default) include all descendants of the element. If `false` then
* only query direct children of the element.
* * **read** - Used to read a different token from the queried element.
* * **static** - True to resolve query results before change detection runs,
* false to resolve after change detection. Defaults to false.
*
* The following selectors are supported.
* * Any class with the `@Component` or `@Directive` decorator
* * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>`
* with `@ContentChild('cmp')`)
* * Any provider defined in the child component tree of the current component (e.g.
* `@ContentChild(SomeService) someService: SomeService`)
* * Any provider defined through a string token (e.g. `@ContentChild('someToken') someTokenVal:
* any`)
* * A `TemplateRef` (e.g. query `<ng-template></ng-template>` with `@ContentChild(TemplateRef)
* template;`)
*
* The following values are supported by `read`:
* * Any class with the `@Component` or `@Directive` decorator
* * Any provider defined on the injector of the component that is matched by the `selector` of
* this query
* * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`)
* * `TemplateRef`, `ElementRef`, and `ViewContainerRef`
*
* Difference between dynamic and static queries:
*
* | Queries | Details |
* |:--- |:--- |
* | Dynamic queries \(`static: false`\) | The query resolves before the `ngAfterContentInit()`
* callback is called. The result will be updated for changes to your view, such as changes to
* `ngIf` and `ngFor` blocks. | | Static queries \(`static: true`\) | The query resolves once
* the view has been created, but before change detection runs (before the `ngOnInit()` callback
* is called). The result, though, will never be updated to reflect changes to your view, such as
* changes to `ngIf` and `ngFor` blocks. |
*
* @usageNotes
*
* {@example core/di/ts/contentChild/content_child_howto.ts region='HowTo'}
*
* ### Example
*
* {@example core/di/ts/contentChild/content_child_example.ts region='Component'}
*
* @Annotation
*/
(
selector: ProviderToken<unknown> | Function | string,
opts?: {descendants?: boolean; read?: any; static?: boolean},
): any;
new (
selector: ProviderToken<unknown> | Function | string,
opts?: {descendants?: boolean; read?: any; static?: boolean},
): ContentChild;
}
/**
* Type of the ContentChild metadata.
*
* @publicApi
*/
export type ContentChild = Query;
/**
* ContentChild decorator and metadata.
*
*
* @Annotation
*
* @publicApi
*/
export const ContentChild: ContentChildDecorator = makePropDecorator(
'ContentChild',
(selector?: any, opts: any = {}) => ({
selector,
first: true,
isViewQuery: false,
descendants: true,
...opts,
}),
Query,
);
/**
* Type of the ViewChildren decorator / constructor function.
*
* @see {@link ViewChildren}
*
* @publicApi
*/
export interface ViewChildrenDecorator {
/**
* @description
* Property decorator that configures a view query.
*
* Use to get the `QueryList` of elements or directives from the view DOM.
* Any time a child element is added, removed, or moved, the query list will be updated,
* and the changes observable of the query list will emit a new value.
*
* View queries are set before the `ngAfterViewInit` callback is called.
*
* **Metadata Properties**:
*
* * **selector** - The directive type or the name used for querying.
* * **read** - Used to read a different token from the queried elements.
* * **emitDistinctChangesOnly** - The ` QueryList#changes` observable will emit new values only
* if the QueryList result has changed. When `false` the `changes` observable might emit even
* if the QueryList has not changed.
* ** Note: *** This config option is **deprecated**, it will be permanently set to `true` and
* removed in future versions of Angular.
*
* The following selectors are supported.
* * Any class with the `@Component` or `@Directive` decorator
* * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>`
* with `@ViewChildren('cmp')`)
* * Any provider defined in the child component tree of the current component (e.g.
* `@ViewChildren(SomeService) someService!: SomeService`)
* * Any provider defined through a string token (e.g. `@ViewChildren('someToken')
* someTokenVal!: any`)
* * A `TemplateRef` (e.g. query `<ng-template></ng-template>` with `@ViewChildren(TemplateRef)
* template;`)
*
* In addition, multiple string selectors can be separated with a comma (e.g.
* `@ViewChildren('cmp1,cmp2')`)
*
* The following values are supported by `read`:
* * Any class with the `@Component` or `@Directive` decorator
* * Any provider defined on the injector of the component that is matched by the `selector` of
* this query
* * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`)
* * `TemplateRef`, `ElementRef`, and `ViewContainerRef`
*
* @usageNotes
*
* {@example core/di/ts/viewChildren/view_children_howto.ts region='HowTo'}
*
* ### Another example
*
* {@example core/di/ts/viewChildren/view_children_example.ts region='Component'}
*
* @Annotation
*/
(
selector: ProviderToken<unknown> | Function | string,
opts?: {read?: any; emitDistinctChangesOnly?: boolean},
): any;
new (
selector: ProviderToken<unknown> | Function | string,
opts?: {read?: any; emitDistinctChangesOnly?: boolean},
): ViewChildren;
}
/**
* Type of the ViewChildren metadata.
*
* @publicApi
*/
export type ViewChildren = Query;
/**
* ViewChildren decorator and metadata.
*
* @Annotation
* @publicApi
*/
export const ViewChildren: ViewChildrenDecorator = makePropDecorator(
'ViewChildren',
(selector?: any, opts: any = {}) => ({
selector,
first: false,
isViewQuery: true,
descendants: true,
emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue,
...opts,
}),
Query,
);
/**
* Type of the ViewChild decorator / constructor function.
*
* @see {@link ViewChild}
* @publicApi
*/ | {
"end_byte": 13537,
"start_byte": 6462,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/di.ts"
} |
angular/packages/core/src/metadata/di.ts_13538_16704 | export interface ViewChildDecorator {
/**
* @description
* Property decorator that configures a view query.
* The change detector looks for the first element or the directive matching the selector
* in the view DOM. If the view DOM changes, and a new child matches the selector,
* the property is updated.
*
* **Metadata Properties**:
*
* * **selector** - The directive type or the name used for querying.
* * **read** - Used to read a different token from the queried elements.
* * **static** - `true` to resolve query results before change detection runs,
* `false` to resolve after change detection. Defaults to `false`.
*
*
* The following selectors are supported.
* * Any class with the `@Component` or `@Directive` decorator
* * A template reference variable as a string (e.g. query `<my-component #cmp></my-component>`
* with `@ViewChild('cmp')`)
* * Any provider defined in the child component tree of the current component (e.g.
* `@ViewChild(SomeService) someService: SomeService`)
* * Any provider defined through a string token (e.g. `@ViewChild('someToken') someTokenVal:
* any`)
* * A `TemplateRef` (e.g. query `<ng-template></ng-template>` with `@ViewChild(TemplateRef)
* template;`)
*
* The following values are supported by `read`:
* * Any class with the `@Component` or `@Directive` decorator
* * Any provider defined on the injector of the component that is matched by the `selector` of
* this query
* * Any provider defined through a string token (e.g. `{provide: 'token', useValue: 'val'}`)
* * `TemplateRef`, `ElementRef`, and `ViewContainerRef`
*
* Difference between dynamic and static queries:
* * Dynamic queries \(`static: false`\) - The query resolves before the `ngAfterViewInit()`
* callback is called. The result will be updated for changes to your view, such as changes to
* `ngIf` and `ngFor` blocks.
* * Static queries \(`static: true`\) - The query resolves once
* the view has been created, but before change detection runs (before the `ngOnInit()` callback
* is called). The result, though, will never be updated to reflect changes to your view, such as
* changes to `ngIf` and `ngFor` blocks.
*
* @usageNotes
*
* ### Example 1
*
* {@example core/di/ts/viewChild/view_child_example.ts region='Component'}
*
* ### Example 2
*
* {@example core/di/ts/viewChild/view_child_howto.ts region='HowTo'}
*
* @Annotation
*/
(
selector: ProviderToken<unknown> | Function | string,
opts?: {read?: any; static?: boolean},
): any;
new (
selector: ProviderToken<unknown> | Function | string,
opts?: {read?: any; static?: boolean},
): ViewChild;
}
/**
* Type of the ViewChild metadata.
*
* @publicApi
*/
export type ViewChild = Query;
/**
* ViewChild decorator and metadata.
*
* @Annotation
* @publicApi
*/
export const ViewChild: ViewChildDecorator = makePropDecorator(
'ViewChild',
(selector: any, opts: any) => ({
selector,
first: true,
isViewQuery: true,
descendants: true,
...opts,
}),
Query,
); | {
"end_byte": 16704,
"start_byte": 13538,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/metadata/di.ts"
} |
angular/packages/core/src/compiler/compiler_facade.ts_0_2154 | /**
* @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 {global} from '../util/global';
import {CompilerFacade, ExportedCompilerFacade, Type} from './compiler_facade_interface';
export * from './compiler_facade_interface';
export const enum JitCompilerUsage {
Decorator,
PartialDeclaration,
}
interface JitCompilerUsageRequest {
usage: JitCompilerUsage;
kind: 'directive' | 'component' | 'pipe' | 'injectable' | 'NgModule';
type: Type;
}
export function getCompilerFacade(request: JitCompilerUsageRequest): CompilerFacade {
const globalNg: ExportedCompilerFacade = global['ng'];
if (globalNg && globalNg.ɵcompilerFacade) {
return globalNg.ɵcompilerFacade;
}
if (typeof ngDevMode === 'undefined' || ngDevMode) {
// Log the type as an error so that a developer can easily navigate to the type from the
// console.
console.error(`JIT compilation failed for ${request.kind}`, request.type);
let message = `The ${request.kind} '${request.type.name}' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.\n\n`;
if (request.usage === JitCompilerUsage.PartialDeclaration) {
message += `The ${request.kind} is part of a library that has been partially compiled.\n`;
message += `However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.\n`;
message += '\n';
message += `Ideally, the library is processed using the Angular Linker to become fully AOT compiled.\n`;
} else {
message += `JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.\n`;
}
message += `Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',\n`;
message += `or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`;
throw new Error(message);
} else {
throw new Error('JIT compiler unavailable');
}
}
| {
"end_byte": 2154,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/compiler/compiler_facade.ts"
} |
angular/packages/core/src/compiler/BUILD.bazel_0_631 | load("//tools:defaults.bzl", "ts_library", "tsec_test")
package(default_visibility = [
"//packages:__pkg__",
"//packages/compiler/test:__pkg__",
"//packages/core:__subpackages__",
"//tools/public_api_guard:__pkg__",
])
ts_library(
name = "compiler",
srcs = glob(
[
"**/*.ts",
],
),
deps = [
"//packages/core/src/util",
],
)
tsec_test(
name = "tsec_test",
target = "compiler",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 631,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/compiler/BUILD.bazel"
} |
angular/packages/core/src/compiler/compiler_facade_interface.ts_0_8243 | /**
* @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 interfaces which are shared between `@angular/core` and `@angular/compiler` to allow
* for late binding of `@angular/compiler` for JIT purposes.
*
* This file has two copies. Please ensure that they are in sync:
* - packages/compiler/src/compiler_facade_interface.ts (main)
* - packages/core/src/compiler/compiler_facade_interface.ts (replica)
*
* Please ensure that the two files are in sync using this command:
* ```
* cp packages/compiler/src/compiler_facade_interface.ts \
* packages/core/src/compiler/compiler_facade_interface.ts
* ```
*/
export interface ExportedCompilerFacade {
ɵcompilerFacade: CompilerFacade;
}
export interface CompilerFacade {
compilePipe(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3PipeMetadataFacade,
): any;
compilePipeDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclarePipeFacade,
): any;
compileInjectable(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3InjectableMetadataFacade,
): any;
compileInjectableDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DeclareInjectableFacade,
): any;
compileInjector(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3InjectorMetadataFacade,
): any;
compileInjectorDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareInjectorFacade,
): any;
compileNgModule(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3NgModuleMetadataFacade,
): any;
compileNgModuleDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareNgModuleFacade,
): any;
compileDirective(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DirectiveMetadataFacade,
): any;
compileDirectiveDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareDirectiveFacade,
): any;
compileComponent(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3ComponentMetadataFacade,
): any;
compileComponentDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
declaration: R3DeclareComponentFacade,
): any;
compileFactory(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3FactoryDefMetadataFacade,
): any;
compileFactoryDeclaration(
angularCoreEnv: CoreEnvironment,
sourceMapUrl: string,
meta: R3DeclareFactoryFacade,
): any;
createParseSourceSpan(kind: string, typeName: string, sourceUrl: string): ParseSourceSpan;
FactoryTarget: typeof FactoryTarget;
// Note that we do not use `{new(): ResourceLoader}` here because
// the resource loader class is abstract and not constructable.
ResourceLoader: Function & {prototype: ResourceLoader};
}
export interface CoreEnvironment {
[name: string]: unknown;
}
export type ResourceLoader = {
get(url: string): Promise<string> | string;
};
export type Provider = unknown;
export type Type = Function;
export type OpaqueValue = unknown;
export enum FactoryTarget {
Directive = 0,
Component = 1,
Injectable = 2,
Pipe = 3,
NgModule = 4,
}
export interface R3DependencyMetadataFacade {
token: OpaqueValue;
attribute: string | null;
host: boolean;
optional: boolean;
self: boolean;
skipSelf: boolean;
}
export interface R3DeclareDependencyMetadataFacade {
token: OpaqueValue;
attribute?: boolean;
host?: boolean;
optional?: boolean;
self?: boolean;
skipSelf?: boolean;
}
export interface R3PipeMetadataFacade {
name: string;
type: Type;
pipeName: string;
pure: boolean;
isStandalone: boolean;
}
export interface R3InjectableMetadataFacade {
name: string;
type: Type;
typeArgumentCount: number;
providedIn?: Type | 'root' | 'platform' | 'any' | null;
useClass?: OpaqueValue;
useFactory?: OpaqueValue;
useExisting?: OpaqueValue;
useValue?: OpaqueValue;
deps?: R3DependencyMetadataFacade[];
}
export interface R3NgModuleMetadataFacade {
type: Type;
bootstrap: Function[];
declarations: Function[];
imports: Function[];
exports: Function[];
schemas: {name: string}[] | null;
id: string | null;
}
export interface R3InjectorMetadataFacade {
name: string;
type: Type;
providers: Provider[];
imports: OpaqueValue[];
}
export interface R3HostDirectiveMetadataFacade {
directive: Type;
inputs?: string[];
outputs?: string[];
}
export interface R3DirectiveMetadataFacade {
name: string;
type: Type;
typeSourceSpan: ParseSourceSpan;
selector: string | null;
queries: R3QueryMetadataFacade[];
host: {[key: string]: string};
propMetadata: {[key: string]: OpaqueValue[]};
lifecycle: {usesOnChanges: boolean};
inputs: (string | {name: string; alias?: string; required?: boolean})[];
outputs: string[];
usesInheritance: boolean;
exportAs: string[] | null;
providers: Provider[] | null;
viewQueries: R3QueryMetadataFacade[];
isStandalone: boolean;
isSignal: boolean;
hostDirectives: R3HostDirectiveMetadataFacade[] | null;
}
export interface R3ComponentMetadataFacade extends R3DirectiveMetadataFacade {
template: string;
preserveWhitespaces: boolean;
animations: OpaqueValue[] | undefined;
declarations: R3TemplateDependencyFacade[];
styles: string[];
encapsulation: ViewEncapsulation;
viewProviders: Provider[] | null;
interpolation?: [string, string];
changeDetection?: ChangeDetectionStrategy;
}
// TODO(legacy-partial-output-inputs): Remove in v18.
// https://github.com/angular/angular/blob/d4b423690210872b5c32a322a6090beda30b05a3/packages/core/src/compiler/compiler_facade_interface.ts#L197-L199
export type LegacyInputPartialMapping =
| string
| [bindingPropertyName: string, classPropertyName: string, transformFunction?: Function];
export interface R3DeclareDirectiveFacade {
selector?: string;
type: Type;
version: string;
inputs?: {
[fieldName: string]:
| {
classPropertyName: string;
publicName: string;
isSignal: boolean;
isRequired: boolean;
transformFunction: Function | null;
}
| LegacyInputPartialMapping;
};
outputs?: {[classPropertyName: string]: string};
host?: {
attributes?: {[key: string]: OpaqueValue};
listeners?: {[key: string]: string};
properties?: {[key: string]: string};
classAttribute?: string;
styleAttribute?: string;
};
queries?: R3DeclareQueryMetadataFacade[];
viewQueries?: R3DeclareQueryMetadataFacade[];
providers?: OpaqueValue;
exportAs?: string[];
usesInheritance?: boolean;
usesOnChanges?: boolean;
isStandalone?: boolean;
hostDirectives?: R3HostDirectiveMetadataFacade[] | null;
isSignal?: boolean;
}
export interface R3DeclareComponentFacade extends R3DeclareDirectiveFacade {
template: string;
isInline?: boolean;
styles?: string[];
// Post-standalone libraries use a unified dependencies field.
dependencies?: R3DeclareTemplateDependencyFacade[];
// Pre-standalone libraries have separate component/directive/pipe fields:
components?: R3DeclareDirectiveDependencyFacade[];
directives?: R3DeclareDirectiveDependencyFacade[];
pipes?: {[pipeName: string]: OpaqueValue | (() => OpaqueValue)};
deferBlockDependencies?: (() => Promise<Type> | null)[];
viewProviders?: OpaqueValue;
animations?: OpaqueValue;
changeDetection?: ChangeDetectionStrategy;
encapsulation?: ViewEncapsulation;
interpolation?: [string, string];
preserveWhitespaces?: boolean;
}
export type R3DeclareTemplateDependencyFacade = {
kind: string;
} & (
| R3DeclareDirectiveDependencyFacade
| R3DeclarePipeDependencyFacade
| R3DeclareNgModuleDependencyFacade
);
export interface R3DeclareDirectiveDependencyFacade {
kind?: 'directive' | 'component';
selector: string;
type: OpaqueValue | (() => OpaqueValue);
inputs?: string[];
outputs?: string[];
exportAs?: string[];
}
| {
"end_byte": 8243,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/compiler/compiler_facade_interface.ts"
} |
angular/packages/core/src/compiler/compiler_facade_interface.ts_8245_10700 | xport interface R3DeclarePipeDependencyFacade {
kind?: 'pipe';
name: string;
type: OpaqueValue | (() => OpaqueValue);
}
export interface R3DeclareNgModuleDependencyFacade {
kind: 'ngmodule';
type: OpaqueValue | (() => OpaqueValue);
}
export enum R3TemplateDependencyKind {
Directive = 0,
Pipe = 1,
NgModule = 2,
}
export interface R3TemplateDependencyFacade {
kind: R3TemplateDependencyKind;
type: OpaqueValue | (() => OpaqueValue);
}
export interface R3FactoryDefMetadataFacade {
name: string;
type: Type;
typeArgumentCount: number;
deps: R3DependencyMetadataFacade[] | null;
target: FactoryTarget;
}
export interface R3DeclareFactoryFacade {
type: Type;
deps: R3DeclareDependencyMetadataFacade[] | 'invalid' | null;
target: FactoryTarget;
}
export interface R3DeclareInjectableFacade {
type: Type;
providedIn?: Type | 'root' | 'platform' | 'any' | null;
useClass?: OpaqueValue;
useFactory?: OpaqueValue;
useExisting?: OpaqueValue;
useValue?: OpaqueValue;
deps?: R3DeclareDependencyMetadataFacade[];
}
export enum ViewEncapsulation {
Emulated = 0,
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
None = 2,
ShadowDom = 3,
}
export type ChangeDetectionStrategy = number;
export interface R3QueryMetadataFacade {
propertyName: string;
first: boolean;
predicate: OpaqueValue | string[];
descendants: boolean;
emitDistinctChangesOnly: boolean;
read: OpaqueValue | null;
static: boolean;
isSignal: boolean;
}
export interface R3DeclareQueryMetadataFacade {
propertyName: string;
first?: boolean;
predicate: OpaqueValue | string[];
descendants?: boolean;
read?: OpaqueValue;
static?: boolean;
emitDistinctChangesOnly?: boolean;
isSignal?: boolean;
}
export interface R3DeclareInjectorFacade {
type: Type;
imports?: OpaqueValue[];
providers?: OpaqueValue[];
}
export interface R3DeclareNgModuleFacade {
type: Type;
bootstrap?: OpaqueValue[] | (() => OpaqueValue[]);
declarations?: OpaqueValue[] | (() => OpaqueValue[]);
imports?: OpaqueValue[] | (() => OpaqueValue[]);
exports?: OpaqueValue[] | (() => OpaqueValue[]);
schemas?: OpaqueValue[];
id?: OpaqueValue;
}
export interface R3DeclarePipeFacade {
type: Type;
name: string;
version: string;
pure?: boolean;
isStandalone?: boolean;
}
export interface ParseSourceSpan {
start: any;
end: any;
details: any;
fullStart: any;
}
| {
"end_byte": 10700,
"start_byte": 8245,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/compiler/compiler_facade_interface.ts"
} |
angular/packages/core/src/debug/debug_node.ts_0_3812 | /**
* @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 {assertTNodeForLView} from '../render3/assert';
import {getLContext} from '../render3/context_discovery';
import {CONTAINER_HEADER_OFFSET, LContainer, NATIVE} from '../render3/interfaces/container';
import {TElementNode, TNode, TNodeFlags, TNodeType} from '../render3/interfaces/node';
import {isComponentHost, isLContainer} from '../render3/interfaces/type_checks';
import {
DECLARATION_COMPONENT_VIEW,
LView,
PARENT,
T_HOST,
TData,
TVIEW,
} from '../render3/interfaces/view';
import {
getComponent,
getContext,
getInjectionTokens,
getInjector,
getListeners,
getLocalRefs,
getOwningComponent,
} from '../render3/util/discovery_utils';
import {INTERPOLATION_DELIMITER} from '../render3/util/misc_utils';
import {renderStringify} from '../render3/util/stringify_utils';
import {getComponentLViewByIndex, getNativeByTNodeOrNull} from '../render3/util/view_utils';
import {assertDomNode} from '../util/assert';
/**
* @publicApi
*/
export class DebugEventListener {
constructor(
public name: string,
public callback: Function,
) {}
}
/**
* @publicApi
*/
export function asNativeElements(debugEls: DebugElement[]): any {
return debugEls.map((el) => el.nativeElement);
}
/**
* @publicApi
*/
export class DebugNode {
/**
* The underlying DOM node.
*/
readonly nativeNode: any;
constructor(nativeNode: Node) {
this.nativeNode = nativeNode;
}
/**
* The `DebugElement` parent. Will be `null` if this is the root element.
*/
get parent(): DebugElement | null {
const parent = this.nativeNode.parentNode as Element;
return parent ? new DebugElement(parent) : null;
}
/**
* The host dependency injector. For example, the root element's component instance injector.
*/
get injector(): Injector {
return getInjector(this.nativeNode);
}
/**
* The element's own component instance, if it has one.
*/
get componentInstance(): any {
const nativeElement = this.nativeNode;
return (
nativeElement && (getComponent(nativeElement as Element) || getOwningComponent(nativeElement))
);
}
/**
* An object that provides parent context for this element. Often an ancestor component instance
* that governs this element.
*
* When an element is repeated within *ngFor, the context is an `NgForOf` whose `$implicit`
* property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero
* of heroes"`.
*/
get context(): any {
return getComponent(this.nativeNode as Element) || getContext(this.nativeNode as Element);
}
/**
* The callbacks attached to the component's @Output properties and/or the element's event
* properties.
*/
get listeners(): DebugEventListener[] {
return getListeners(this.nativeNode as Element).filter((listener) => listener.type === 'dom');
}
/**
* Dictionary of objects associated with template local variables (e.g. #foo), keyed by the local
* variable name.
*/
get references(): {[key: string]: any} {
return getLocalRefs(this.nativeNode);
}
/**
* This component's injector lookup tokens. Includes the component itself plus the tokens that the
* component lists in its providers metadata.
*/
get providerTokens(): any[] {
return getInjectionTokens(this.nativeNode as Element);
}
}
/**
* @publicApi
*
* @see [Component testing scenarios](guide/testing/components-scenarios)
* @see [Basics of testing components](guide/testing/components-basics)
* @see [Testing utility APIs](guide/testing/utility-apis)
*/ | {
"end_byte": 3812,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/debug/debug_node.ts"
} |
angular/packages/core/src/debug/debug_node.ts_3813_11337 | export class DebugElement extends DebugNode {
constructor(nativeNode: Element) {
ngDevMode && assertDomNode(nativeNode);
super(nativeNode);
}
/**
* The underlying DOM element at the root of the component.
*/
get nativeElement(): any {
return this.nativeNode.nodeType == Node.ELEMENT_NODE ? (this.nativeNode as Element) : null;
}
/**
* The element tag name, if it is an element.
*/
get name(): string {
const context = getLContext(this.nativeNode)!;
const lView = context ? context.lView : null;
if (lView !== null) {
const tData = lView[TVIEW].data;
const tNode = tData[context.nodeIndex] as TNode;
return tNode.value!;
} else {
return this.nativeNode.nodeName;
}
}
/**
* Gets a map of property names to property values for an element.
*
* This map includes:
* - Regular property bindings (e.g. `[id]="id"`)
* - Host property bindings (e.g. `host: { '[id]': "id" }`)
* - Interpolated property bindings (e.g. `id="{{ value }}")
*
* It does not include:
* - input property bindings (e.g. `[myCustomInput]="value"`)
* - attribute bindings (e.g. `[attr.role]="menu"`)
*/
get properties(): {[key: string]: any} {
const context = getLContext(this.nativeNode)!;
const lView = context ? context.lView : null;
if (lView === null) {
return {};
}
const tData = lView[TVIEW].data;
const tNode = tData[context.nodeIndex] as TNode;
const properties: {[key: string]: string} = {};
// Collect properties from the DOM.
copyDomProperties(this.nativeElement, properties);
// Collect properties from the bindings. This is needed for animation renderer which has
// synthetic properties which don't get reflected into the DOM.
collectPropertyBindings(properties, tNode, lView, tData);
return properties;
}
/**
* A map of attribute names to attribute values for an element.
*/
// TODO: replace null by undefined in the return type
get attributes(): {[key: string]: string | null} {
const attributes: {[key: string]: string | null} = {};
const element = this.nativeElement as Element | undefined;
if (!element) {
return attributes;
}
const context = getLContext(element)!;
const lView = context ? context.lView : null;
if (lView === null) {
return {};
}
const tNodeAttrs = (lView[TVIEW].data[context.nodeIndex] as TNode).attrs;
const lowercaseTNodeAttrs: string[] = [];
// For debug nodes we take the element's attribute directly from the DOM since it allows us
// to account for ones that weren't set via bindings (e.g. ViewEngine keeps track of the ones
// that are set through `Renderer2`). The problem is that the browser will lowercase all names,
// however since we have the attributes already on the TNode, we can preserve the case by going
// through them once, adding them to the `attributes` map and putting their lower-cased name
// into an array. Afterwards when we're going through the native DOM attributes, we can check
// whether we haven't run into an attribute already through the TNode.
if (tNodeAttrs) {
let i = 0;
while (i < tNodeAttrs.length) {
const attrName = tNodeAttrs[i];
// Stop as soon as we hit a marker. We only care about the regular attributes. Everything
// else will be handled below when we read the final attributes off the DOM.
if (typeof attrName !== 'string') break;
const attrValue = tNodeAttrs[i + 1];
attributes[attrName] = attrValue as string;
lowercaseTNodeAttrs.push(attrName.toLowerCase());
i += 2;
}
}
for (const attr of element.attributes) {
// Make sure that we don't assign the same attribute both in its
// case-sensitive form and the lower-cased one from the browser.
if (!lowercaseTNodeAttrs.includes(attr.name)) {
attributes[attr.name] = attr.value;
}
}
return attributes;
}
/**
* The inline styles of the DOM element.
*/
// TODO: replace null by undefined in the return type
get styles(): {[key: string]: string | null} {
const element = this.nativeElement as HTMLElement | null;
return (element?.style ?? {}) as {[key: string]: string | null};
}
/**
* A map containing the class names on the element as keys.
*
* This map is derived from the `className` property of the DOM element.
*
* Note: The values of this object will always be `true`. The class key will not appear in the KV
* object if it does not exist on the element.
*
* @see [Element.className](https://developer.mozilla.org/en-US/docs/Web/API/Element/className)
*/
get classes(): {[key: string]: boolean} {
const result: {[key: string]: boolean} = {};
const element = this.nativeElement as HTMLElement | SVGElement;
// SVG elements return an `SVGAnimatedString` instead of a plain string for the `className`.
const className = element.className as string | SVGAnimatedString;
const classes =
typeof className !== 'string' ? className.baseVal.split(' ') : className.split(' ');
classes.forEach((value: string) => (result[value] = true));
return result;
}
/**
* The `childNodes` of the DOM element as a `DebugNode` array.
*
* @see [Node.childNodes](https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes)
*/
get childNodes(): DebugNode[] {
const childNodes = this.nativeNode.childNodes;
const children: DebugNode[] = [];
for (let i = 0; i < childNodes.length; i++) {
const element = childNodes[i];
children.push(getDebugNode(element)!);
}
return children;
}
/**
* The immediate `DebugElement` children. Walk the tree by descending through `children`.
*/
get children(): DebugElement[] {
const nativeElement = this.nativeElement;
if (!nativeElement) return [];
const childNodes = nativeElement.children;
const children: DebugElement[] = [];
for (let i = 0; i < childNodes.length; i++) {
const element = childNodes[i];
children.push(getDebugNode(element) as DebugElement);
}
return children;
}
/**
* @returns the first `DebugElement` that matches the predicate at any depth in the subtree.
*/
query(predicate: Predicate<DebugElement>): DebugElement {
const results = this.queryAll(predicate);
return results[0] || null;
}
/**
* @returns All `DebugElement` matches for the predicate at any depth in the subtree.
*/
queryAll(predicate: Predicate<DebugElement>): DebugElement[] {
const matches: DebugElement[] = [];
_queryAll(this, predicate, matches, true);
return matches;
}
/**
* @returns All `DebugNode` matches for the predicate at any depth in the subtree.
*/
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] {
const matches: DebugNode[] = [];
_queryAll(this, predicate, matches, false);
return matches;
}
/**
* Triggers the event by its name if there is a corresponding listener in the element's
* `listeners` collection.
*
* If the event lacks a listener or there's some other problem, consider
* calling `nativeElement.dispatchEvent(eventObject)`.
*
* @param eventName The name of the event to trigger
* @param eventObj The _event object_ expected by the handler
*
* @see [Testing components scenarios](guide/testing/components-scenarios#trigger-event-handler)
*/ | {
"end_byte": 11337,
"start_byte": 3813,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/debug/debug_node.ts"
} |
angular/packages/core/src/debug/debug_node.ts_11340_15926 | triggerEventHandler(eventName: string, eventObj?: any): void {
const node = this.nativeNode as any;
const invokedListeners: Function[] = [];
this.listeners.forEach((listener) => {
if (listener.name === eventName) {
const callback = listener.callback;
callback.call(node, eventObj);
invokedListeners.push(callback);
}
});
// We need to check whether `eventListeners` exists, because it's something
// that Zone.js only adds to `EventTarget` in browser environments.
if (typeof node.eventListeners === 'function') {
// Note that in Ivy we wrap event listeners with a call to `event.preventDefault` in some
// cases. We use '__ngUnwrap__' as a special token that gives us access to the actual event
// listener.
node.eventListeners(eventName).forEach((listener: Function) => {
// In order to ensure that we can detect the special __ngUnwrap__ token described above, we
// use `toString` on the listener and see if it contains the token. We use this approach to
// ensure that it still worked with compiled code since it cannot remove or rename string
// literals. We also considered using a special function name (i.e. if(listener.name ===
// special)) but that was more cumbersome and we were also concerned the compiled code could
// strip the name, turning the condition in to ("" === "") and always returning true.
if (listener.toString().indexOf('__ngUnwrap__') !== -1) {
const unwrappedListener = listener('__ngUnwrap__');
return (
invokedListeners.indexOf(unwrappedListener) === -1 &&
unwrappedListener.call(node, eventObj)
);
}
});
}
}
}
function copyDomProperties(element: Element | null, properties: {[name: string]: string}): void {
if (element) {
// Skip own properties (as those are patched)
let obj = Object.getPrototypeOf(element);
const NodePrototype: any = Node.prototype;
while (obj !== null && obj !== NodePrototype) {
const descriptors = Object.getOwnPropertyDescriptors(obj);
for (let key in descriptors) {
if (!key.startsWith('__') && !key.startsWith('on')) {
// don't include properties starting with `__` and `on`.
// `__` are patched values which should not be included.
// `on` are listeners which also should not be included.
const value = (element as any)[key];
if (isPrimitiveValue(value)) {
properties[key] = value;
}
}
}
obj = Object.getPrototypeOf(obj);
}
}
}
function isPrimitiveValue(value: any): boolean {
return (
typeof value === 'string' ||
typeof value === 'boolean' ||
typeof value === 'number' ||
value === null
);
}
/**
* Walk the TNode tree to find matches for the predicate.
*
* @param parentElement the element from which the walk is started
* @param predicate the predicate to match
* @param matches the list of positive matches
* @param elementsOnly whether only elements should be searched
*/
function _queryAll(
parentElement: DebugElement,
predicate: Predicate<DebugElement>,
matches: DebugElement[],
elementsOnly: true,
): void;
function _queryAll(
parentElement: DebugElement,
predicate: Predicate<DebugNode>,
matches: DebugNode[],
elementsOnly: false,
): void;
function _queryAll(
parentElement: DebugElement,
predicate: Predicate<DebugElement> | Predicate<DebugNode>,
matches: DebugElement[] | DebugNode[],
elementsOnly: boolean,
) {
const context = getLContext(parentElement.nativeNode)!;
const lView = context ? context.lView : null;
if (lView !== null) {
const parentTNode = lView[TVIEW].data[context.nodeIndex] as TNode;
_queryNodeChildren(
parentTNode,
lView,
predicate,
matches,
elementsOnly,
parentElement.nativeNode,
);
} else {
// If the context is null, then `parentElement` was either created with Renderer2 or native DOM
// APIs.
_queryNativeNodeDescendants(parentElement.nativeNode, predicate, matches, elementsOnly);
}
}
/**
* Recursively match the current TNode against the predicate, and goes on with the next ones.
*
* @param tNode the current TNode
* @param lView the LView of this TNode
* @param predicate the predicate to match
* @param matches the list of positive matches
* @param elementsOnly whether only elements should be searched
* @param rootNativeNode the root native node on which predicate should not be matched
*/ | {
"end_byte": 15926,
"start_byte": 11340,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/debug/debug_node.ts"
} |
angular/packages/core/src/debug/debug_node.ts_15927_23936 | function _queryNodeChildren(
tNode: TNode,
lView: LView,
predicate: Predicate<DebugElement> | Predicate<DebugNode>,
matches: DebugElement[] | DebugNode[],
elementsOnly: boolean,
rootNativeNode: any,
) {
ngDevMode && assertTNodeForLView(tNode, lView);
const nativeNode = getNativeByTNodeOrNull(tNode, lView);
// For each type of TNode, specific logic is executed.
if (tNode.type & (TNodeType.AnyRNode | TNodeType.ElementContainer)) {
// Case 1: the TNode is an element
// The native node has to be checked.
_addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
if (isComponentHost(tNode)) {
// If the element is the host of a component, then all nodes in its view have to be processed.
// Note: the component's content (tNode.child) will be processed from the insertion points.
const componentView = getComponentLViewByIndex(tNode.index, lView);
if (componentView && componentView[TVIEW].firstChild) {
_queryNodeChildren(
componentView[TVIEW].firstChild!,
componentView,
predicate,
matches,
elementsOnly,
rootNativeNode,
);
}
} else {
if (tNode.child) {
// Otherwise, its children have to be processed.
_queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
}
// We also have to query the DOM directly in order to catch elements inserted through
// Renderer2. Note that this is __not__ optimal, because we're walking similar trees multiple
// times. ViewEngine could do it more efficiently, because all the insertions go through
// Renderer2, however that's not the case in Ivy. This approach is being used because:
// 1. Matching the ViewEngine behavior would mean potentially introducing a dependency
// from `Renderer2` to Ivy which could bring Ivy code into ViewEngine.
// 2. It allows us to capture nodes that were inserted directly via the DOM.
nativeNode && _queryNativeNodeDescendants(nativeNode, predicate, matches, elementsOnly);
}
// In all cases, if a dynamic container exists for this node, each view inside it has to be
// processed.
const nodeOrContainer = lView[tNode.index];
if (isLContainer(nodeOrContainer)) {
_queryNodeChildrenInContainer(
nodeOrContainer,
predicate,
matches,
elementsOnly,
rootNativeNode,
);
}
} else if (tNode.type & TNodeType.Container) {
// Case 2: the TNode is a container
// The native node has to be checked.
const lContainer = lView[tNode.index];
_addQueryMatch(lContainer[NATIVE], predicate, matches, elementsOnly, rootNativeNode);
// Each view inside the container has to be processed.
_queryNodeChildrenInContainer(lContainer, predicate, matches, elementsOnly, rootNativeNode);
} else if (tNode.type & TNodeType.Projection) {
// Case 3: the TNode is a projection insertion point (i.e. a <ng-content>).
// The nodes projected at this location all need to be processed.
const componentView = lView![DECLARATION_COMPONENT_VIEW];
const componentHost = componentView[T_HOST] as TElementNode;
const head: TNode | null = (componentHost.projection as (TNode | null)[])[
tNode.projection as number
];
if (Array.isArray(head)) {
for (let nativeNode of head) {
_addQueryMatch(nativeNode, predicate, matches, elementsOnly, rootNativeNode);
}
} else if (head) {
const nextLView = componentView[PARENT]! as LView;
const nextTNode = nextLView[TVIEW].data[head.index] as TNode;
_queryNodeChildren(nextTNode, nextLView, predicate, matches, elementsOnly, rootNativeNode);
}
} else if (tNode.child) {
// Case 4: the TNode is a view.
_queryNodeChildren(tNode.child, lView, predicate, matches, elementsOnly, rootNativeNode);
}
// We don't want to go to the next sibling of the root node.
if (rootNativeNode !== nativeNode) {
// To determine the next node to be processed, we need to use the next or the projectionNext
// link, depending on whether the current node has been projected.
const nextTNode = tNode.flags & TNodeFlags.isProjected ? tNode.projectionNext : tNode.next;
if (nextTNode) {
_queryNodeChildren(nextTNode, lView, predicate, matches, elementsOnly, rootNativeNode);
}
}
}
/**
* Process all TNodes in a given container.
*
* @param lContainer the container to be processed
* @param predicate the predicate to match
* @param matches the list of positive matches
* @param elementsOnly whether only elements should be searched
* @param rootNativeNode the root native node on which predicate should not be matched
*/
function _queryNodeChildrenInContainer(
lContainer: LContainer,
predicate: Predicate<DebugElement> | Predicate<DebugNode>,
matches: DebugElement[] | DebugNode[],
elementsOnly: boolean,
rootNativeNode: any,
) {
for (let i = CONTAINER_HEADER_OFFSET; i < lContainer.length; i++) {
const childView = lContainer[i] as LView;
const firstChild = childView[TVIEW].firstChild;
if (firstChild) {
_queryNodeChildren(firstChild, childView, predicate, matches, elementsOnly, rootNativeNode);
}
}
}
/**
* Match the current native node against the predicate.
*
* @param nativeNode the current native node
* @param predicate the predicate to match
* @param matches the list of positive matches
* @param elementsOnly whether only elements should be searched
* @param rootNativeNode the root native node on which predicate should not be matched
*/
function _addQueryMatch(
nativeNode: any,
predicate: Predicate<DebugElement> | Predicate<DebugNode>,
matches: DebugElement[] | DebugNode[],
elementsOnly: boolean,
rootNativeNode: any,
) {
if (rootNativeNode !== nativeNode) {
const debugNode = getDebugNode(nativeNode);
if (!debugNode) {
return;
}
// Type of the "predicate and "matches" array are set based on the value of
// the "elementsOnly" parameter. TypeScript is not able to properly infer these
// types with generics, so we manually cast the parameters accordingly.
if (
elementsOnly &&
debugNode instanceof DebugElement &&
predicate(debugNode) &&
matches.indexOf(debugNode) === -1
) {
matches.push(debugNode);
} else if (
!elementsOnly &&
(predicate as Predicate<DebugNode>)(debugNode) &&
(matches as DebugNode[]).indexOf(debugNode) === -1
) {
(matches as DebugNode[]).push(debugNode);
}
}
}
/**
* Match all the descendants of a DOM node against a predicate.
*
* @param nativeNode the current native node
* @param predicate the predicate to match
* @param matches the list where matches are stored
* @param elementsOnly whether only elements should be searched
*/
function _queryNativeNodeDescendants(
parentNode: any,
predicate: Predicate<DebugElement> | Predicate<DebugNode>,
matches: DebugElement[] | DebugNode[],
elementsOnly: boolean,
) {
const nodes = parentNode.childNodes;
const length = nodes.length;
for (let i = 0; i < length; i++) {
const node = nodes[i];
const debugNode = getDebugNode(node);
if (debugNode) {
if (
elementsOnly &&
debugNode instanceof DebugElement &&
predicate(debugNode) &&
matches.indexOf(debugNode) === -1
) {
matches.push(debugNode);
} else if (
!elementsOnly &&
(predicate as Predicate<DebugNode>)(debugNode) &&
(matches as DebugNode[]).indexOf(debugNode) === -1
) {
(matches as DebugNode[]).push(debugNode);
}
_queryNativeNodeDescendants(node, predicate, matches, elementsOnly);
}
}
}
/**
* Iterates through the property bindings for a given node and generates
* a map of property names to values. This map only contains property bindings
* defined in templates, not in host bindings.
*/ | {
"end_byte": 23936,
"start_byte": 15927,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/debug/debug_node.ts"
} |
angular/packages/core/src/debug/debug_node.ts_23937_25960 | function collectPropertyBindings(
properties: {[key: string]: string},
tNode: TNode,
lView: LView,
tData: TData,
): void {
let bindingIndexes = tNode.propertyBindings;
if (bindingIndexes !== null) {
for (let i = 0; i < bindingIndexes.length; i++) {
const bindingIndex = bindingIndexes[i];
const propMetadata = tData[bindingIndex] as string;
const metadataParts = propMetadata.split(INTERPOLATION_DELIMITER);
const propertyName = metadataParts[0];
if (metadataParts.length > 1) {
let value = metadataParts[1];
for (let j = 1; j < metadataParts.length - 1; j++) {
value += renderStringify(lView[bindingIndex + j - 1]) + metadataParts[j + 1];
}
properties[propertyName] = value;
} else {
properties[propertyName] = lView[bindingIndex];
}
}
}
}
// Need to keep the nodes in a global Map so that multiple angular apps are supported.
const _nativeNodeToDebugNode = new Map<any, DebugNode>();
const NG_DEBUG_PROPERTY = '__ng_debug__';
/**
* @publicApi
*/
export function getDebugNode(nativeNode: any): DebugNode | null {
if (nativeNode instanceof Node) {
if (!nativeNode.hasOwnProperty(NG_DEBUG_PROPERTY)) {
(nativeNode as any)[NG_DEBUG_PROPERTY] =
nativeNode.nodeType == Node.ELEMENT_NODE
? new DebugElement(nativeNode as Element)
: new DebugNode(nativeNode);
}
return (nativeNode as any)[NG_DEBUG_PROPERTY];
}
return null;
}
export function getAllDebugNodes(): DebugNode[] {
return Array.from(_nativeNodeToDebugNode.values());
}
export function indexDebugNode(node: DebugNode) {
_nativeNodeToDebugNode.set(node.nativeNode, node);
}
export function removeDebugNodeFromIndex(node: DebugNode) {
_nativeNodeToDebugNode.delete(node.nativeNode);
}
/**
* A boolean-valued function over a value, possibly including context information
* regarding that value's position in an array.
*
* @publicApi
*/
export type Predicate<T> = (value: T) => boolean; | {
"end_byte": 25960,
"start_byte": 23937,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/debug/debug_node.ts"
} |
angular/packages/core/src/reflection/platform_reflection_capabilities.ts_0_788 | /**
* @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';
export interface PlatformReflectionCapabilities {
factory(type: Type<any>): Function;
hasLifecycleHook(type: any, lcProperty: string): boolean;
/**
* Return a list of annotations/types for constructor parameters
*/
parameters(type: Type<any>): any[][];
/**
* Return a list of annotations declared on the class
*/
annotations(type: Type<any>): any[];
/**
* Return a object literal which describes the annotations on Class fields/properties.
*/
propMetadata(typeOrFunc: Type<any>): {[key: string]: any[]};
}
| {
"end_byte": 788,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/reflection/platform_reflection_capabilities.ts"
} |
angular/packages/core/src/reflection/reflection_capabilities.ts_0_3006 | /**
* @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 {isType, Type} from '../interface/type';
import {newArray} from '../util/array_utils';
import {ANNOTATIONS, PARAMETERS, PROP_METADATA} from '../util/decorators';
import {global} from '../util/global';
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities';
/*
* #########################
* Attention: These Regular expressions have to hold even if the code is minified!
* ##########################
*/
/**
* Regular expression that detects pass-through constructors for ES5 output. This Regex
* intends to capture the common delegation pattern emitted by TypeScript and Babel. Also
* it intends to capture the pattern where existing constructors have been downleveled from
* ES2015 to ES5 using TypeScript w/ downlevel iteration. e.g.
*
* ```
* function MyClass() {
* var _this = _super.apply(this, arguments) || this;
* ```
*
* downleveled to ES5 with `downlevelIteration` for TypeScript < 4.2:
* ```
* function MyClass() {
* var _this = _super.apply(this, __spread(arguments)) || this;
* ```
*
* or downleveled to ES5 with `downlevelIteration` for TypeScript >= 4.2:
* ```
* function MyClass() {
* var _this = _super.apply(this, __spreadArray([], __read(arguments), false)) || this;
* ```
*
* More details can be found in: https://github.com/angular/angular/issues/38453.
*/
export const ES5_DELEGATE_CTOR =
/^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*(arguments|(?:[^()]+\(\[\],)?[^()]+\(arguments\).*)\)/;
/** Regular expression that detects ES2015 classes which extend from other classes. */
export const ES2015_INHERITED_CLASS = /^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{/;
/**
* Regular expression that detects ES2015 classes which extend from other classes and
* have an explicit constructor defined.
*/
export const ES2015_INHERITED_CLASS_WITH_CTOR =
/^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(/;
/**
* Regular expression that detects ES2015 classes which extend from other classes
* and inherit a constructor.
*/
export const ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR =
/^class\s+[A-Za-z\d$_]*\s*extends\s+[^{]+{[\s\S]*constructor\s*\(\)\s*{[^}]*super\(\.\.\.arguments\)/;
/**
* Determine whether a stringified type is a class which delegates its constructor
* to its parent.
*
* This is not trivial since compiled code can actually contain a constructor function
* even if the original source code did not. For instance, when the child class contains
* an initialized instance property.
*/
export function isDelegateCtor(typeStr: string): boolean {
return (
ES5_DELEGATE_CTOR.test(typeStr) ||
ES2015_INHERITED_CLASS_WITH_DELEGATE_CTOR.test(typeStr) ||
(ES2015_INHERITED_CLASS.test(typeStr) && !ES2015_INHERITED_CLASS_WITH_CTOR.test(typeStr))
);
} | {
"end_byte": 3006,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/reflection/reflection_capabilities.ts"
} |
angular/packages/core/src/reflection/reflection_capabilities.ts_3008_11369 | export class ReflectionCapabilities implements PlatformReflectionCapabilities {
private _reflect: any;
constructor(reflect?: any) {
this._reflect = reflect || global['Reflect'];
}
factory<T>(t: Type<T>): (args: any[]) => T {
return (...args: any[]) => new t(...args);
}
/** @internal */
_zipTypesAndAnnotations(paramTypes: any[], paramAnnotations: any[]): any[][] {
let result: any[][];
if (typeof paramTypes === 'undefined') {
result = newArray(paramAnnotations.length);
} else {
result = newArray(paramTypes.length);
}
for (let i = 0; i < result.length; i++) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if (typeof paramTypes === 'undefined') {
result[i] = [];
} else if (paramTypes[i] && paramTypes[i] != Object) {
result[i] = [paramTypes[i]];
} else {
result[i] = [];
}
if (paramAnnotations && paramAnnotations[i] != null) {
result[i] = result[i].concat(paramAnnotations[i]);
}
}
return result;
}
private _ownParameters(type: Type<any>, parentCtor: any): any[][] | null {
const typeStr = type.toString();
// If we have no decorators, we only have function.length as metadata.
// In that case, to detect whether a child class declared an own constructor or not,
// we need to look inside of that constructor to check whether it is
// just calling the parent.
// This also helps to work around for https://github.com/Microsoft/TypeScript/issues/12439
// that sets 'design:paramtypes' to []
// if a class inherits from another class but has no ctor declared itself.
if (isDelegateCtor(typeStr)) {
return null;
}
// Prefer the direct API.
if ((<any>type).parameters && (<any>type).parameters !== parentCtor.parameters) {
return (<any>type).parameters;
}
// API of tsickle for lowering decorators to properties on the class.
const tsickleCtorParams = (<any>type).ctorParameters;
if (tsickleCtorParams && tsickleCtorParams !== parentCtor.ctorParameters) {
// Newer tsickle uses a function closure
// Retain the non-function case for compatibility with older tsickle
const ctorParameters =
typeof tsickleCtorParams === 'function' ? tsickleCtorParams() : tsickleCtorParams;
const paramTypes = ctorParameters.map((ctorParam: any) => ctorParam && ctorParam.type);
const paramAnnotations = ctorParameters.map(
(ctorParam: any) => ctorParam && convertTsickleDecoratorIntoMetadata(ctorParam.decorators),
);
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// API for metadata created by invoking the decorators.
const paramAnnotations = type.hasOwnProperty(PARAMETERS) && (type as any)[PARAMETERS];
const paramTypes =
this._reflect &&
this._reflect.getOwnMetadata &&
this._reflect.getOwnMetadata('design:paramtypes', type);
if (paramTypes || paramAnnotations) {
return this._zipTypesAndAnnotations(paramTypes, paramAnnotations);
}
// If a class has no decorators, at least create metadata
// based on function.length.
// Note: We know that this is a real constructor as we checked
// the content of the constructor above.
return newArray<any[]>(type.length);
}
parameters(type: Type<any>): any[][] {
// Note: only report metadata if we have at least one class decorator
// to stay in sync with the static reflector.
if (!isType(type)) {
return [];
}
const parentCtor = getParentCtor(type);
let parameters = this._ownParameters(type, parentCtor);
if (!parameters && parentCtor !== Object) {
parameters = this.parameters(parentCtor);
}
return parameters || [];
}
private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[] | null {
// Prefer the direct API.
if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) {
let annotations = (<any>typeOrFunc).annotations;
if (typeof annotations === 'function' && annotations.annotations) {
annotations = annotations.annotations;
}
return annotations;
}
// API of tsickle for lowering decorators to properties on the class.
if ((<any>typeOrFunc).decorators && (<any>typeOrFunc).decorators !== parentCtor.decorators) {
return convertTsickleDecoratorIntoMetadata((<any>typeOrFunc).decorators);
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(ANNOTATIONS)) {
return (typeOrFunc as any)[ANNOTATIONS];
}
return null;
}
annotations(typeOrFunc: Type<any>): any[] {
if (!isType(typeOrFunc)) {
return [];
}
const parentCtor = getParentCtor(typeOrFunc);
const ownAnnotations = this._ownAnnotations(typeOrFunc, parentCtor) || [];
const parentAnnotations = parentCtor !== Object ? this.annotations(parentCtor) : [];
return parentAnnotations.concat(ownAnnotations);
}
private _ownPropMetadata(typeOrFunc: any, parentCtor: any): {[key: string]: any[]} | null {
// Prefer the direct API.
if (
(<any>typeOrFunc).propMetadata &&
(<any>typeOrFunc).propMetadata !== parentCtor.propMetadata
) {
let propMetadata = (<any>typeOrFunc).propMetadata;
if (typeof propMetadata === 'function' && propMetadata.propMetadata) {
propMetadata = propMetadata.propMetadata;
}
return propMetadata;
}
// API of tsickle for lowering decorators to properties on the class.
if (
(<any>typeOrFunc).propDecorators &&
(<any>typeOrFunc).propDecorators !== parentCtor.propDecorators
) {
const propDecorators = (<any>typeOrFunc).propDecorators;
const propMetadata = <{[key: string]: any[]}>{};
Object.keys(propDecorators).forEach((prop) => {
propMetadata[prop] = convertTsickleDecoratorIntoMetadata(propDecorators[prop]);
});
return propMetadata;
}
// API for metadata created by invoking the decorators.
if (typeOrFunc.hasOwnProperty(PROP_METADATA)) {
return (typeOrFunc as any)[PROP_METADATA];
}
return null;
}
propMetadata(typeOrFunc: any): {[key: string]: any[]} {
if (!isType(typeOrFunc)) {
return {};
}
const parentCtor = getParentCtor(typeOrFunc);
const propMetadata: {[key: string]: any[]} = {};
if (parentCtor !== Object) {
const parentPropMetadata = this.propMetadata(parentCtor);
Object.keys(parentPropMetadata).forEach((propName) => {
propMetadata[propName] = parentPropMetadata[propName];
});
}
const ownPropMetadata = this._ownPropMetadata(typeOrFunc, parentCtor);
if (ownPropMetadata) {
Object.keys(ownPropMetadata).forEach((propName) => {
const decorators: any[] = [];
if (propMetadata.hasOwnProperty(propName)) {
decorators.push(...propMetadata[propName]);
}
decorators.push(...ownPropMetadata[propName]);
propMetadata[propName] = decorators;
});
}
return propMetadata;
}
ownPropMetadata(typeOrFunc: any): {[key: string]: any[]} {
if (!isType(typeOrFunc)) {
return {};
}
return this._ownPropMetadata(typeOrFunc, getParentCtor(typeOrFunc)) || {};
}
hasLifecycleHook(type: any, lcProperty: string): boolean {
return type instanceof Type && lcProperty in type.prototype;
}
}
function convertTsickleDecoratorIntoMetadata(decoratorInvocations: any[]): any[] {
if (!decoratorInvocations) {
return [];
}
return decoratorInvocations.map((decoratorInvocation) => {
const decoratorType = decoratorInvocation.type;
const annotationCls = decoratorType.annotationCls;
const annotationArgs = decoratorInvocation.args ? decoratorInvocation.args : [];
return new annotationCls(...annotationArgs);
});
}
function getParentCtor(ctor: Function): Type<any> {
const parentProto = ctor.prototype ? Object.getPrototypeOf(ctor.prototype) : null;
const parentCtor = parentProto ? parentProto.constructor : null;
// Note: We always use `Object` as the null value
// to simplify checking later on.
return parentCtor || Object;
} | {
"end_byte": 11369,
"start_byte": 3008,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/reflection/reflection_capabilities.ts"
} |
angular/packages/core/src/reflection/BUILD.bazel_0_636 | load("//tools:defaults.bzl", "ts_library", "tsec_test")
package(default_visibility = [
"//packages:__pkg__",
"//packages/core:__subpackages__",
"//tools/public_api_guard:__pkg__",
])
ts_library(
name = "reflection",
srcs = glob(
[
"**/*.ts",
],
),
deps = [
"//packages/core/src/interface",
"//packages/core/src/util",
],
)
tsec_test(
name = "tsec_test",
target = "reflection",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 636,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/src/reflection/BUILD.bazel"
} |
angular/packages/platform-server/PACKAGE.md_0_171 | Supports delivery of Angular apps on a server, for use with server-side rendering.
For more information, see [Server-side Rendering: An intro to Angular SSR](guide/ssr).
| {
"end_byte": 171,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/PACKAGE.md"
} |
angular/packages/platform-server/BUILD.bazel_0_2583 | load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//tools:defaults.bzl", "api_golden_test_npm_package", "esbuild", "generate_api_docs", "ng_module", "ng_package", "tsec_test")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "platform-server",
package_name = "@angular/platform-server",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
exclude = ["src/bundled-domino.d.ts"],
),
deps = [
":bundled_domino_lib",
"//packages/animations/browser",
"//packages/common",
"//packages/common/http",
"//packages/compiler",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser/animations",
"//packages/zone.js/lib:zone_d_ts",
"@npm//@types/node",
"@npm//rxjs",
"@npm//xhr2",
],
)
esbuild(
name = "bundled_domino",
entry_point = "@npm//:node_modules/domino/lib/index.js",
format = "esm",
output = "src/bundled-domino.mjs",
deps = ["@npm//domino"],
)
js_library(
name = "bundled_domino_lib",
srcs = [
"src/bundled-domino.d.ts",
":bundled_domino",
],
)
tsec_test(
name = "tsec_test",
target = "platform-server",
tsconfig = "//packages:tsec_config",
)
ng_package(
name = "npm_package",
srcs = [
"package.json",
],
externals = [
"xhr2",
],
tags = [
"release-with-framework",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//adev:__pkg__",
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
"//packages/compiler-cli/integrationtest:__pkg__",
],
deps = [
":platform-server",
"//packages/platform-server/init",
"//packages/platform-server/testing",
],
)
api_golden_test_npm_package(
name = "platform-server_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/platform-server",
npm_package = "angular/packages/platform-server/npm_package",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-server_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-server",
)
| {
"end_byte": 2583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/BUILD.bazel"
} |
angular/packages/platform-server/index.ts_0_481 | /**
* @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 is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verification. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 481,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/index.ts"
} |
angular/packages/platform-server/public_api.ts_0_438 | /**
* @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
*/
/// <reference types="node" />
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/platform-server';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 438,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/public_api.ts"
} |
angular/packages/platform-server/init/PACKAGE.md_0_599 | Initializes the server environment for rendering an Angular application.
For example, it provides shims (such as DOM globals) for the server environment.
The initialization happens as a [side effect of importing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_a_module_for_its_side_effects_only) the entry point (i.e. there are no specific exports):
```ts
import '@angular/platform-server/init';
```
<div class="alert is-important">
The import must come before any imports (direct or transitive) that rely on DOM built-ins being available.
</div>
| {
"end_byte": 599,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/PACKAGE.md"
} |
angular/packages/platform-server/init/BUILD.bazel_0_951 | load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//tools:defaults.bzl", "esbuild", "ng_module", "tsec_test")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "init",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
exclude = ["src/bundled-domino.d.ts"],
),
deps = [
":bundled_domino_lib",
],
)
esbuild(
name = "bundled_domino",
entry_point = "@npm//:node_modules/domino/lib/index.js",
format = "esm",
output = "src/bundled-domino.mjs",
deps = ["@npm//domino"],
)
js_library(
name = "bundled_domino_lib",
srcs = [
"src/bundled-domino.d.ts",
":bundled_domino",
],
)
tsec_test(
name = "tsec_test",
target = "init",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
| {
"end_byte": 951,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/BUILD.bazel"
} |
angular/packages/platform-server/init/index.ts_0_480 | /**
* @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 is not used to build this module. It is only used during editing
// by the TypeScript language service and during build for verifcation. `ngc`
// replaces this file with production index.ts when it rewrites private symbol
// names.
export * from './public_api';
| {
"end_byte": 480,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/index.ts"
} |
angular/packages/platform-server/init/public_api.ts_0_319 | /**
* @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
*/
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/init';
| {
"end_byte": 319,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/public_api.ts"
} |
angular/packages/platform-server/init/test/BUILD.bazel_0_671 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/platform-server/init/index.mjs",
deps = ["//packages/platform-server/init"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages/platform-server/init",
"//packages/platform-server/init:bundled_domino_lib",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node_no_angular"],
deps = [
":test_lib",
],
)
| {
"end_byte": 671,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/test/BUILD.bazel"
} |
angular/packages/platform-server/init/test/shims_spec.ts_0_1132 | /**
* @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 domino from '../src/bundled-domino';
import {applyShims} from '../src/shims';
describe('applyShims()', () => {
const globalClone = {...global};
afterEach(() => {
// Un-patch `global`.
const currentProps = Object.keys(global);
for (const prop of currentProps) {
if (globalClone.hasOwnProperty(prop)) {
(global as any)[prop] = (globalClone as any)[prop];
} else {
delete (global as any)[prop];
}
}
});
it('should load `domino.impl` onto `global`', () => {
expect(global).not.toEqual(jasmine.objectContaining(domino.impl));
applyShims();
expect(global).toEqual(jasmine.objectContaining(domino.impl));
});
it('should define `KeyboardEvent` on `global`', () => {
expect((global as any).KeyboardEvent).not.toBe((domino.impl as any).Event);
applyShims();
expect((global as any).KeyboardEvent).toBe((domino.impl as any).Event);
});
});
| {
"end_byte": 1132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/test/shims_spec.ts"
} |
angular/packages/platform-server/init/src/init.ts_0_366 | /**
* @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
*/
/**
* @module
* @description
* Entry point for all initialization APIs of the platform-server package.
*/
import {applyShims} from './shims';
applyShims();
| {
"end_byte": 366,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/src/init.ts"
} |
angular/packages/platform-server/init/src/shims.ts_0_671 | /**
* @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 domino from './bundled-domino';
/**
* Apply the necessary shims to make DOM globals (such as `Element`, `HTMLElement`, etc.) available
* on the environment.
*/
export function applyShims(): void {
// Make all Domino types available in the global env.
// NB: Any changes here should also be done in `packages/platform-server/src/domino_adapter.ts`.
Object.assign(globalThis, domino.impl);
(globalThis as any)['KeyboardEvent'] = domino.impl.Event;
}
| {
"end_byte": 671,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/src/shims.ts"
} |
angular/packages/platform-server/init/src/bundled-domino.d.ts_0_257 | /**
* @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 domino from 'domino';
export default domino;
| {
"end_byte": 257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/init/src/bundled-domino.d.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_0_7786 | /**
* @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 '@angular/compiler';
import {animate, AnimationBuilder, state, style, transition, trigger} from '@angular/animations';
import {DOCUMENT, isPlatformServer, PlatformLocation, ɵgetDOM as getDOM} from '@angular/common';
import {
HTTP_INTERCEPTORS,
HttpClient,
HttpClientModule,
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {
ApplicationConfig,
ApplicationRef,
Component,
destroyPlatform,
EnvironmentProviders,
HostListener,
Inject,
inject as coreInject,
Injectable,
Input,
makeStateKey,
mergeApplicationConfig,
NgModule,
NgModuleRef,
NgZone,
PLATFORM_ID,
Provider,
TransferState,
Type,
ViewEncapsulation,
ɵPendingTasks as PendingTasks,
ɵwhenStable as whenStable,
APP_INITIALIZER,
inject,
getPlatform,
} from '@angular/core';
import {SSR_CONTENT_INTEGRITY_MARKER} from '@angular/core/src/hydration/utils';
import {TestBed} from '@angular/core/testing';
import {
bootstrapApplication,
BrowserModule,
provideClientHydration,
Title,
} from '@angular/platform-browser';
import {
BEFORE_APP_SERIALIZED,
INITIAL_CONFIG,
platformServer,
PlatformState,
provideServerRendering,
renderModule,
ServerModule,
} from '@angular/platform-server';
import {provideRouter, RouterOutlet, Routes} from '@angular/router';
import {Observable} from 'rxjs';
import {renderApplication, SERVER_CONTEXT} from '../src/utils';
const APP_CONFIG: ApplicationConfig = {
providers: [provideServerRendering()],
};
function getStandaloneBootstrapFn(
component: Type<unknown>,
providers: Array<Provider | EnvironmentProviders> = [],
): () => Promise<ApplicationRef> {
return () => bootstrapApplication(component, mergeApplicationConfig(APP_CONFIG, {providers}));
}
function createMyServerApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: `Works!`,
})
class MyServerApp {}
return MyServerApp;
}
const MyServerApp = createMyServerApp(false);
const MyServerAppStandalone = createMyServerApp(true);
@NgModule({
declarations: [MyServerApp],
exports: [MyServerApp],
})
export class MyServerAppModule {}
function createAppWithPendingTask(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: `Completed: {{ completed }}`,
})
class PendingTasksApp {
completed = 'No';
constructor() {
const pendingTasks = coreInject(PendingTasks);
const taskId = pendingTasks.add();
setTimeout(() => {
pendingTasks.remove(taskId);
this.completed = 'Yes';
});
}
}
return PendingTasksApp;
}
const PendingTasksApp = createAppWithPendingTask(false);
const PendingTasksAppStandalone = createAppWithPendingTask(true);
@NgModule({
declarations: [PendingTasksApp],
exports: [PendingTasksApp],
imports: [ServerModule],
bootstrap: [PendingTasksApp],
})
export class PendingTasksAppModule {}
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, ServerModule],
})
class ExampleModule {}
function getTitleRenderHook(doc: any) {
return () => {
// Set the title as part of the render hook.
doc.title = 'RenderHook';
};
}
function exceptionRenderHook() {
throw new Error('error');
}
function getMetaRenderHook(doc: any) {
return () => {
// Add a meta tag before rendering the document.
const metaElement = doc.createElement('meta');
metaElement.setAttribute('name', 'description');
doc.head.appendChild(metaElement);
};
}
function getAsyncTitleRenderHook(doc: any) {
return () => {
// Async set the title as part of the render hook.
return new Promise<void>((resolve) => {
setTimeout(() => {
doc.title = 'AsyncRenderHook';
resolve();
});
});
};
}
function asyncRejectRenderHook() {
return () => {
return new Promise<void>((_resolve, reject) => {
setTimeout(() => {
reject('reject');
});
});
};
}
const RenderHookProviders = [
{provide: BEFORE_APP_SERIALIZED, useFactory: getTitleRenderHook, multi: true, deps: [DOCUMENT]},
];
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, BrowserModule, ServerModule],
providers: [...RenderHookProviders],
})
class RenderHookModule {}
const MultiRenderHookProviders = [
{provide: BEFORE_APP_SERIALIZED, useFactory: getTitleRenderHook, multi: true, deps: [DOCUMENT]},
{provide: BEFORE_APP_SERIALIZED, useValue: exceptionRenderHook, multi: true},
{provide: BEFORE_APP_SERIALIZED, useFactory: getMetaRenderHook, multi: true, deps: [DOCUMENT]},
];
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, BrowserModule, ServerModule],
providers: [...MultiRenderHookProviders],
})
class MultiRenderHookModule {}
const AsyncRenderHookProviders = [
{
provide: BEFORE_APP_SERIALIZED,
useFactory: getAsyncTitleRenderHook,
multi: true,
deps: [DOCUMENT],
},
];
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, BrowserModule, ServerModule],
providers: [...AsyncRenderHookProviders],
})
class AsyncRenderHookModule {}
const AsyncMultiRenderHookProviders = [
{provide: BEFORE_APP_SERIALIZED, useFactory: getMetaRenderHook, multi: true, deps: [DOCUMENT]},
{
provide: BEFORE_APP_SERIALIZED,
useFactory: getAsyncTitleRenderHook,
multi: true,
deps: [DOCUMENT],
},
{provide: BEFORE_APP_SERIALIZED, useFactory: asyncRejectRenderHook, multi: true},
];
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, BrowserModule, ServerModule],
providers: [...AsyncMultiRenderHookProviders],
})
class AsyncMultiRenderHookModule {}
@Component({
selector: 'app',
template: `Works too!`,
standalone: false,
})
class MyServerApp2 {}
@NgModule({declarations: [MyServerApp2], imports: [ServerModule], bootstrap: [MyServerApp2]})
class ExampleModule2 {}
@Component({
selector: 'app',
template: ``,
standalone: false,
})
class TitleApp {
constructor(private title: Title) {}
ngOnInit() {
this.title.setTitle('Test App Title');
}
}
@NgModule({declarations: [TitleApp], imports: [ServerModule], bootstrap: [TitleApp]})
class TitleAppModule {}
function createMyAsyncServerApp(standalone: boolean) {
@Component({
selector: 'app',
template: '{{text}}<h1 [textContent]="h1"></h1>',
standalone,
})
class MyAsyncServerApp {
text = '';
h1 = '';
@HostListener('window:scroll')
track() {
console.error('scroll');
}
ngOnInit() {
Promise.resolve(null).then(() =>
setTimeout(() => {
this.text = 'Works!';
this.h1 = 'fine';
}, 10),
);
}
}
return MyAsyncServerApp;
}
const MyAsyncServerApp = createMyAsyncServerApp(false);
const MyAsyncServerAppStandalone = getStandaloneBootstrapFn(createMyAsyncServerApp(true));
@NgModule({
declarations: [MyAsyncServerApp],
imports: [BrowserModule, ServerModule],
bootstrap: [MyAsyncServerApp],
})
class AsyncServerModule {}
function createSVGComponent(standalone: boolean) {
@Component({
selector: 'app',
template: '<svg><use xlink:href="#clear"></use></svg>',
standalone,
})
class SVGComponent {}
return SVGComponent;
}
const SVGComponent = createSVGComponent(false);
const SVGComponentStandalone = getStandaloneBootstrapFn(createSVGComponent(true));
@NgModule({
declarations: [SVGComponent],
imports: [BrowserModule, ServerModule],
bootstrap: [SVGComponent],
})
class SVGServerModule {}
f | {
"end_byte": 7786,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_7788_14143 | ction createMyAnimationApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: `
<div [@myAnimation]="state">
<svg *ngIf="true"></svg>
{{text}}
</div>`,
animations: [
trigger('myAnimation', [
state('void', style({'opacity': '0'})),
state(
'active',
style({
'opacity': '1', // simple supported property
'font-weight': 'bold', // property with dashed name
'transform': 'translate3d(0, 0, 0)', // not natively supported by Domino
}),
),
transition('void => *', [animate('0ms')]),
]),
],
})
class MyAnimationApp {
state = 'active';
constructor(private builder: AnimationBuilder) {}
text = 'Works!';
}
return MyAnimationApp;
}
const MyAnimationApp = createMyAnimationApp(false);
const MyAnimationAppStandalone = getStandaloneBootstrapFn(createMyAnimationApp(true));
@NgModule({
declarations: [MyAnimationApp],
imports: [BrowserModule, ServerModule],
bootstrap: [MyAnimationApp],
})
class AnimationServerModule {}
function createMyStylesApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: `<div>Works!</div>`,
styles: ['div {color: blue; } :host { color: red; }'],
})
class MyStylesApp {}
return MyStylesApp;
}
const MyStylesApp = createMyStylesApp(false);
const MyStylesAppStandalone = getStandaloneBootstrapFn(createMyStylesApp(true));
@NgModule({
declarations: [MyStylesApp],
imports: [BrowserModule, ServerModule],
bootstrap: [MyStylesApp],
})
class ExampleStylesModule {}
function createMyTransferStateApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: `<div>Works!</div>`,
})
class MyStylesApp {
state = coreInject(TransferState);
constructor() {
this.state.set(makeStateKey<string>('some-key'), 'some-value');
}
}
return MyStylesApp;
}
const MyTransferStateApp = createMyTransferStateApp(false);
const MyTransferStateAppStandalone = getStandaloneBootstrapFn(createMyTransferStateApp(true));
@NgModule({
declarations: [MyTransferStateApp],
imports: [BrowserModule, ServerModule],
bootstrap: [MyTransferStateApp],
})
class MyTransferStateModule {}
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, ServerModule, HttpClientModule, HttpClientTestingModule],
})
export class HttpClientExampleModule {}
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
constructor(private http: HttpClient) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
@NgModule({
bootstrap: [MyServerApp],
imports: [MyServerAppModule, ServerModule, HttpClientModule, HttpClientTestingModule],
providers: [{provide: HTTP_INTERCEPTORS, multi: true, useClass: MyHttpInterceptor}],
})
export class HttpInterceptorExampleModule {}
@Component({
selector: 'app',
template: `<img [src]="'link'">`,
standalone: false,
})
class ImageApp {}
@NgModule({declarations: [ImageApp], imports: [ServerModule], bootstrap: [ImageApp]})
class ImageExampleModule {}
function createShadowDomEncapsulationApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: 'Shadow DOM works',
encapsulation: ViewEncapsulation.ShadowDom,
styles: [':host { color: red; }'],
})
class ShadowDomEncapsulationApp {}
return ShadowDomEncapsulationApp;
}
const ShadowDomEncapsulationApp = createShadowDomEncapsulationApp(false);
const ShadowDomEncapsulationAppStandalone = getStandaloneBootstrapFn(
createShadowDomEncapsulationApp(true),
);
@NgModule({
declarations: [ShadowDomEncapsulationApp],
imports: [BrowserModule, ServerModule],
bootstrap: [ShadowDomEncapsulationApp],
})
class ShadowDomExampleModule {}
function createFalseAttributesComponents(standalone: boolean) {
@Component({
standalone,
selector: 'my-child',
template: 'Works!',
})
class MyChildComponent {
@Input() public attr!: boolean;
}
@Component({
standalone,
selector: 'app',
template: '<my-child [attr]="false"></my-child>',
imports: standalone ? [MyChildComponent] : [],
})
class MyHostComponent {}
return [MyHostComponent, MyChildComponent];
}
const [MyHostComponent, MyChildComponent] = createFalseAttributesComponents(false);
const MyHostComponentStandalone = getStandaloneBootstrapFn(
createFalseAttributesComponents(true)[0],
);
@NgModule({
declarations: [MyHostComponent, MyChildComponent],
bootstrap: [MyHostComponent],
imports: [ServerModule, BrowserModule],
})
class FalseAttributesModule {}
function createMyInputComponent(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: '<input [name]="name">',
})
class MyInputComponent {
@Input() name = '';
}
return MyInputComponent;
}
const MyInputComponent = createMyInputComponent(false);
const MyInputComponentStandalone = getStandaloneBootstrapFn(createMyInputComponent(true));
@NgModule({
declarations: [MyInputComponent],
bootstrap: [MyInputComponent],
imports: [ServerModule, BrowserModule],
})
class NameModule {}
function createHTMLTypesApp(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: '<div [innerHTML]="html"></div>',
})
class HTMLTypesApp {
html = '<b>foo</b> bar';
constructor(@Inject(DOCUMENT) doc: Document) {}
}
return HTMLTypesApp;
}
const HTMLTypesApp = createHTMLTypesApp(false);
const HTMLTypesAppStandalone = getStandaloneBootstrapFn(createHTMLTypesApp(true));
@NgModule({
declarations: [HTMLTypesApp],
imports: [BrowserModule, ServerModule],
bootstrap: [HTMLTypesApp],
})
class HTMLTypesModule {}
function createMyHiddenComponent(standalone: boolean) {
@Component({
standalone,
selector: 'app',
template: '<input [hidden]="true"><input [hidden]="false">',
})
class MyHiddenComponent {
@Input() name = '';
}
return MyHiddenComponent;
}
const MyHiddenComponent = createMyHiddenComponent(false);
const MyHiddenComponentStandalone = getStandaloneBootstrapFn(createMyHiddenComponent(true));
@NgModule({
declarations: [MyHiddenComponent],
bootstrap: [MyHiddenComponent],
imports: [ServerModule, BrowserModule],
})
class HiddenModule {}
( | {
"end_byte": 14143,
"start_byte": 7788,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_14145_22986 | nction () {
if (getDOM().supportsDOMEvents) return; // NODE only
describe('platform-server integration', () => {
beforeEach(() => {
destroyPlatform();
});
afterEach(() => {
destroyPlatform();
});
afterAll(() => {
destroyPlatform();
});
it('should bootstrap', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const moduleRef = await platform.bootstrapModule(ExampleModule);
expect(isPlatformServer(moduleRef.injector.get(PLATFORM_ID))).toBe(true);
const doc = moduleRef.injector.get(DOCUMENT);
expect(doc.head).toBe(doc.querySelector('head')!);
expect(doc.body).toBe(doc.querySelector('body')!);
expect(doc.documentElement.textContent).toEqual('Works!');
platform.destroy();
});
it('should allow multiple platform instances', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const platform2 = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
await platform.bootstrapModule(ExampleModule).then((moduleRef) => {
const doc = moduleRef.injector.get(DOCUMENT);
expect(doc.documentElement.textContent).toEqual('Works!');
platform.destroy();
});
await platform2.bootstrapModule(ExampleModule2).then((moduleRef) => {
const doc = moduleRef.injector.get(DOCUMENT);
expect(doc.documentElement.textContent).toEqual('Works too!');
platform2.destroy();
});
});
it('adds title to the document using Title service', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<html><head><title></title></head><body><app></app></body></html>'},
},
]);
const ref = await platform.bootstrapModule(TitleAppModule);
const state = ref.injector.get(PlatformState);
const doc = ref.injector.get(DOCUMENT);
const title = doc.querySelector('title')!;
expect(title.textContent).toBe('Test App Title');
expect(state.renderToString()).toContain('<title>Test App Title</title>');
});
it('should get base href from document', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<html><head><base href="/"></head><body><app></app></body></html>'},
},
]);
const moduleRef = await platform.bootstrapModule(ExampleModule);
const location = moduleRef.injector.get(PlatformLocation);
expect(location.getBaseHrefFromDOM()).toEqual('/');
platform.destroy();
});
it('adds styles with ng-app-id attribute', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<html><head></head><body><app></app></body></html>'},
},
]);
const ref = await platform.bootstrapModule(ExampleStylesModule);
const doc = ref.injector.get(DOCUMENT);
const head = doc.getElementsByTagName('head')[0];
const styles: any[] = head.children as any;
expect(styles.length).toBe(1);
expect(styles[0].textContent).toContain('color: red');
expect(styles[0].getAttribute('ng-app-id')).toBe('ng');
});
it('copies known properties to attributes', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const ref = await platform.bootstrapModule(ImageExampleModule);
const appRef: ApplicationRef = ref.injector.get(ApplicationRef);
const app = appRef.components[0].location.nativeElement;
const img = app.getElementsByTagName('img')[0] as any;
expect(img.attributes['src'].value).toEqual('link');
});
describe('PlatformLocation', () => {
it('is injectable', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const appRef = await platform.bootstrapModule(ExampleModule);
const location = appRef.injector.get(PlatformLocation);
expect(location.pathname).toBe('/');
platform.destroy();
});
it('is configurable via INITIAL_CONFIG', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<app></app>', url: 'http://test.com/deep/path?query#hash'},
},
]);
const appRef = await platform.bootstrapModule(ExampleModule);
const location = appRef.injector.get(PlatformLocation);
expect(location.pathname).toBe('/deep/path');
expect(location.search).toBe('?query');
expect(location.hash).toBe('#hash');
});
it('parses component pieces of a URL', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<app></app>', url: 'http://test.com:80/deep/path?query#hash'},
},
]);
const appRef = await platform.bootstrapModule(ExampleModule);
const location = appRef.injector.get(PlatformLocation);
expect(location.hostname).toBe('test.com');
expect(location.protocol).toBe('http:');
expect(location.port).toBe('');
expect(location.pathname).toBe('/deep/path');
expect(location.search).toBe('?query');
expect(location.hash).toBe('#hash');
});
it('handles empty search and hash portions of the url', async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<app></app>', url: 'http://test.com/deep/path'},
},
]);
const appRef = await platform.bootstrapModule(ExampleModule);
const location = appRef.injector.get(PlatformLocation);
expect(location.pathname).toBe('/deep/path');
expect(location.search).toBe('');
expect(location.hash).toBe('');
});
it('pushState causes the URL to update', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const appRef = await platform.bootstrapModule(ExampleModule);
const location = appRef.injector.get(PlatformLocation);
location.pushState(null, 'Test', '/foo#bar');
expect(location.pathname).toBe('/foo');
expect(location.hash).toBe('#bar');
platform.destroy();
});
it('allows subscription to the hash state', (done) => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
platform.bootstrapModule(ExampleModule).then((appRef) => {
const location: PlatformLocation = appRef.injector.get(PlatformLocation);
expect(location.pathname).toBe('/');
location.onHashChange((e: any) => {
expect(e.type).toBe('hashchange');
expect(e.oldUrl).toBe('/');
expect(e.newUrl).toBe('/foo#bar');
platform.destroy();
done();
});
location.pushState(null, 'Test', '/foo#bar');
});
});
});
describe('render', () => {
let doc: string;
let expectedOutput =
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!<h1>fine</h1></app></body></html>';
beforeEach(() => {
// PlatformConfig takes in a parsed document so that it can be cached across requests.
doc = '<html><head></head><body><app></app></body></html>';
});
afterEach(() => {
doc = '<html><head></head><body><app></app></body></html>';
TestBed.resetTestingModule();
});
it('using long form should work', async () => {
const platform = platformServer([{provide: INITIAL_CONFIG, useValue: {document: doc}}]);
const moduleRef = await platform.bootstrapModule(AsyncServerModule);
const applicationRef = moduleRef.injector.get(ApplicationRef);
await whenStable(applicationRef);
// Note: the `ng-server-context` is not present in this output, since
// `renderModule` or `renderApplication` functions are not used here.
const expectedOutput =
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER">' +
'Works!<h1>fine</h1></app></body></html>';
expect(platform.injector.get(PlatformState).renderToString()).toBe(expectedOutput);
});
// Run the set of tests with regular and standalone components.
| {
"end_byte": 22986,
"start_byte": 14145,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_22993_32382 | ue, false].forEach((isStandalone: boolean) => {
it(`using ${isStandalone ? 'renderApplication' : 'renderModule'} should work`, async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyAsyncServerAppStandalone, options)
: renderModule(AsyncServerModule, options);
const output = await bootstrap;
expect(output).toBe(expectedOutput);
});
it(
`using ${isStandalone ? 'renderApplication' : 'renderModule'} ` +
`should allow passing a document reference`,
async () => {
const document = TestBed.inject(DOCUMENT);
// Append root element based on the app selector.
const rootEl = document.createElement('app');
document.body.appendChild(rootEl);
// Append a special marker to verify that we use a correct instance
// of the document for rendering.
const markerEl = document.createComment('test marker');
document.body.appendChild(markerEl);
const options = {document};
const bootstrap = isStandalone
? renderApplication(MyAsyncServerAppStandalone, {document})
: renderModule(AsyncServerModule, options);
const output = await bootstrap.finally(() => {
rootEl.remove();
markerEl.remove();
});
expect(output).toBe(
'<html><head><title>fakeTitle</title></head>' +
'<body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'Works!<h1>fine</h1></app>' +
'<!--test marker--></body></html>',
);
},
);
it('works with SVG elements', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(SVGComponentStandalone, {...options})
: renderModule(SVGServerModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'<svg><use xlink:href="#clear"></use></svg></app></body></html>',
);
});
it('works with animation', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyAnimationAppStandalone, options)
: renderModule(AnimationServerModule, options);
const output = await bootstrap;
expect(output).toContain('Works!');
expect(output).toContain('ng-trigger-myAnimation');
expect(output).toContain('opacity: 1;');
expect(output).toContain('transform: translate3d(0, 0, 0);');
expect(output).toContain('font-weight: bold;');
});
it('should handle ViewEncapsulation.ShadowDom', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(ShadowDomEncapsulationAppStandalone, options)
: renderModule(ShadowDomExampleModule, options);
const output = await bootstrap;
expect(output).not.toBe('');
expect(output).toContain('color: red');
});
it('adds the `ng-server-context` attribute to host elements', async () => {
const options = {
document: doc,
};
const providers = [
{
provide: SERVER_CONTEXT,
useValue: 'ssg',
},
];
const bootstrap = isStandalone
? renderApplication(MyStylesAppStandalone, {...options, platformProviders: providers})
: renderModule(ExampleStylesModule, {...options, extraProviders: providers});
const output = await bootstrap;
expect(output).toMatch(
/<app _nghost-ng-c\d+="" ng-version="0.0.0-PLACEHOLDER" ng-server-context="ssg">/,
);
});
it('sanitizes the `serverContext` value', async () => {
const options = {
document: doc,
};
const providers = [
{
provide: SERVER_CONTEXT,
useValue: '!!!Some extra chars&& --><!--',
},
];
const bootstrap = isStandalone
? renderApplication(MyStylesAppStandalone, {...options, platformProviders: providers})
: renderModule(ExampleStylesModule, {...options, extraProviders: providers});
// All symbols other than [a-zA-Z0-9\-] are removed
const output = await bootstrap;
expect(output).toMatch(/ng-server-context="Someextrachars----"/);
});
it(
`using ${isStandalone ? 'renderApplication' : 'renderModule'} ` +
`should serialize transfer state only once`,
async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyTransferStateAppStandalone, options)
: renderModule(MyTransferStateModule, options);
const expectedOutput =
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other"><div>Works!</div></app>' +
'<script id="ng-state" type="application/json">{"some-key":"some-value"}</script></body></html>';
const output = await bootstrap;
expect(output).toEqual(expectedOutput);
},
);
it('uses `other` as the `serverContext` value when all symbols are removed after sanitization', async () => {
const options = {
document: doc,
};
const providers = [
{
provide: SERVER_CONTEXT,
useValue: '!!! &&<>',
},
];
const bootstrap = isStandalone
? renderApplication(MyStylesAppStandalone, {...options, platformProviders: providers})
: renderModule(ExampleStylesModule, {...options, extraProviders: providers});
// All symbols other than [a-zA-Z0-9\-] are removed,
// the `other` is used as the default.
const output = await bootstrap;
expect(output).toMatch(/ng-server-context="other"/);
});
it('appends SSR integrity marker comment when hydration is enabled', async () => {
@Component({
standalone: true,
selector: 'app',
template: ``,
})
class SimpleApp {}
const bootstrap = renderApplication(
getStandaloneBootstrapFn(SimpleApp, [provideClientHydration()]),
{document: doc},
);
// HttpClient cache and DOM hydration are enabled by default.
const output = await bootstrap;
expect(output).toContain(`<body><!--${SSR_CONTENT_INTEGRITY_MARKER}-->`);
});
it('should handle false values on attributes', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyHostComponentStandalone, options)
: renderModule(FalseAttributesModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'<my-child ng-reflect-attr="false">Works!</my-child></app></body></html>',
);
});
it('should handle element property "name"', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyInputComponentStandalone, options)
: renderModule(NameModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'<input name=""></app></body></html>',
);
});
it('should work with sanitizer to handle "innerHTML"', async () => {
// Clear out any global states. These should be set when platform-server
// is initialized.
(global as any).Node = undefined;
(global as any).Document = undefined;
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(HTMLTypesAppStandalone, options)
: renderModule(HTMLTypesModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'<div><b>foo</b> bar</div></app></body></html>',
);
});
it('should handle element property "hidden"', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyHiddenComponentStandalone, options)
: renderModule(HiddenModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">' +
'<input hidden=""><input></app></body></html>',
);
});
| {
"end_byte": 32382,
"start_byte": 22993,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_32392_41630 | 'should call render hook', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(
getStandaloneBootstrapFn(MyServerAppStandalone, RenderHookProviders),
options,
)
: renderModule(RenderHookModule, options);
const output = await bootstrap;
// title should be added by the render hook.
expect(output).toBe(
'<html><head><title>RenderHook</title></head><body>' +
'<app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</app></body></html>',
);
});
it('should call multiple render hooks', async () => {
const consoleSpy = spyOn(console, 'warn');
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(
getStandaloneBootstrapFn(MyServerAppStandalone, MultiRenderHookProviders),
options,
)
: renderModule(MultiRenderHookModule, options);
const output = await bootstrap;
// title should be added by the render hook.
expect(output).toBe(
'<html><head><title>RenderHook</title><meta name="description"></head>' +
'<body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</app></body></html>',
);
expect(consoleSpy).toHaveBeenCalled();
});
it('should call async render hooks', async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(
getStandaloneBootstrapFn(MyServerAppStandalone, AsyncRenderHookProviders),
options,
)
: renderModule(AsyncRenderHookModule, options);
const output = await bootstrap;
// title should be added by the render hook.
expect(output).toBe(
'<html><head><title>AsyncRenderHook</title></head><body>' +
'<app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</app></body></html>',
);
});
it('should call multiple async and sync render hooks', async () => {
const consoleSpy = spyOn(console, 'warn');
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(
getStandaloneBootstrapFn(MyServerAppStandalone, AsyncMultiRenderHookProviders),
options,
)
: renderModule(AsyncMultiRenderHookModule, options);
const output = await bootstrap;
// title should be added by the render hook.
expect(output).toBe(
'<html><head><meta name="description"><title>AsyncRenderHook</title></head>' +
'<body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</app></body></html>',
);
expect(consoleSpy).toHaveBeenCalled();
});
it(
`should wait for InitialRenderPendingTasks before serializing ` +
`(standalone: ${isStandalone})`,
async () => {
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(getStandaloneBootstrapFn(PendingTasksAppStandalone), options)
: renderModule(PendingTasksAppModule, options);
const output = await bootstrap;
expect(output).toBe(
'<html><head></head><body>' +
'<app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Completed: Yes</app>' +
'</body></html>',
);
},
);
it(
`should call onOnDestroy of a service after a successful render` +
`(standalone: ${isStandalone})`,
async () => {
let wasServiceNgOnDestroyCalled = false;
@Injectable({providedIn: 'root'})
class DestroyableService {
ngOnDestroy() {
wasServiceNgOnDestroyCalled = true;
}
}
const SuccessfulAppInitializerProviders = [
{
provide: APP_INITIALIZER,
useFactory: () => {
inject(DestroyableService);
return () => Promise.resolve(); // Success in APP_INITIALIZER
},
multi: true,
},
];
@NgModule({
providers: SuccessfulAppInitializerProviders,
imports: [MyServerAppModule, ServerModule],
bootstrap: [MyServerApp],
})
class ServerSuccessfulAppInitializerModule {}
const ServerSuccessfulAppInitializerAppStandalone = getStandaloneBootstrapFn(
createMyServerApp(true),
SuccessfulAppInitializerProviders,
);
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(ServerSuccessfulAppInitializerAppStandalone, options)
: renderModule(ServerSuccessfulAppInitializerModule, options);
await bootstrap;
expect(getPlatform()).withContext('PlatformRef should be destroyed').toBeNull();
expect(wasServiceNgOnDestroyCalled)
.withContext('DestroyableService.ngOnDestroy() should be called')
.toBeTrue();
},
);
it(
`should call onOnDestroy of a service after some APP_INITIALIZER fails ` +
`(standalone: ${isStandalone})`,
async () => {
let wasServiceNgOnDestroyCalled = false;
@Injectable({providedIn: 'root'})
class DestroyableService {
ngOnDestroy() {
wasServiceNgOnDestroyCalled = true;
}
}
const FailingAppInitializerProviders = [
{
provide: APP_INITIALIZER,
useFactory: () => {
inject(DestroyableService);
return () => Promise.reject('Error in APP_INITIALIZER');
},
multi: true,
},
];
@NgModule({
providers: FailingAppInitializerProviders,
imports: [MyServerAppModule, ServerModule],
bootstrap: [MyServerApp],
})
class ServerFailingAppInitializerModule {}
const ServerFailingAppInitializerAppStandalone = getStandaloneBootstrapFn(
createMyServerApp(true),
FailingAppInitializerProviders,
);
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(ServerFailingAppInitializerAppStandalone, options)
: renderModule(ServerFailingAppInitializerModule, options);
await expectAsync(bootstrap).toBeRejectedWith('Error in APP_INITIALIZER');
expect(getPlatform()).withContext('PlatformRef should be destroyed').toBeNull();
expect(wasServiceNgOnDestroyCalled)
.withContext('DestroyableService.ngOnDestroy() should be called')
.toBeTrue();
},
);
it(
`should call onOnDestroy of a service after an error happens in a root component's constructor ` +
`(standalone: ${isStandalone})`,
async () => {
let wasServiceNgOnDestroyCalled = false;
@Injectable({providedIn: 'root'})
class DestroyableService {
ngOnDestroy() {
wasServiceNgOnDestroyCalled = true;
}
}
@Component({
standalone: isStandalone,
selector: 'app',
template: `Works!`,
})
class MyServerFailingConstructorApp {
constructor() {
inject(DestroyableService);
throw 'Error in constructor of the root component';
}
}
@NgModule({
declarations: [MyServerFailingConstructorApp],
imports: [MyServerAppModule, ServerModule],
bootstrap: [MyServerFailingConstructorApp],
})
class MyServerFailingConstructorAppModule {}
const MyServerFailingConstructorAppStandalone = getStandaloneBootstrapFn(
MyServerFailingConstructorApp,
);
const options = {document: doc};
const bootstrap = isStandalone
? renderApplication(MyServerFailingConstructorAppStandalone, options)
: renderModule(MyServerFailingConstructorAppModule, options);
await expectAsync(bootstrap).toBeRejectedWith(
'Error in constructor of the root component',
);
expect(getPlatform()).withContext('PlatformRef should be destroyed').toBeNull();
expect(wasServiceNgOnDestroyCalled)
.withContext('DestroyableService.ngOnDestroy() should be called')
.toBeTrue();
},
);
});
});
| {
"end_byte": 41630,
"start_byte": 32392,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/integration_spec.ts_41636_46549 | cribe('Router', () => {
it('should wait for lazy routes before serializing', async () => {
const ngZone = TestBed.inject(NgZone);
@Component({
standalone: true,
selector: 'lazy',
template: `LazyCmp content`,
})
class LazyCmp {}
const routes: Routes = [
{
path: '',
loadComponent: () => {
return ngZone.runOutsideAngular(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(LazyCmp), 100);
});
});
},
},
];
@Component({
standalone: false,
selector: 'app',
template: `
Works!
<router-outlet />
`,
})
class MyServerApp {}
@NgModule({
declarations: [MyServerApp],
exports: [MyServerApp],
imports: [BrowserModule, ServerModule, RouterOutlet],
providers: [provideRouter(routes)],
bootstrap: [MyServerApp],
})
class MyServerAppModule {}
const options = {document: '<html><head></head><body><app></app></body></html>'};
const output = await renderModule(MyServerAppModule, options);
// Expect serialization to happen once a lazy-loaded route completes loading
// and a lazy component is rendered.
expect(output).toContain('<lazy>LazyCmp content</lazy>');
});
});
describe('HttpClient', () => {
it('can inject HttpClient', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const ref = await platform.bootstrapModule(HttpClientExampleModule);
expect(ref.injector.get(HttpClient) instanceof HttpClient).toBeTruthy();
});
it('can make HttpClient requests', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
await platform.bootstrapModule(HttpClientExampleModule).then((ref) => {
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
const http = ref.injector.get(HttpClient);
ref.injector.get<NgZone>(NgZone).run(() => {
http.get<string>('http://localhost/testing').subscribe((body: string) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
it('can use HttpInterceptor that injects HttpClient', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
await platform.bootstrapModule(HttpInterceptorExampleModule).then((ref) => {
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
const http = ref.injector.get(HttpClient);
ref.injector.get(NgZone).run(() => {
http.get<string>('http://localhost/testing').subscribe((body: string) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
describe(`given 'url' is provided in 'INITIAL_CONFIG'`, () => {
let mock: HttpTestingController;
let ref: NgModuleRef<HttpInterceptorExampleModule>;
let http: HttpClient;
beforeEach(async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<app></app>', url: 'http://localhost:4000/foo'},
},
]);
ref = await platform.bootstrapModule(HttpInterceptorExampleModule);
mock = ref.injector.get(HttpTestingController);
http = ref.injector.get(HttpClient);
});
it('should resolve relative request URLs to absolute', async () => {
ref.injector.get(NgZone).run(() => {
http.get('/testing').subscribe((body) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost:4000/testing').flush('success!');
});
});
it(`should not replace the baseUrl of a request when it's absolute`, async () => {
ref.injector.get(NgZone).run(() => {
http.get('http://localhost/testing').subscribe((body) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
});
});
})();
| {
"end_byte": 46549,
"start_byte": 41636,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/integration_spec.ts"
} |
angular/packages/platform-server/test/transfer_state_spec.ts_0_3161 | /**
* @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 {Component, makeStateKey, NgModule, TransferState} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {renderModule, ServerModule} from '@angular/platform-server';
describe('transfer_state', () => {
const defaultExpectedOutput =
'<html><head></head><body><app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</app><script id="ng-state" type="application/json">{"test":10}</script></body></html>';
it('adds transfer script tag when using renderModule', async () => {
const STATE_KEY = makeStateKey<number>('test');
@Component({
selector: 'app',
template: 'Works!',
standalone: false,
})
class TransferComponent {
constructor(private transferStore: TransferState) {
this.transferStore.set(STATE_KEY, 10);
}
}
@NgModule({
bootstrap: [TransferComponent],
declarations: [TransferComponent],
imports: [BrowserModule, ServerModule],
})
class TransferStoreModule {}
const output = await renderModule(TransferStoreModule, {document: '<app></app>'});
expect(output).toBe(defaultExpectedOutput);
});
it('cannot break out of <script> tag in serialized output', async () => {
const STATE_KEY = makeStateKey<string>('testString');
@Component({
selector: 'esc-app',
template: 'Works!',
standalone: false,
})
class EscapedComponent {
constructor(private transferStore: TransferState) {
this.transferStore.set(STATE_KEY, '</script><script>alert(\'Hello&\' + "World");');
}
}
@NgModule({
bootstrap: [EscapedComponent],
declarations: [EscapedComponent],
imports: [BrowserModule, ServerModule],
})
class EscapedTransferStoreModule {}
const output = await renderModule(EscapedTransferStoreModule, {
document: '<esc-app></esc-app>',
});
expect(output).toBe(
'<html><head></head><body><esc-app ng-version="0.0.0-PLACEHOLDER" ng-server-context="other">Works!</esc-app>' +
'<script id="ng-state" type="application/json">' +
`{"testString":"\\u003C/script>\\u003Cscript>alert('Hello&' + \\"World\\");"}` +
'</script></body></html>',
);
});
it('adds transfer script tag when setting state during onSerialize', async () => {
const STATE_KEY = makeStateKey<number>('test');
@Component({
selector: 'app',
template: 'Works!',
standalone: false,
})
class TransferComponent {
constructor(private transferStore: TransferState) {
this.transferStore.onSerialize(STATE_KEY, () => 10);
}
}
@NgModule({
bootstrap: [TransferComponent],
declarations: [TransferComponent],
imports: [BrowserModule, ServerModule],
})
class TransferStoreModule {}
const output = await renderModule(TransferStoreModule, {document: '<app></app>'});
expect(output).toBe(defaultExpectedOutput);
});
});
| {
"end_byte": 3161,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/transfer_state_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_0_6179 | /**
* @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 '@angular/localize/init';
import {
CommonModule,
DOCUMENT,
isPlatformServer,
NgComponentOutlet,
NgFor,
NgIf,
NgTemplateOutlet,
PlatformLocation,
} from '@angular/common';
import {MockPlatformLocation} from '@angular/common/testing';
import {computeMsgId} from '@angular/compiler';
import {
afterRender,
ApplicationRef,
ChangeDetectorRef,
Component,
ContentChildren,
createComponent,
destroyPlatform,
Directive,
ElementRef,
EnvironmentInjector,
ErrorHandler,
getPlatform,
inject,
Input,
NgZone,
Pipe,
PipeTransform,
PLATFORM_ID,
provideExperimentalZonelessChangeDetection,
Provider,
QueryList,
TemplateRef,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
ɵwhenStable as whenStable,
} from '@angular/core';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {TestBed} from '@angular/core/testing';
import {clearTranslations, loadTranslations} from '@angular/localize';
import {HydrationFeature, withI18nSupport} from '@angular/platform-browser';
import {provideRouter, RouterOutlet, Routes} from '@angular/router';
import {
clearDocument,
getAppContents,
prepareEnvironmentAndHydrate,
resetTViewsFor,
stripUtilAttributes,
} from './dom_utils';
import {
EMPTY_TEXT_NODE_COMMENT,
getComponentRef,
getHydrationInfoFromTransferState,
NGH_ATTR_NAME,
ssr,
stripExcessiveSpaces,
stripSsrIntegrityMarker,
stripTransferDataScript,
TEXT_NODE_SEPARATOR_COMMENT,
TRANSFER_STATE_TOKEN_ID,
verifyAllChildNodesClaimedForHydration,
verifyAllNodesClaimedForHydration,
verifyClientAndSSRContentsMatch,
verifyHasLog,
verifyHasNoLog,
verifyNodeHasMismatchInfo,
verifyNodeHasSkipHydrationMarker,
verifyNoNodesWereClaimedForHydration,
withDebugConsole,
withNoopErrorHandler,
verifyEmptyConsole,
DebugConsole,
clearConsole,
} from './hydration_utils';
import {CLIENT_RENDER_MODE_FLAG} from '@angular/core/src/hydration/api';
describe('platform-server full application hydration integration', () => {
beforeEach(() => {
if (typeof ngDevMode === 'object') {
// Reset all ngDevMode counters.
for (const metric of Object.keys(ngDevMode!)) {
const currentValue = (ngDevMode as unknown as {[key: string]: number | boolean})[metric];
if (typeof currentValue === 'number') {
// Rest only numeric values, which represent counters.
(ngDevMode as unknown as {[key: string]: number | boolean})[metric] = 0;
}
}
}
if (getPlatform()) destroyPlatform();
});
afterAll(() => destroyPlatform());
describe('hydration', () => {
let doc: Document;
beforeEach(() => {
doc = TestBed.inject(DOCUMENT);
});
afterEach(() => {
clearDocument(doc);
clearConsole(TestBed.inject(ApplicationRef));
});
describe('annotations', () => {
it('should add hydration annotations to component host nodes during ssr', async () => {
@Component({
standalone: true,
selector: 'nested',
template: 'This is a nested component.',
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<nested />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
expect(ssrContents).toContain(`<nested ${NGH_ATTR_NAME}`);
});
it('should skip local ref slots while producing hydration annotations', async () => {
@Component({
standalone: true,
selector: 'nested',
template: 'This is a nested component.',
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<div #localRef></div>
<nested />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
expect(ssrContents).toContain(`<nested ${NGH_ATTR_NAME}`);
});
it('should skip embedded views from an ApplicationRef during annotation', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-template #tmpl>Hi!</ng-template>
`,
})
class SimpleComponent {
@ViewChild('tmpl', {read: TemplateRef}) tmplRef!: TemplateRef<unknown>;
private appRef = inject(ApplicationRef);
ngAfterViewInit() {
const viewRef = this.tmplRef.createEmbeddedView({});
this.appRef.attachView(viewRef);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
});
});
describe('server rendering', () => {
it('should wipe out existing host element content when server side rendering', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div>Some content</div>
`,
})
class SimpleComponent {}
const extraChildNodes = '<!--comment--> Some text! <b>and a tag</b>';
const doc = `<html><head></head><body><app>${extraChildNodes}</app></body></html>`;
const html = await ssr(SimpleComponent, {doc});
const ssrContents = getAppContents(html);
// We expect that the existing content of the host node is fully removed.
expect(ssrContents).not.toContain(extraChildNodes);
expect(ssrContents).toContain('<app ngh="0"><div>Some content</div></app>');
});
});
| {
"end_byte": 6179,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_6185_15558 | escribe('hydration', () => {
it('should remove ngh attributes after hydration on the client', async () => {
@Component({
standalone: true,
selector: 'app',
template: 'Hi!',
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.getAttribute(NGH_ATTR_NAME)).toBeNull();
});
describe('basic scenarios', () => {
it('should support text-only contents', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is hydrated content.
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate root components with empty templates', async () => {
@Component({
standalone: true,
selector: 'app',
template: '',
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate child components with empty templates', async () => {
@Component({
standalone: true,
selector: 'child',
template: '',
})
class ChildComponent {}
@Component({
standalone: true,
imports: [ChildComponent],
selector: 'app',
template: '<child />',
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, ChildComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support a single text interpolation', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
{{ text }}
`,
})
class SimpleComponent {
text = 'text';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support text and HTML elements', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<header>Header</header>
<main>This is hydrated content in the main element.</main>
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support text and HTML elements in nested components', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div>This is the content of a nested component</div>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp />
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Make sure there are no extra logs in case
// default NgZone is setup for an application.
verifyHasNoLog(
appRef,
'NG05000: Angular detected that hydration was enabled for an application ' +
'that uses a custom or a noop Zone.js implementation.',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support elements with local refs', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<header #headerRef>Header</header>
<main #mainRef>This is hydrated content in the main element.</main>
<footer #footerRef>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should handle extra child nodes within a root app component', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div>Some content</div>
`,
})
class SimpleComponent {}
const extraChildNodes = '<!--comment--> Some text! <b>and a tag</b>';
const docContent = `<html><head></head><body><app>${extraChildNodes}</app></body></html>`;
const html = await ssr(SimpleComponent, {doc: docContent});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 15558,
"start_byte": 6185,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_15566_20553 | escribe('ng-container', () => {
it('should support empty containers', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is an empty container: <ng-container></ng-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support non-empty containers', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is a non-empty container:
<ng-container>
<h1>Hello world!</h1>
</ng-container>
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support nested containers', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is a non-empty container:
<ng-container>
<ng-container>
<ng-container>
<h1>Hello world!</h1>
</ng-container>
</ng-container>
</ng-container>
<div>Post-container element</div>
<ng-container>
<div>Tags between containers</div>
<ng-container>
<div>More tags between containers</div>
<ng-container>
<h1>Hello world!</h1>
</ng-container>
</ng-container>
</ng-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support element containers with *ngIf', async () => {
@Component({
selector: 'cmp',
standalone: true,
template: 'Hi!',
})
class Cmp {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<ng-container *ngIf="true">
<div #inner></div>
</ng-container>
<ng-template #outer />
`,
})
class SimpleComponent {
@ViewChild('inner', {read: ViewContainerRef}) inner!: ViewContainerRef;
@ViewChild('outer', {read: ViewContainerRef}) outer!: ViewContainerRef;
ngAfterViewInit() {
this.inner.createComponent(Cmp);
this.outer.createComponent(Cmp);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, Cmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 20553,
"start_byte": 15566,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_20561_27303 | escribe('view containers', () => {
describe('*ngIf', () => {
it('should work with *ngIf on ng-container nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
This is a non-empty container:
<ng-container *ngIf="true">
<h1>Hello world!</h1>
</ng-container>
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with empty containers on ng-container nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
This is an empty container:
<ng-container *ngIf="false" />
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with *ngIf on element nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello world!</h1>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with empty containers on element nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<h1 *ngIf="false">Hello world!</h1>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with *ngIf on component host nodes', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello World!</h1>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NestedComponent],
template: `
This is a component:
<nested-cmp *ngIf="true" />
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support nested *ngIfs', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
This is a non-empty container:
<ng-container *ngIf="true">
<h1 *ngIf="true">
<span *ngIf="true">Hello world!</span>
</h1>
</ng-container>
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 27303,
"start_byte": 20561,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_27313_33718 | escribe('*ngFor', () => {
it('should support *ngFor on <ng-container> nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<ng-container *ngFor="let item of items">
<h1 *ngIf="true">Item #{{ item }}</h1>
</ng-container>
<div>Post-container element</div>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Check whether serialized hydration info has a multiplier
// (which avoids repeated views serialization).
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain('"x":3');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support *ngFor on element nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div *ngFor="let item of items">
<h1 *ngIf="true">Item #{{ item }}</h1>
</div>
<div>Post-container element</div>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Check whether serialized hydration info has a multiplier
// (which avoids repeated views serialization).
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain('"x":3');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support *ngFor on host component nodes', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello World!</h1>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor, NestedComponent],
template: `
<nested-cmp *ngFor="let item of items" />
<div>Post-container element</div>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Check whether serialized hydration info has a multiplier
// (which avoids repeated views serialization).
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain('"x":3');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support compact serialization for *ngFor', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div *ngFor="let number of numbers">
Number {{ number }}
<ng-container *ngIf="number >= 0 && number < 5">is in [0, 5) range.</ng-container>
<ng-container *ngIf="number >= 5 && number < 8">is in [5, 8) range.</ng-container>
<ng-container *ngIf="number >= 8 && number < 10">is in [8, 10) range.</ng-container>
</div>
`,
})
class SimpleComponent {
numbers = [...Array(10).keys()]; // [0..9]
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Check whether serialized hydration info has multipliers
// (which avoids repeated views serialization).
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain('"x":5'); // [0, 5) range, 5 views
expect(hydrationInfo).toContain('"x":3'); // [5, 8) range, 3 views
expect(hydrationInfo).toContain('"x":2'); // [8, 10) range, 2 views
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 33718,
"start_byte": 27313,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_33728_40955 | escribe('*ngComponentOutlet', () => {
it('should support hydration on <ng-container> nodes', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello World!</h1>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgComponentOutlet],
template: `
<ng-container *ngComponentOutlet="NestedComponent" />`,
})
class SimpleComponent {
// This field is necessary to expose
// the `NestedComponent` to the template.
NestedComponent = NestedComponent;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support hydration on element nodes', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello World!</h1>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgComponentOutlet],
template: `
<div *ngComponentOutlet="NestedComponent"></div>
`,
})
class SimpleComponent {
// This field is necessary to expose
// the `NestedComponent` to the template.
NestedComponent = NestedComponent;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support hydration for nested components', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [NgIf],
template: `
<h1 *ngIf="true">Hello World!</h1>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'other-nested-cmp',
imports: [NgComponentOutlet],
template: `
<ng-container *ngComponentOutlet="NestedComponent" />`,
})
class OtherNestedComponent {
// This field is necessary to expose
// the `NestedComponent` to the template.
NestedComponent = NestedComponent;
}
@Component({
standalone: true,
selector: 'app',
imports: [NgComponentOutlet],
template: `
<ng-container *ngComponentOutlet="OtherNestedComponent" />`,
})
class SimpleComponent {
// This field is necessary to expose
// the `OtherNestedComponent` to the template.
OtherNestedComponent = OtherNestedComponent;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, NestedComponent, OtherNestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
describe('*ngTemplateOutlet', () => {
it('should work with <ng-container>', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgTemplateOutlet],
template: `
<ng-template #tmpl>
This is a content of the template!
</ng-template>
<ng-container [ngTemplateOutlet]="tmpl"></ng-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with element nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgTemplateOutlet],
template: `
<ng-template #tmpl>
This is a content of the template!
</ng-template>
<div [ngTemplateOutlet]="tmpl"></div>
<div>Some extra content</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 40955,
"start_byte": 33728,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_40965_47565 | escribe('ViewContainerRef', () => {
it('should work with ViewContainerRef.createComponent', async () => {
@Component({
standalone: true,
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div #target></div>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with ViewContainerRef.createEmbeddedView', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<ng-template #tmpl>
<h1>This is a content of an ng-template.</h1>
</ng-template>
<ng-container #target></ng-container>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate dynamically created components using root component as an anchor', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate embedded views when using root component as an anchor', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-template #tmpl>
<h1>Content of embedded view</h1>
</ng-template>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
| {
"end_byte": 47565,
"start_byte": 40965,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_47577_56822 | t('should hydrate dynamically created components using root component as an anchor', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'nested-dynamic-a',
template: `
<p>NestedDynamicComponentA</p>
`,
})
class NestedDynamicComponentA {}
@Component({
standalone: true,
imports: [CommonModule],
selector: 'nested-dynamic-b',
template: `
<p>NestedDynamicComponentB</p>
`,
})
class NestedDynamicComponentB {}
@Component({
standalone: true,
imports: [CommonModule],
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
`,
})
class DynamicComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(NestedDynamicComponentB);
compRef.changeDetectorRef.detectChanges();
}
}
@Component({
standalone: true,
selector: 'app',
template: `
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
doc = inject(DOCUMENT);
appRef = inject(ApplicationRef);
elementRef = inject(ElementRef);
viewContainerRef = inject(ViewContainerRef);
environmentInjector = inject(EnvironmentInjector);
createOuterDynamicComponent() {
const hostElement = this.doc.body.querySelector('[id=dynamic-cmp-target]')!;
const compRef = createComponent(DynamicComponent, {
hostElement,
environmentInjector: this.environmentInjector,
});
compRef.changeDetectorRef.detectChanges();
this.appRef.attachView(compRef.hostView);
}
createInnerDynamicComponent() {
const compRef = this.viewContainerRef.createComponent(NestedDynamicComponentA);
compRef.changeDetectorRef.detectChanges();
}
ngAfterViewInit() {
this.createInnerDynamicComponent();
this.createOuterDynamicComponent();
}
}
// In this test we expect to have the following structure,
// where both root component nodes also act as ViewContainerRef
// anchors, i.e.:
// ```
// <app />
// <nested-dynamic-b />
// <!--container-->
// <div></div> // Host element for DynamicComponent
// <nested-dynamic-a/>
// <!--container-->
// ```
// The test verifies that 2 root components acting as ViewContainerRef
// do not have overlaps in DOM elements that represent views and all
// DOM nodes are able to hydrate correctly.
const indexHtml =
'<html><head></head><body>' +
'<app></app>' +
'<div id="dynamic-cmp-target"></div>' +
'</body></html>';
const html = await ssr(SimpleComponent, {doc: indexHtml});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should hydrate dynamically created components using ' +
"another component's host node as an anchor",
async () => {
@Component({
standalone: true,
selector: 'another-dynamic',
template: `<span>This is a content of another dynamic component.</span>`,
})
class AnotherDynamicComponent {
vcr = inject(ViewContainerRef);
}
@Component({
standalone: true,
selector: 'dynamic',
template: `<span>This is a content of a dynamic component.</span>`,
})
class DynamicComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(AnotherDynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
@Component({
standalone: true,
selector: 'app',
template: `<main>Hi! This is the main content.</main>`,
})
class SimpleComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should hydrate dynamically created embedded views using ' +
"another component's host node as an anchor",
async () => {
@Component({
standalone: true,
selector: 'dynamic',
template: `
<ng-template #tmpl>
<h1>Content of an embedded view</h1>
</ng-template>
<main>Hi! This is the dynamic component content.</main>
`,
})
class DynamicComponent {
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
@Component({
standalone: true,
selector: 'app',
template: `<main>Hi! This is the main content.</main>`,
})
class SimpleComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
| {
"end_byte": 56822,
"start_byte": 47577,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_56834_64230 | t(
'should re-create the views from the ViewContainerRef ' +
'if there is a mismatch in template ids between the current view ' +
'(that is being created) and the first dehydrated view in the list',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-template #tmplH1>
<h1>Content of H1</h1>
</ng-template>
<ng-template #tmplH2>
<h2>Content of H2</h2>
</ng-template>
<ng-template #tmplH3>
<h3>Content of H3</h3>
</ng-template>
<p>Pre-container content</p>
<ng-container #target></ng-container>
<div>Post-container content</div>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
@ViewChild('tmplH1', {read: TemplateRef}) tmplH1!: TemplateRef<unknown>;
@ViewChild('tmplH2', {read: TemplateRef}) tmplH2!: TemplateRef<unknown>;
@ViewChild('tmplH3', {read: TemplateRef}) tmplH3!: TemplateRef<unknown>;
isServer = isPlatformServer(inject(PLATFORM_ID));
ngAfterViewInit() {
const viewRefH1 = this.vcr.createEmbeddedView(this.tmplH1);
const viewRefH2 = this.vcr.createEmbeddedView(this.tmplH2);
const viewRefH3 = this.vcr.createEmbeddedView(this.tmplH3);
viewRefH1.detectChanges();
viewRefH2.detectChanges();
viewRefH3.detectChanges();
// Move the last view in front of the first one.
this.vcr.move(viewRefH3, 0);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// We expect that all 3 dehydrated views would be removed
// (each dehydrated view represents a real embedded view),
// since we can not hydrate them in order (views were
// moved in a container).
expect(ngDevMode!.dehydratedViewsRemoved).toBe(3);
const clientRootNode = compRef.location.nativeElement;
const h1 = clientRootNode.querySelector('h1');
const h2 = clientRootNode.querySelector('h2');
const h3 = clientRootNode.querySelector('h3');
const exceptions = [h1, h2, h3];
verifyAllNodesClaimedForHydration(clientRootNode, exceptions);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it('should allow injecting ViewContainerRef in the root component', async () => {
@Component({
standalone: true,
selector: 'app',
template: `Hello World!`,
})
class SimpleComponent {
private vcRef = inject(ViewContainerRef);
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
// Replace the trailing comment node (added as a result of the
// `ViewContainerRef` injection) before comparing contents.
const _ssrContents = ssrContents.replace(/<\/app><!--container-->/, '</app>');
verifyClientAndSSRContentsMatch(_ssrContents, clientRootNode);
});
});
describe('<ng-template>', () => {
it('should support unused <ng-template>s', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-template #a>Some content</ng-template>
<div>Tag in between</div>
<ng-template #b>Some content</ng-template>
<p>Tag in between</p>
<ng-template #c>
Some content
<ng-template #d>
Nested template content.
</ng-template>
</ng-template>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
describe('transplanted views', () => {
it('should work when passing TemplateRef to a different component', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'insertion-component',
template: `
<ng-container [ngTemplateOutlet]="template"></ng-container>
`,
})
class InsertionComponent {
@Input() template!: TemplateRef<unknown>;
}
@Component({
standalone: true,
selector: 'app',
imports: [InsertionComponent, CommonModule],
template: `
<ng-template #template>
This is a transplanted view!
<div *ngIf="true">With more nested views!</div>
</ng-template>
<insertion-component [template]="template" />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
});
});
| {
"end_byte": 64230,
"start_byte": 56834,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_64236_72595 | escribe('i18n', () => {
describe('support is enabled', () => {
afterEach(() => {
clearTranslations();
});
it('should append skip hydration flag if component uses i18n blocks and no `withI18nSupport()` call present', async () => {
@Component({
standalone: true,
selector: 'app',
template: '<div i18n>Hi!</div>',
})
class SimpleComponent {
// Having `ViewContainerRef` here is important: it triggers
// a code path that serializes top-level `LContainer`s.
vcr = inject(ViewContainerRef);
}
const hydrationFeatures = [] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
// Since `withI18nSupport()` was not included and a component has i18n blocks -
// we expect that the `ngSkipHydration` attribute was added during serialization.
expect(ssrContents).not.toContain('ngh="');
expect(ssrContents).toContain('ngskiphydration="');
});
it('should not append skip hydration flag if component uses i18n blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div i18n>Hi!</div>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
});
it('should not append skip hydration flag if component uses i18n blocks inside embedded views', async () => {
@Component({
standalone: true,
imports: [NgIf],
selector: 'app',
template: `
<main *ngIf="true">
<div *ngIf="true" i18n>Hi!</div>
</main>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
});
it('should not append skip hydration flag if component uses i18n blocks on <ng-container>s', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-container i18n>Hi!</ng-container>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
});
it('should not append skip hydration flag if component uses i18n blocks (with *ngIfs on <ng-container>s)', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'app',
template: `
<ng-container *ngIf="true" i18n>Hi!</ng-container>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
});
it('should support translations that do not include every placeholder', async () => {
loadTranslations({
[computeMsgId('Some {$START_TAG_STRONG}strong{$CLOSE_TAG_STRONG} content')]:
'Some normal content',
});
@Component({
standalone: true,
selector: 'app',
template: `<div i18n>Some <strong>strong</strong> content</div>`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.innerHTML).toBe('Some normal content');
});
it('should support projecting translated content', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `<ng-content select="span"></ng-content><ng-content select="div"></ng-content>`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `<div i18n><app-content><div>one</div><span>two</span></app-content></div>`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
expect(content.innerHTML).toBe('<span>two</span><div>one</div>');
});
it('should work when i18n content is not projected', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `
@if (false) {
<ng-content />
}
Content outside of 'if'.
`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content>
<div i18n>Hello!</div>
<ng-container i18n>Hello again!</ng-container>
</app-content>
`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
const text = content.textContent.trim();
expect(text).toBe("Content outside of 'if'.");
expect(text).not.toContain('Hello');
});
| {
"end_byte": 72595,
"start_byte": 64236,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_72605_81139 | t('should support interleaving projected content', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `Start <ng-content select="div" /> Middle <ng-content select="span" /> End`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content i18n>
<span>Span</span>
Middle Start
Middle End
<div>Div</div>
</app-content>
`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
expect(content.innerHTML).toBe('Start <div>Div</div> Middle <span>Span</span> End');
});
it('should support disjoint nodes', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `Start <ng-content select=":not(span)" /> Middle <ng-content select="span" /> End`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content i18n>
Inner Start
<span>Span</span>
{ count, plural, other { Hello <span>World</span>! }}
Inner End
</app-content>
`,
imports: [ContentComponent],
})
class SimpleComponent {
count = 0;
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
expect(content.innerHTML).toBe(
'Start Inner Start Hello <span>World</span>! <!--ICU 26:0--> Inner End Middle <span>Span</span> End',
);
});
it('should support nested content projection', async () => {
@Component({
standalone: true,
selector: 'app-content-inner',
template: `Start <ng-content select=":not(span)" /> Middle <ng-content select="span" /> End`,
})
class InnerContentComponent {}
@Component({
standalone: true,
selector: 'app-content-outer',
template: `<app-content-inner><ng-content /></app-content-inner>`,
imports: [InnerContentComponent],
})
class OuterContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content-outer i18n>
Outer Start
<span>Span</span>
{ count, plural, other { Hello <span>World</span>! }}
Outer End
</app-content-outer>
`,
imports: [OuterContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, OuterContentComponent, InnerContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content-outer');
expect(content.innerHTML).toBe(
'<app-content-inner>Start Outer Start <span>Span</span> Hello <span>World</span>! <!--ICU 26:0--> Outer End Middle End</app-content-inner>',
);
});
it('should support hosting projected content', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `<span i18n>Start <ng-content /> End</span>`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `<div><app-content>Middle</app-content></div>`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.innerHTML).toBe('<app-content><span>Start Middle End</span></app-content>');
});
it('should support projecting multiple elements', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `<ng-content />`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content i18n>
Start
<span>Middle</span>
End
</app-content>
`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
expect(content.innerHTML).toMatch(/ Start <span>Middle<\/span> End /);
});
| {
"end_byte": 81139,
"start_byte": 72605,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_81149_90496 | t('should support disconnecting i18n nodes during projection', async () => {
@Component({
standalone: true,
selector: 'app-content',
template: `Start <ng-content select="span" /> End`,
})
class ContentComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<app-content i18n>
Middle Start
<span>Middle</span>
Middle End
</app-content>
`,
imports: [ContentComponent],
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ContentComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const content = clientRootNode.querySelector('app-content');
expect(content.innerHTML).toBe('Start <span>Middle</span> End');
});
it('should support using translated views as view container anchors', async () => {
@Component({
standalone: true,
selector: 'dynamic-cmp',
template: `DynamicComponent content`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
template: `<div i18n><div #target>one</div><span>two</span></div>`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
const clientContents = stripExcessiveSpaces(stripUtilAttributes(div.innerHTML, false));
expect(clientContents).toBe(
'<div>one</div><dynamic-cmp>DynamicComponent content</dynamic-cmp><!--container--><span>two</span>',
);
});
it('should support translations that reorder placeholders', async () => {
loadTranslations({
[computeMsgId(
'{$START_TAG_DIV}one{$CLOSE_TAG_DIV}{$START_TAG_SPAN}two{$CLOSE_TAG_SPAN}',
)]: '{$START_TAG_SPAN}dos{$CLOSE_TAG_SPAN}{$START_TAG_DIV}uno{$CLOSE_TAG_DIV}',
});
@Component({
standalone: true,
selector: 'app',
template: `<div i18n><div>one</div><span>two</span></div>`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.innerHTML).toBe('<span>dos</span><div>uno</div>');
});
it('should support translations that include additional elements', async () => {
loadTranslations({
[computeMsgId('{VAR_PLURAL, plural, other {normal}}')]:
'{VAR_PLURAL, plural, other {<strong>strong</strong>}}',
});
@Component({
standalone: true,
selector: 'app',
template: `<div i18n>Some {case, plural, other {normal}} content</div>`,
})
class SimpleComponent {
case = 0;
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.innerHTML).toMatch(/Some <strong>strong<\/strong><!--ICU 26:0--> content/);
});
it('should support translations that remove elements', async () => {
loadTranslations({
[computeMsgId('Hello {$START_TAG_STRONG}World{$CLOSE_TAG_STRONG}!')]: 'Bonjour!',
});
@Component({
standalone: true,
selector: 'app',
template: `<div i18n>Hello <strong>World</strong>!</div>`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.innerHTML).toMatch(/Bonjour!/);
});
it('should cleanup dehydrated ICU cases', async () => {
@Component({
standalone: true,
selector: 'app',
template: `<div i18n>{isServer, select, true { This is a SERVER-ONLY content } false { This is a CLIENT-ONLY content }}</div>`,
})
class SimpleComponent {
isServer = isPlatformServer(inject(PLATFORM_ID)) + '';
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('This is a CLIENT-ONLY content');
expect(ssrContents).toContain('This is a SERVER-ONLY content');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('This is a CLIENT-ONLY content');
expect(clientContents).not.toContain('This is a SERVER-ONLY content');
});
| {
"end_byte": 90496,
"start_byte": 81149,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_90506_98114 | t('should hydrate ICUs (simple)', async () => {
@Component({
standalone: true,
selector: 'app',
template: `<div i18n>{{firstCase}} {firstCase, plural, =1 {item} other {items}}, {{secondCase}} {secondCase, plural, =1 {item} other {items}}</div>`,
})
class SimpleComponent {
firstCase = 0;
secondCase = 1;
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const div = clientRootNode.querySelector('div');
expect(div.textContent).toBe('0 items, 1 item');
});
it('should hydrate ICUs (nested)', async () => {
@Component({
standalone: true,
selector: 'simple-component',
template: `<div i18n>{firstCase, select, 1 {one-{secondCase, select, 1 {one} 2 {two}}} 2 {two-{secondCase, select, 1 {one} 2 {two}}}}</div>`,
})
class SimpleComponent {
@Input() firstCase!: number;
@Input() secondCase!: number;
}
@Component({
standalone: true,
imports: [SimpleComponent],
selector: 'app',
template: `
<simple-component id="one" firstCase="1" secondCase="1"></simple-component>
<simple-component id="two" firstCase="1" secondCase="2"></simple-component>
<simple-component id="three" firstCase="2" secondCase="1"></simple-component>
<simple-component id="four" firstCase="2" secondCase="2"></simple-component>
`,
})
class AppComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(AppComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(AppComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, AppComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<AppComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.querySelector('#one').textContent).toBe('one-one');
expect(clientRootNode.querySelector('#two').textContent).toBe('one-two');
expect(clientRootNode.querySelector('#three').textContent).toBe('two-one');
expect(clientRootNode.querySelector('#four').textContent).toBe('two-two');
});
it('should hydrate containers', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-container i18n>
Container #1
</ng-container>
<ng-container i18n>
Container #2
</ng-container>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const clientContents = stripExcessiveSpaces(clientRootNode.innerHTML);
expect(clientContents).toBe(
' Container #1 <!--ng-container--> Container #2 <!--ng-container-->',
);
});
it('should hydrate when using the *ngFor directive', async () => {
@Component({
standalone: true,
imports: [NgFor],
selector: 'app',
template: `
<ol i18n>
<li *ngFor="let item of items">{{ item }}</li>
</ol>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const clientContents = stripExcessiveSpaces(clientRootNode.innerHTML);
expect(clientContents).toBe(
'<ol><li>1</li><li>2</li><li>3</li><!--bindings={ "ng-reflect-ng-for-of": "1,2,3" }--></ol>',
);
});
it('should hydrate when using @for control flow', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ol i18n>
@for (item of items; track $index) {
<li>{{ item }}</li>
}
</ol>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const clientContents = stripExcessiveSpaces(clientRootNode.innerHTML);
expect(clientContents).toBe('<ol><li>1</li><li>2</li><li>3</li><!--container--></ol>');
});
| {
"end_byte": 98114,
"start_byte": 90506,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_98124_101912 | escribe('with ngSkipHydration', () => {
it('should skip hydration when ngSkipHydration and i18n attributes are present on a same node', async () => {
loadTranslations({
[computeMsgId(' Some {$START_TAG_STRONG}strong{$CLOSE_TAG_STRONG} content ')]:
'Some normal content',
});
@Component({
standalone: true,
selector: 'cmp-a',
template: `<ng-content />`,
})
class CmpA {}
@Component({
standalone: true,
selector: 'app',
imports: [CmpA],
template: `
<cmp-a i18n ngSkipHydration>
Some <strong>strong</strong> content
</cmp-a>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const cmpA = clientRootNode.querySelector('cmp-a');
expect(cmpA.textContent).toBe('Some normal content');
verifyNodeHasSkipHydrationMarker(cmpA);
});
it('should skip hydration when i18n is inside of an ngSkipHydration block', async () => {
loadTranslations({
[computeMsgId('strong')]: 'very strong',
});
@Component({
standalone: true,
selector: 'cmp-a',
template: `<ng-content />`,
})
class CmpA {}
@Component({
standalone: true,
selector: 'app',
imports: [CmpA],
template: `
<cmp-a ngSkipHydration>
Some <strong i18n>strong</strong> content
</cmp-a>
`,
})
class SimpleComponent {}
const hydrationFeatures = [withI18nSupport()] as unknown as HydrationFeature<any>[];
const html = await ssr(SimpleComponent, {hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
const cmpA = clientRootNode.querySelector('cmp-a');
expect(cmpA.textContent.trim()).toBe('Some very strong content');
verifyNodeHasSkipHydrationMarker(cmpA);
});
});
});
// Note: hydration for i18n blocks is not *yet* fully supported, so the tests
// below verify that components that use i18n are excluded from the hydration
// by adding the `ngSkipHydration` flag onto the component host element.
| {
"end_byte": 101912,
"start_byte": 98124,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_101919_110307 | escribe('support is disabled', () => {
it('should append skip hydration flag if component uses i18n blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div i18n>Hi!</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="">');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should keep the skip hydration flag if component uses i18n blocks', async () => {
@Component({
standalone: true,
selector: 'app',
host: {ngSkipHydration: 'true'},
template: `
<div i18n>Hi!</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="true">');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should append skip hydration flag if component uses i18n blocks inside embedded views', async () => {
@Component({
standalone: true,
imports: [NgIf],
selector: 'app',
template: `
<main *ngIf="true">
<div *ngIf="true" i18n>Hi!</div>
</main>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="">');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should append skip hydration flag if component uses i18n blocks on <ng-container>s', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-container i18n>Hi!</ng-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="">');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should append skip hydration flag if component uses i18n blocks (with *ngIfs on <ng-container>s)', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'app',
template: `
<ng-container *ngIf="true" i18n>Hi!</ng-container>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="">');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should *not* throw when i18n attributes are used', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div i18n-title title="Hello world">Hi!</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should *not* throw when i18n is used in nested component ' +
'excluded using `ngSkipHydration`',
async () => {
@Component({
standalone: true,
selector: 'nested',
template: `
<div i18n>Hi!</div>
`,
})
class NestedComponent {}
@Component({
standalone: true,
imports: [NestedComponent],
selector: 'app',
template: `
Nested component with i18n inside:
<nested ngSkipHydration />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it('should exclude components with i18n from hydration automatically', async () => {
@Component({
standalone: true,
selector: 'nested',
template: `
<div i18n>Hi!</div>
`,
})
class NestedComponent {}
@Component({
standalone: true,
imports: [NestedComponent],
selector: 'app',
template: `
Nested component with i18n inside
(the content of this component would be excluded from hydration):
<nested />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
});
| {
"end_byte": 110307,
"start_byte": 101919,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_110313_117509 | escribe('defer blocks', () => {
it('should not trigger defer blocks on the server', async () => {
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp],
template: `
Visible: {{ isVisible }}.
@defer (when isVisible) {
<my-lazy-cmp />
} @loading {
Loading...
} @placeholder {
Placeholder!
} @error {
Failed to load dependencies :(
}
`,
})
class SimpleComponent {
isVisible = false;
ngOnInit() {
setTimeout(() => {
// This changes the triggering condition of the defer block,
// but it should be ignored and the placeholder content should be visible.
this.isVisible = true;
});
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Even though trigger condition is `true`,
// the defer block remains in the "placeholder" mode on the server.
expect(ssrContents).toContain('Visible: true.');
expect(ssrContents).toContain('Placeholder');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// This content is rendered only on the client, since it's
// inside a defer block.
const innerComponent = clientRootNode.querySelector('my-lazy-cmp');
const exceptions = [innerComponent];
verifyAllNodesClaimedForHydration(clientRootNode, exceptions);
// Verify that defer block renders correctly after hydration and triggering
// loading condition.
expect(clientRootNode.outerHTML).toContain('<my-lazy-cmp>Hi!</my-lazy-cmp>');
});
it('should hydrate a placeholder block', async () => {
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
selector: 'my-placeholder-cmp',
standalone: true,
imports: [NgIf],
template: '<div *ngIf="true">Hi!</div>',
})
class MyPlaceholderCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp, MyPlaceholderCmp],
template: `
Visible: {{ isVisible }}.
@defer (when isVisible) {
<my-lazy-cmp />
} @loading {
Loading...
} @placeholder {
Placeholder!
<my-placeholder-cmp />
} @error {
Failed to load dependencies :(
}
`,
})
class SimpleComponent {
isVisible = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Make sure we have placeholder contents in SSR output.
expect(ssrContents).toContain('Placeholder! <my-placeholder-cmp ngh="0"><div>Hi!</div>');
resetTViewsFor(SimpleComponent, MyPlaceholderCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should render nothing on the server if no placeholder block is provided', async () => {
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
selector: 'my-placeholder-cmp',
standalone: true,
imports: [NgIf],
template: '<div *ngIf="true">Hi!</div>',
})
class MyPlaceholderCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp, MyPlaceholderCmp],
template: `
Before|@defer (when isVisible) {<my-lazy-cmp />}|After
`,
})
class SimpleComponent {
isVisible = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Make sure no elements from a defer block is present in SSR output.
// Note: comment nodes represent main content and defer block anchors,
// which is expected.
expect(ssrContents).toContain('Before|<!--container--><!--container-->|After');
resetTViewsFor(SimpleComponent, MyPlaceholderCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should not reference IntersectionObserver on the server', async () => {
// This test verifies that there are no errors produced while rendering on a server
// when `on viewport` trigger is used for a defer block.
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp],
template: `
@defer (when isVisible; prefetch on viewport(ref)) {
<my-lazy-cmp />
} @placeholder {
<div #ref>Placeholder!</div>
}
`,
})
class SimpleComponent {
isVisible = false;
}
const errors: string[] = [];
class CustomErrorHandler extends ErrorHandler {
override handleError(error: any): void {
errors.push(error);
}
}
const envProviders = [
{
provide: ErrorHandler,
useClass: CustomErrorHandler,
},
];
const html = await ssr(SimpleComponent, {envProviders});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('Placeholder');
// Verify that there are no errors.
expect(errors).toHaveSize(0);
});
| {
"end_byte": 117509,
"start_byte": 110313,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_117517_124457 | t('should not hydrate when an entire block in skip hydration section', async () => {
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content />
</main>
`,
})
class ProjectorCmp {}
@Component({
selector: 'my-placeholder-cmp',
standalone: true,
imports: [NgIf],
template: '<div *ngIf="true">Hi!</div>',
})
class MyPlaceholderCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp, MyPlaceholderCmp, ProjectorCmp],
template: `
Visible: {{ isVisible }}.
<projector-cmp ngSkipHydration="true">
@defer (when isVisible) {
<my-lazy-cmp />
} @loading {
Loading...
} @placeholder {
<my-placeholder-cmp />
} @error {
Failed to load dependencies :(
}
</projector-cmp>
`,
})
class SimpleComponent {
isVisible = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Make sure we have placeholder contents in SSR output.
expect(ssrContents).toContain('<my-placeholder-cmp');
resetTViewsFor(SimpleComponent, MyPlaceholderCmp, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// Verify that placeholder nodes were not claimed for hydration,
// i.e. nodes were re-created since placeholder was in skip hydration block.
const placeholderCmp = clientRootNode.querySelector('my-placeholder-cmp');
verifyNoNodesWereClaimedForHydration(placeholderCmp);
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should not hydrate when a placeholder block in skip hydration section', async () => {
@Component({
selector: 'my-lazy-cmp',
standalone: true,
template: 'Hi!',
})
class MyLazyCmp {}
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content />
</main>
`,
})
class ProjectorCmp {}
@Component({
selector: 'my-placeholder-cmp',
standalone: true,
imports: [NgIf],
template: '<div *ngIf="true">Hi!</div>',
})
class MyPlaceholderCmp {}
@Component({
standalone: true,
selector: 'app',
imports: [MyLazyCmp, MyPlaceholderCmp, ProjectorCmp],
template: `
Visible: {{ isVisible }}.
<projector-cmp ngSkipHydration="true">
@defer (when isVisible) {
<my-lazy-cmp />
} @loading {
Loading...
} @placeholder {
<my-placeholder-cmp ngSkipHydration="true" />
} @error {
Failed to load dependencies :(
}
</projector-cmp>
`,
})
class SimpleComponent {
isVisible = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Make sure we have placeholder contents in SSR output.
expect(ssrContents).toContain('<my-placeholder-cmp');
resetTViewsFor(SimpleComponent, MyPlaceholderCmp, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// Verify that placeholder nodes were not claimed for hydration,
// i.e. nodes were re-created since placeholder was in skip hydration block.
const placeholderCmp = clientRootNode.querySelector('my-placeholder-cmp');
verifyNoNodesWereClaimedForHydration(placeholderCmp);
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
describe('ShadowDom encapsulation', () => {
it('should append skip hydration flag if component uses ShadowDom encapsulation', async () => {
@Component({
standalone: true,
selector: 'app',
encapsulation: ViewEncapsulation.ShadowDom,
template: `Hi!`,
styles: [':host { color: red; }'],
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngskiphydration="">');
});
it(
'should append skip hydration flag if component uses ShadowDom encapsulation ' +
'(but keep parent and sibling elements hydratable)',
async () => {
@Component({
standalone: true,
selector: 'shadow-dom',
encapsulation: ViewEncapsulation.ShadowDom,
template: `ShadowDom component`,
styles: [':host { color: red; }'],
})
class ShadowDomComponent {}
@Component({
standalone: true,
selector: 'regular',
template: `<p>Regular component</p>`,
})
class RegularComponent {
@Input() id?: string;
}
@Component({
standalone: true,
selector: 'app',
imports: [RegularComponent, ShadowDomComponent],
template: `
<main>Main content</main>
<regular id="1" />
<shadow-dom />
<regular id="2" />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh="0">');
expect(ssrContents).toContain('<shadow-dom ngskiphydration="">');
expect(ssrContents).toContain('<regular id="1" ngh="0">');
expect(ssrContents).toContain('<regular id="2" ngh="0">');
},
);
});
| {
"end_byte": 124457,
"start_byte": 117517,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_124463_134179 | escribe('ngSkipHydration', () => {
it('should skip hydrating elements with ngSkipHydration attribute', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div>This is the content of a nested component</div>
`,
})
class NestedComponent {
@Input() title = '';
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp [title]="someTitle" style="width:100px; height:200px; color:red" moo="car" foo="value" baz ngSkipHydration />
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should skip hydrating elements when host element ' + 'has the ngSkipHydration attribute',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main>Main content</main>
`,
})
class SimpleComponent {}
const indexHtml =
'<html><head></head><body>' + '<app ngSkipHydration></app>' + '</body></html>';
const html = await ssr(SimpleComponent, {doc: indexHtml});
const ssrContents = getAppContents(html);
// No `ngh` attribute in the <app> element.
expect(ssrContents).toContain('<app ngskiphydration=""><main>Main content</main></app>');
// Even though hydration was skipped at the root level, the hydration
// info key and an empty array as a value are still included into the
// TransferState to indicate that the server part was configured correctly.
const transferState = getHydrationInfoFromTransferState(html);
expect(transferState).toContain(TRANSFER_STATE_TOKEN_ID);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should allow the same component with and without hydration in the same template ' +
'(when component with `ngSkipHydration` goes first)',
async () => {
@Component({
standalone: true,
selector: 'nested',
imports: [NgIf],
template: `
<ng-container *ngIf="true">Hello world</ng-container>
`,
})
class Nested {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, Nested],
template: `
<nested ngSkipHydration />
<nested />
<nested ngSkipHydration />
<nested />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, Nested);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should allow projecting hydrated content into components that skip hydration ' +
'(view containers with embedded views as projection root nodes)',
async () => {
@Component({
standalone: true,
selector: 'regular-cmp',
template: `
<ng-content />
`,
})
class RegularCmp {}
@Component({
standalone: true,
selector: 'deeply-nested',
host: {ngSkipHydration: 'true'},
template: `
<ng-content />
`,
})
class DeeplyNested {}
@Component({
standalone: true,
selector: 'deeply-nested-wrapper',
host: {ngSkipHydration: 'true'},
imports: [RegularCmp],
template: `
<regular-cmp>
<ng-content />
</regular-cmp>
`,
})
class DeeplyNestedWrapper {}
@Component({
standalone: true,
selector: 'layout',
imports: [DeeplyNested, DeeplyNestedWrapper],
template: `
<deeply-nested>
<deeply-nested-wrapper>
<ng-content />
</deeply-nested-wrapper>
</deeply-nested>
`,
})
class Layout {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, Layout],
template: `
<layout>
<h1 *ngIf="true">Hi!</h1>
</layout>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, Layout, RegularCmp, DeeplyNested, DeeplyNestedWrapper);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should allow projecting hydrated content into components that skip hydration ' +
'(view containers with components as projection root nodes)',
async () => {
@Component({
standalone: true,
selector: 'dynamic-cmp',
template: `DynamicComponent content`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'regular-cmp',
template: `
<ng-content />
`,
})
class RegularCmp {}
@Component({
standalone: true,
selector: 'deeply-nested',
host: {ngSkipHydration: 'true'},
template: `
<ng-content />
`,
})
class DeeplyNested {}
@Component({
standalone: true,
selector: 'deeply-nested-wrapper',
host: {ngSkipHydration: 'true'},
imports: [RegularCmp],
template: `
<regular-cmp>
<ng-content />
</regular-cmp>
`,
})
class DeeplyNestedWrapper {}
@Component({
standalone: true,
selector: 'layout',
imports: [DeeplyNested, DeeplyNestedWrapper],
template: `
<deeply-nested>
<deeply-nested-wrapper>
<ng-content />
</deeply-nested-wrapper>
</deeply-nested>
`,
})
class Layout {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, Layout],
template: `
<layout>
<div #target></div>
</layout>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(
SimpleComponent,
Layout,
DynamicComponent,
RegularCmp,
DeeplyNested,
DeeplyNestedWrapper,
);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
| {
"end_byte": 134179,
"start_byte": 124463,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_134187_142135 | t(
'should allow projecting hydrated content into components that skip hydration ' +
'(with ng-containers as projection root nodes)',
async () => {
@Component({
standalone: true,
selector: 'regular-cmp',
template: `
<ng-content />
`,
})
class RegularCmp {}
@Component({
standalone: true,
selector: 'deeply-nested',
host: {ngSkipHydration: 'true'},
template: `
<ng-content />
`,
})
class DeeplyNested {}
@Component({
standalone: true,
selector: 'deeply-nested-wrapper',
host: {ngSkipHydration: 'true'},
imports: [RegularCmp],
template: `
<regular-cmp>
<ng-content />
</regular-cmp>
`,
})
class DeeplyNestedWrapper {}
@Component({
standalone: true,
selector: 'layout',
imports: [DeeplyNested, DeeplyNestedWrapper],
template: `
<deeply-nested>
<deeply-nested-wrapper>
<ng-content />
</deeply-nested-wrapper>
</deeply-nested>
`,
})
class Layout {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, Layout],
template: `
<layout>
<ng-container>Hi!</ng-container>
</layout>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, Layout, RegularCmp, DeeplyNested, DeeplyNestedWrapper);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should allow the same component with and without hydration in the same template ' +
'(when component without `ngSkipHydration` goes first)',
async () => {
@Component({
standalone: true,
selector: 'nested',
imports: [NgIf],
template: `
<ng-container *ngIf="true">Hello world</ng-container>
`,
})
class Nested {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, Nested],
template: `
<nested />
<nested ngSkipHydration />
<nested />
<nested ngSkipHydration />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent, Nested);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it('should hydrate when the value of an attribute is "ngskiphydration"', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div>This is the content of a nested component</div>
`,
})
class NestedComponent {
@Input() title = '';
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp style="width:100px; height:200px; color:red" moo="car" foo="value" baz [title]="ngSkipHydration" />
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should skip hydrating elements with ngSkipHydration host binding', async () => {
@Component({
standalone: true,
selector: 'second-cmp',
template: `<div>Not hydrated</div>`,
})
class SecondCmd {}
@Component({
standalone: true,
imports: [SecondCmd],
selector: 'nested-cmp',
template: `<second-cmp />`,
host: {ngSkipHydration: 'true'},
})
class NestedCmp {}
@Component({
standalone: true,
imports: [NestedCmp],
selector: 'app',
template: `
<nested-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should skip hydrating all child content of an element with ngSkipHydration attribute', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div>This is the content of a nested component</div>
`,
})
class NestedComponent {
@Input() title = '';
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp ngSkipHydration>
<h1>Dehydrated content header</h1>
<p>This content is definitely dehydrated and could use some water.</p>
</nested-cmp>
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
| {
"end_byte": 142135,
"start_byte": 134187,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_142143_151409 | t('should skip hydrating when ng-containers exist and ngSkipHydration attribute is present', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div>This is the content of a nested component</div>
`,
})
class NestedComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp ngSkipHydration>
<ng-container>
<h1>Dehydrated content header</h1>
</ng-container>
</nested-cmp>
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyHasLog(
appRef,
'Angular hydrated 1 component(s) and 6 node(s), 1 component(s) were skipped',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should skip hydrating and safely allow DOM manipulation inside block that was skipped', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div #nestedDiv>This is the content of a nested component</div>
`,
})
class NestedComponent {
el = inject(ElementRef);
ngAfterViewInit() {
const span = document.createElement('span');
span.innerHTML = 'Appended span';
this.el.nativeElement.appendChild(span);
}
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp ngSkipHydration />
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
expect(clientRootNode.outerHTML).toContain('Appended span');
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should skip hydrating and safely allow adding and removing DOM nodes inside block that was skipped', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `
<h1>Hello World!</h1>
<div #nestedDiv>
<p>This content will be removed</p>
</div>
`,
})
class NestedComponent {
el = inject(ElementRef);
ngAfterViewInit() {
document.querySelector('p')?.remove();
const span = document.createElement('span');
span.innerHTML = 'Appended span';
this.el.nativeElement.appendChild(span);
}
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `
<header>Header</header>
<nested-cmp ngSkipHydration />
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
expect(clientRootNode.outerHTML).toContain('Appended span');
expect(clientRootNode.outerHTML).not.toContain('This content will be removed');
verifyAllNodesClaimedForHydration(clientRootNode);
});
it('should skip hydrating elements with ngSkipHydration attribute on ViewContainerRef host', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
template: `<p>Just some text</p>`,
})
class NestedComponent {
el = inject(ElementRef);
doc = inject(DOCUMENT);
ngAfterViewInit() {
const pTag = this.doc.querySelector('p');
pTag?.remove();
const span = this.doc.createElement('span');
span.innerHTML = 'Appended span';
this.el.nativeElement.appendChild(span);
}
}
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [NestedComponent],
template: `
<main>
<nested-cmp></nested-cmp>
</main>
`,
})
class ProjectorCmp {
vcr = inject(ViewContainerRef);
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp ngSkipHydration>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should throw when ngSkipHydration attribute is set on a node ' +
'which is not a component host',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<header ngSkipHydration>Header</header>
<footer ngSkipHydration>Footer</footer>
`,
})
class SimpleComponent {}
try {
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
fail('Expected the hydration process to throw.');
} catch (e: unknown) {
expect((e as Error).toString()).toContain(
'The `ngSkipHydration` flag is applied ' +
"on a node that doesn't act as a component host",
);
}
},
);
it(
'should throw when ngSkipHydration attribute is set on a node ' +
'which is not a component host (when using host bindings)',
async () => {
@Directive({
standalone: true,
selector: '[dir]',
host: {ngSkipHydration: 'true'},
})
class Dir {}
@Component({
standalone: true,
selector: 'app',
imports: [Dir],
template: `
<div dir></div>
`,
})
class SimpleComponent {}
try {
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
fail('Expected the hydration process to throw.');
} catch (e: unknown) {
const errorMessage = (e as Error).toString();
expect(errorMessage).toContain(
'The `ngSkipHydration` flag is applied ' +
"on a node that doesn't act as a component host",
);
expect(errorMessage).toContain(
'<div ngskiphydration="true" dir="">…</div> <-- AT THIS LOCATION',
);
}
},
);
});
| {
"end_byte": 151409,
"start_byte": 142143,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_151415_157484 | cribe('corrupted text nodes restoration', () => {
it('should support empty text nodes', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is hydrated content.
<span>{{spanText}}</span>.
<p>{{pText}}</p>
<div>{{anotherText}}</div>
`,
})
class SimpleComponent {
spanText = '';
pText = '';
anotherText = '';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should support empty text interpolations within elements ' +
'(when interpolation is on a new line)',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div>
{{ text }}
</div>
`,
})
class SimpleComponent {
text = '';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Expect special markers to not be present, since there
// are no corrupted text nodes that require restoring.
//
// The HTML contents produced by the SSR would look like this:
// `<div> </div>` (1 text node with 2 empty spaces inside of
// a <div>), which would result in creating a text node by a
// browser.
expect(ssrContents).not.toContain(EMPTY_TEXT_NODE_COMMENT);
expect(ssrContents).not.toContain(TEXT_NODE_SEPARATOR_COMMENT);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it('should not treat text nodes with ` `s as empty', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div> {{ text }} </div>
<h1>Hello world!</h1>
<h2>Hello world!</h2>
`,
})
class SimpleComponent {
text = '';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Expect special markers to not be present, since there
// are no corrupted text nodes that require restoring.
expect(ssrContents).not.toContain(EMPTY_TEXT_NODE_COMMENT);
expect(ssrContents).not.toContain(TEXT_NODE_SEPARATOR_COMMENT);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support restoration of multiple text nodes in a row', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is hydrated content.<span>{{emptyText}}{{moreText}}{{andMoreText}}</span>.
<p>{{secondEmptyText}}{{secondMoreText}}</p>
`,
})
class SimpleComponent {
emptyText = '';
moreText = '';
andMoreText = '';
secondEmptyText = '';
secondMoreText = '';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support projected text node content with plain text nodes', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<div>
Hello
<ng-container *ngIf="true">Angular</ng-container>
<ng-container *ngIf="true">World</ng-container>
</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 157484,
"start_byte": 151415,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_157490_166692 | cribe('post-hydration cleanup', () => {
it('should cleanup unclaimed views in a component (when using elements)', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<b *ngIf="isServer">This is a SERVER-ONLY content</b>
<i *ngIf="!isServer">This is a CLIENT-ONLY content</i>
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('<i>This is a CLIENT-ONLY content</i>');
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content</b>');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content</i>');
expect(clientContents).not.toContain('<b>This is a SERVER-ONLY content</b>');
});
it('should cleanup unclaimed views in a component (when using <ng-container>s)', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<ng-container *ngIf="isServer">This is a SERVER-ONLY content</ng-container>
<ng-container *ngIf="!isServer">This is a CLIENT-ONLY content</ng-container>
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('This is a CLIENT-ONLY content<!--ng-container-->');
expect(ssrContents).toContain('This is a SERVER-ONLY content<!--ng-container-->');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('This is a CLIENT-ONLY content<!--ng-container-->');
expect(clientContents).not.toContain('This is a SERVER-ONLY content<!--ng-container-->');
});
it(
'should cleanup unclaimed views in a view container when ' +
'root component is used as an anchor for ViewContainerRef',
async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<ng-template #tmpl>
<span *ngIf="isServer">This is a SERVER-ONLY content (embedded view)</span>
<div *ngIf="!isServer">This is a CLIENT-ONLY content (embedded view)</div>
</ng-template>
<b *ngIf="isServer">This is a SERVER-ONLY content (root component)</b>
<i *ngIf="!isServer">This is a CLIENT-ONLY content (root component)</i>
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain(
'<i>This is a CLIENT-ONLY content (root component)</i>',
);
expect(ssrContents).not.toContain(
'<div>This is a CLIENT-ONLY content (embedded view)</div>',
);
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content (root component)</b>');
expect(ssrContents).toContain(
'<span>This is a SERVER-ONLY content (embedded view)</span>',
);
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.parentNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content (root component)</i>');
expect(clientContents).toContain(
'<div>This is a CLIENT-ONLY content (embedded view)</div>',
);
expect(clientContents).not.toContain(
'<b>This is a SERVER-ONLY content (root component)</b>',
);
expect(clientContents).not.toContain(
'<span>This is a SERVER-ONLY content (embedded view)</span>',
);
},
);
it('should cleanup within inner containers', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<ng-container *ngIf="true">
<b *ngIf="isServer">This is a SERVER-ONLY content</b>
Outside of the container (must be retained).
</ng-container>
<i *ngIf="!isServer">This is a CLIENT-ONLY content</i>
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('<i>This is a CLIENT-ONLY content</i>');
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content</b>');
expect(ssrContents).toContain('Outside of the container (must be retained).');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content</i>');
expect(clientContents).not.toContain('<b>This is a SERVER-ONLY content</b>');
// This line must be preserved (it's outside of the dehydrated container).
expect(clientContents).toContain('Outside of the container (must be retained).');
});
| {
"end_byte": 166692,
"start_byte": 157490,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_166700_174206 | 'should reconcile *ngFor-generated views', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div>
<span *ngFor="let item of items">
{{ item }}
<b *ngIf="item > 15">is bigger than 15!</b>
</span>
<main>Hi! This is the main content.</main>
</div>
`,
})
class SimpleComponent {
isServer = isPlatformServer(inject(PLATFORM_ID));
// Note: this is needed to test cleanup/reconciliation logic.
items = this.isServer ? [10, 20, 100, 200] : [30, 5, 50];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
// Post-cleanup should *not* contain dehydrated views.
const postCleanupContents = stripExcessiveSpaces(clientRootNode.outerHTML);
expect(postCleanupContents).not.toContain(
'<span> 5 <b>is bigger than 15!</b><!--bindings={ "ng-reflect-ng-if": "false" }--></span>',
);
expect(postCleanupContents).toContain(
'<span> 30 <b>is bigger than 15!</b><!--bindings={ "ng-reflect-ng-if": "true" }--></span>',
);
expect(postCleanupContents).toContain(
'<span> 5 <!--bindings={ "ng-reflect-ng-if": "false" }--></span>',
);
expect(postCleanupContents).toContain(
'<span> 50 <b>is bigger than 15!</b><!--bindings={ "ng-reflect-ng-if": "true" }--></span>',
);
});
it('should cleanup dehydrated views within dynamically created components', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
<b *ngIf="isServer">This is a SERVER-ONLY content</b>
<i *ngIf="!isServer">This is a CLIENT-ONLY content</i>
<ng-container *ngIf="isServer">
This is also a SERVER-ONLY content, but inside ng-container.
<b>With some extra tags</b> and some text inside.
</ng-container>
`,
})
class DynamicComponent {
isServer = isPlatformServer(inject(PLATFORM_ID));
}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div #target></div>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// We expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('<i>This is a CLIENT-ONLY content</i>');
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content</b>');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content</i>');
expect(clientContents).not.toContain('<b>This is a SERVER-ONLY content</b>');
});
it('should trigger change detection after cleanup (immediate)', async () => {
const observedChildCountLog: number[] = [];
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<span *ngIf="isServer">This is a SERVER-ONLY content</span>
<span *ngIf="!isServer">This is a CLIENT-ONLY content</span>
`,
})
class SimpleComponent {
isServer = isPlatformServer(inject(PLATFORM_ID));
elementRef = inject(ElementRef);
constructor() {
afterRender(() => {
observedChildCountLog.push(this.elementRef.nativeElement.childElementCount);
});
}
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
// Before hydration
expect(observedChildCountLog).toEqual([]);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
await whenStable(appRef);
// afterRender should be triggered by:
// 1.) Bootstrap
// 2.) Microtask empty event
// 3.) Stabilization + cleanup
expect(observedChildCountLog).toEqual([2, 2, 1]);
});
it('should trigger change detection after cleanup (deferred)', async () => {
const observedChildCountLog: number[] = [];
@Component({
standalone: true,
selector: 'app',
imports: [NgIf],
template: `
<span *ngIf="isServer">This is a SERVER-ONLY content</span>
<span *ngIf="!isServer">This is a CLIENT-ONLY content</span>
`,
})
class SimpleComponent {
isServer = isPlatformServer(inject(PLATFORM_ID));
elementRef = inject(ElementRef);
constructor() {
afterRender(() => {
observedChildCountLog.push(this.elementRef.nativeElement.childElementCount);
});
// Create a dummy promise to prevent stabilization
new Promise<void>((resolve) => {
setTimeout(resolve, 0);
});
}
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
// Before hydration
expect(observedChildCountLog).toEqual([]);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
// afterRender should be triggered by:
// 1.) Bootstrap
// 2.) Microtask empty event
expect(observedChildCountLog).toEqual([2, 2]);
await whenStable(appRef);
// afterRender should be triggered by:
// 3.) Microtask empty event
// 4.) Stabilization + cleanup
expect(observedChildCountLog).toEqual([2, 2, 2, 1]);
});
});
| {
"end_byte": 174206,
"start_byte": 166700,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_174212_182572 | cribe('content projection', () => {
it('should project plain text', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content></ng-content>
</main>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
Projected content is just a plain text.
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyHasLog(
appRef,
'Angular hydrated 2 component(s) and 5 node(s), 0 component(s) were skipped',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should allow re-projection of child content', async () => {
@Component({
standalone: true,
selector: 'mat-step',
template: `<ng-template><ng-content /></ng-template>`,
})
class MatStep {
@ViewChild(TemplateRef, {static: true}) content!: TemplateRef<any>;
}
@Component({
standalone: true,
selector: 'mat-stepper',
imports: [NgTemplateOutlet],
template: `
@for (step of steps; track step) {
<ng-container [ngTemplateOutlet]="step.content" />
}
`,
})
class MatStepper {
@ContentChildren(MatStep) steps!: QueryList<MatStep>;
}
@Component({
standalone: true,
selector: 'nested-cmp',
template: 'Nested cmp content',
})
class NestedCmp {}
@Component({
standalone: true,
imports: [MatStepper, MatStep, NgIf, NestedCmp],
selector: 'app',
template: `
<mat-stepper>
<mat-step>Text-only content</mat-step>
<mat-step>
<ng-container>Using ng-containers</ng-container>
</mat-step>
<mat-step>
<ng-container *ngIf="true">
Using ng-containers with *ngIf
</ng-container>
</mat-step>
<mat-step>
@if (true) {
Using built-in control flow (if)
}
</mat-step>
<mat-step>
<nested-cmp />
</mat-step>
</mat-stepper>
`,
})
class App {}
const html = await ssr(App);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
// Verify that elements projected without their parent nodes
// use an element within the same template (at position `0`
// in the test, i.e. `<mat-stepper>`) as an anchor.
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain(
'"n":{"2":"0f","4":"0fn2","7":"0fn5","9":"0fn9","11":"0fn12"}',
);
resetTViewsFor(App, MatStepper, NestedCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, App);
const compRef = getComponentRef<App>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should project plain text and HTML elements', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content></ng-content>
</main>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
Projected content is a plain text.
<b>Also the content has some tags</b>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support re-projection of contents', async () => {
@Component({
standalone: true,
selector: 'reprojector-cmp',
template: `
<main>
<ng-content></ng-content>
</main>
`,
})
class ReprojectorCmp {}
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [ReprojectorCmp],
template: `
<reprojector-cmp>
<b>Before</b>
<ng-content></ng-content>
<i>After</i>
</reprojector-cmp>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
Projected content is a plain text.
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp, ReprojectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should handle multiple nodes projected in a single slot', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<ng-content select="foo" />
<ng-content select="bar" />
`,
})
class ProjectorCmp {}
@Component({selector: 'foo', standalone: true, template: ''})
class FooCmp {}
@Component({selector: 'bar', standalone: true, template: ''})
class BarCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp, FooCmp, BarCmp],
selector: 'app',
template: `
<projector-cmp>
<foo />
<bar />
<foo />
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
| {
"end_byte": 182572,
"start_byte": 174212,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_182580_191016 | 'should handle multiple nodes projected in a single slot (different order)', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<ng-content select="foo" />
<ng-content select="bar" />
`,
})
class ProjectorCmp {}
@Component({selector: 'foo', standalone: true, template: ''})
class FooCmp {}
@Component({selector: 'bar', standalone: true, template: ''})
class BarCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp, FooCmp, BarCmp],
selector: 'app',
template: `
<projector-cmp>
<bar />
<foo />
<bar />
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should handle empty projection slots within <ng-container>', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [CommonModule],
template: `
<ng-container *ngIf="true">
<ng-content select="[left]"></ng-content>
<div>
<ng-content select="[main]"></ng-content>
</div>
<ng-content select="[right]"></ng-content>
</ng-container>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should handle empty projection slots within <ng-container> ' +
'(when no other elements are present)',
async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [CommonModule],
template: `
<ng-container *ngIf="true">
<ng-content select="[left]"></ng-content>
<ng-content select="[right]"></ng-content>
</ng-container>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it(
'should handle empty projection slots within a template ' +
'(when no other elements are present)',
async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<ng-content select="[left]"></ng-content>
<ng-content select="[right]"></ng-content>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
it('should project contents into different slots', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<div>
Header slot: <ng-content select="header"></ng-content>
Main slot: <ng-content select="main"></ng-content>
Footer slot: <ng-content select="footer"></ng-content>
<ng-content></ng-content> <!-- everything else -->
</div>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
<!-- contents is intentionally randomly ordered -->
<h1>H1</h1>
<footer>Footer</footer>
<header>Header</header>
<main>Main</main>
<h2>H2</h2>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should handle view container nodes that go after projection slots', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [CommonModule],
template: `
<ng-container *ngIf="true">
<ng-content select="[left]"></ng-content>
<span *ngIf="true">{{ label }}</span>
</ng-container>
`,
})
class ProjectorCmp {
label = 'Hi';
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
| {
"end_byte": 191016,
"start_byte": 182580,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_191024_200808 |
'should handle view container nodes that go after projection slots ' +
'(when view container host node is <ng-container>)',
async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [CommonModule],
template: `
<ng-container *ngIf="true">
<ng-content select="[left]"></ng-content>
<ng-container *ngIf="true">{{ label }}</ng-container>
</ng-container>
`,
})
class ProjectorCmp {
label = 'Hi';
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp />
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
},
);
describe('partial projection', () => {
it('should support cases when some element nodes are not projected', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<div>
Header slot: <ng-content select="header" />
Main slot: <ng-content select="main" />
Footer slot: <ng-content select="footer" />
<!-- no "default" projection bucket -->
</div>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
<!-- contents is randomly ordered for testing -->
<h1>This node is not projected.</h1>
<footer>Footer</footer>
<header>Header</header>
<main>Main</main>
<h2>This node is not projected as well.</h2>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support cases when some element nodes are not projected', async () => {
@Component({
standalone: true,
selector: 'app-dropdown-content',
template: `<ng-content />`,
})
class DropdownContentComponent {}
@Component({
standalone: true,
selector: 'app-dropdown',
template: `
@if (false) {
<ng-content select="app-dropdown-content" />
}
`,
})
class DropdownComponent {}
@Component({
standalone: true,
imports: [DropdownComponent, DropdownContentComponent],
selector: 'app-menu',
template: `
<app-dropdown>
<app-dropdown-content>
<ng-content />
</app-dropdown-content>
</app-dropdown>
`,
})
class MenuComponent {}
@Component({
selector: 'app',
standalone: true,
imports: [MenuComponent],
template: `
<app-menu>
Menu Content
</app-menu>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(
SimpleComponent,
MenuComponent,
DropdownComponent,
DropdownContentComponent,
);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support cases when view containers are not projected', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `No content projection slots.`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
<ng-container *ngIf="true">
<h1>This node is not projected.</h1>
<h2>This node is not projected as well.</h2>
</ng-container>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support cases when component nodes are not projected', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `No content projection slots.`,
})
class ProjectorCmp {}
@Component({
standalone: true,
selector: 'nested',
template: 'This is a nested component.',
})
class NestedComponent {}
@Component({
standalone: true,
imports: [ProjectorCmp, NestedComponent],
selector: 'app',
template: `
<projector-cmp>
<nested>
<h1>This node is not projected.</h1>
<h2>This node is not projected as well.</h2>
</nested>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support cases when component nodes are not projected in nested components', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content />
</main>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
selector: 'nested',
template: 'No content projection slots.',
})
class NestedComponent {}
@Component({
standalone: true,
imports: [ProjectorCmp, NestedComponent],
selector: 'app',
template: `
<projector-cmp>
<nested>
<h1>This node is not projected.</h1>
<h2>This node is not projected as well.</h2>
</nested>
</projector-cmp>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp, NestedComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
| {
"end_byte": 200808,
"start_byte": 191024,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_200816_209894 | "should project contents with *ngIf's", async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content></ng-content>
</main>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp, CommonModule],
selector: 'app',
template: `
<projector-cmp>
<h1 *ngIf="visible">Header with an ngIf condition.</h1>
</projector-cmp>
`,
})
class SimpleComponent {
visible = true;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should project contents with *ngFor', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<main>
<ng-content></ng-content>
</main>
`,
})
class ProjectorCmp {}
@Component({
standalone: true,
imports: [ProjectorCmp, CommonModule],
selector: 'app',
template: `
<projector-cmp>
<h1 *ngFor="let item of items">Item {{ item }}</h1>
</projector-cmp>
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should support projecting contents outside of a current host element', async () => {
@Component({
standalone: true,
selector: 'dynamic-cmp',
template: `<div #target></div>`,
})
class DynamicComponent {
@ViewChild('target', {read: ViewContainerRef}) vcRef!: ViewContainerRef;
createView(tmplRef: TemplateRef<unknown>) {
this.vcRef.createEmbeddedView(tmplRef);
}
}
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<ng-template #ref>
<ng-content></ng-content>
</ng-template>
`,
})
class ProjectorCmp {
@ViewChild('ref', {read: TemplateRef}) tmplRef!: TemplateRef<unknown>;
appRef = inject(ApplicationRef);
environmentInjector = inject(EnvironmentInjector);
doc = inject(DOCUMENT) as Document;
isServer = isPlatformServer(inject(PLATFORM_ID));
ngAfterViewInit() {
// Create a host DOM node outside of the main app's host node
// to emulate a situation where a host node already exists
// on a page.
let hostElement: Element;
if (this.isServer) {
hostElement = this.doc.createElement('portal-app');
this.doc.body.insertBefore(hostElement, this.doc.body.firstChild);
} else {
hostElement = this.doc.querySelector('portal-app')!;
}
const cmp = createComponent(DynamicComponent, {
hostElement,
environmentInjector: this.environmentInjector,
});
cmp.changeDetectorRef.detectChanges();
cmp.instance.createView(this.tmplRef);
this.appRef.attachView(cmp.hostView);
}
}
@Component({
standalone: true,
imports: [ProjectorCmp, CommonModule],
selector: 'app',
template: `
<projector-cmp>
<header>Header</header>
</projector-cmp>
`,
})
class SimpleComponent {
visible = true;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
const portalRootNode = clientRootNode.ownerDocument.querySelector('portal-app');
verifyAllNodesClaimedForHydration(clientRootNode);
verifyAllNodesClaimedForHydration(portalRootNode.firstChild);
const clientContents =
stripUtilAttributes(portalRootNode.outerHTML, false) +
stripUtilAttributes(clientRootNode.outerHTML, false);
expect(clientContents).toBe(
stripSsrIntegrityMarker(stripUtilAttributes(stripTransferDataScript(ssrContents), false)),
'Client and server contents mismatch',
);
});
it('should handle projected containers inside other containers', async () => {
@Component({
standalone: true,
selector: 'child-comp',
template: '<ng-content />',
})
class ChildComp {}
@Component({
standalone: true,
selector: 'root-comp',
template: '<ng-content />',
})
class RootComp {}
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule, RootComp, ChildComp],
template: `
<root-comp>
<ng-container *ngFor="let item of items; last as last">
<child-comp *ngIf="!last">{{ item }}|</child-comp>
</ng-container>
</root-comp>
`,
})
class MyApp {
items: number[] = [1, 2, 3];
}
const html = await ssr(MyApp);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(MyApp, RootComp, ChildComp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, MyApp);
const compRef = getComponentRef<MyApp>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should throw an error when projecting DOM nodes via ViewContainerRef.createComponent API', async () => {
@Component({
standalone: true,
selector: 'dynamic',
template: `
<ng-content />
<ng-content />
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div #target></div>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const div = document.createElement('div');
const p = document.createElement('p');
const span = document.createElement('span');
const b = document.createElement('b');
// In this test we create DOM nodes outside of Angular context
// (i.e. not using Angular APIs) and try to content-project them.
// This is an unsupported pattern and we expect an exception.
const compRef = this.vcr.createComponent(DynamicComponent, {
projectableNodes: [
[div, p],
[span, b],
],
});
compRef.changeDetectorRef.detectChanges();
}
}
try {
await ssr(SimpleComponent);
} catch (error: unknown) {
const errorMessage = (error as Error).toString();
expect(errorMessage).toContain(
'During serialization, Angular detected DOM nodes that ' +
'were created outside of Angular context',
);
expect(errorMessage).toContain('<dynamic>…</dynamic> <-- AT THIS LOCATION');
}
});
| {
"end_byte": 209894,
"start_byte": 200816,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_209902_217914 | hould throw an error when projecting DOM nodes via createComponent function call', async () => {
@Component({
standalone: true,
selector: 'dynamic',
template: `
<ng-content />
<ng-content />
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div #target></div>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
envInjector = inject(EnvironmentInjector);
ngAfterViewInit() {
const div = document.createElement('div');
const p = document.createElement('p');
const span = document.createElement('span');
const b = document.createElement('b');
// In this test we create DOM nodes outside of Angular context
// (i.e. not using Angular APIs) and try to content-project them.
// This is an unsupported pattern and we expect an exception.
const compRef = createComponent(DynamicComponent, {
environmentInjector: this.envInjector,
projectableNodes: [
[div, p],
[span, b],
],
});
compRef.changeDetectorRef.detectChanges();
}
}
try {
await ssr(SimpleComponent);
} catch (error: unknown) {
const errorMessage = (error as Error).toString();
expect(errorMessage).toContain(
'During serialization, Angular detected DOM nodes that ' +
'were created outside of Angular context',
);
expect(errorMessage).toContain('<dynamic>…</dynamic> <-- AT THIS LOCATION');
}
});
it('should support cases when <ng-content> is used with *ngIf="false"', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [NgIf],
template: `
Project?: <span>{{ project ? 'yes' : 'no' }}</span>
<ng-content *ngIf="project" />
`,
})
class ProjectorCmp {
@Input() project: boolean = false;
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp [project]="project">
<h1>This node is not projected.</h1>
<h2>This node is not projected as well.</h2>
</projector-cmp>
`,
})
class SimpleComponent {
project = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
let h1 = clientRootNode.querySelector('h1');
let h2 = clientRootNode.querySelector('h2');
let span = clientRootNode.querySelector('span');
expect(h1).not.toBeDefined();
expect(h2).not.toBeDefined();
expect(span.textContent).toBe('no');
// Flip the flag to enable content projection.
compRef.instance.project = true;
compRef.changeDetectorRef.detectChanges();
h1 = clientRootNode.querySelector('h1');
h2 = clientRootNode.querySelector('h2');
span = clientRootNode.querySelector('span');
expect(h1).toBeDefined();
expect(h2).toBeDefined();
expect(span.textContent).toBe('yes');
});
it('should support cases when <ng-content> is used with *ngIf="true"', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
imports: [NgIf],
template: `
Project?: <span>{{ project ? 'yes' : 'no' }}</span>
<ng-content *ngIf="project" />
`,
})
class ProjectorCmp {
@Input() project: boolean = false;
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp [project]="project">
<h1>This node is projected.</h1>
<h2>This node is projected as well.</h2>
</projector-cmp>
`,
})
class SimpleComponent {
project = true;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
let h1 = clientRootNode.querySelector('h1');
let h2 = clientRootNode.querySelector('h2');
let span = clientRootNode.querySelector('span');
expect(h1).toBeDefined();
expect(h2).toBeDefined();
expect(span.textContent).toBe('yes');
// Flip the flag to disable content projection.
compRef.instance.project = false;
compRef.changeDetectorRef.detectChanges();
h1 = clientRootNode.querySelector('h1');
h2 = clientRootNode.querySelector('h2');
span = clientRootNode.querySelector('span');
expect(h1).not.toBeDefined();
expect(h2).not.toBeDefined();
expect(span.textContent).toBe('no');
});
it('should support slots with fallback content', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<div>
Header slot: <ng-content select="header">Header fallback</ng-content>
Main slot: <ng-content select="main"><main>Main fallback</main></ng-content>
Footer slot: <ng-content select="footer">Footer fallback {{expr}}</ng-content>
<ng-content>Wildcard fallback</ng-content>
</div>
`,
})
class ProjectorCmp {
expr = 123;
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `<projector-cmp></projector-cmp>`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
const content = clientRootNode.innerHTML;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(content).toContain('Header slot: Header fallback');
expect(content).toContain('Main slot: <main>Main fallback</main>');
expect(content).toContain('Footer slot: Footer fallback 123');
expect(content).toContain('Wildcard fallback');
});
| {
"end_byte": 217914,
"start_byte": 209902,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_217922_222319 | uld support mixed slots with and without fallback content', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: `
<div>
Header slot: <ng-content select="header">Header fallback</ng-content>
Main slot: <ng-content select="main"><main>Main fallback</main></ng-content>
Footer slot: <ng-content select="footer">Footer fallback {{expr}}</ng-content>
<ng-content>Wildcard fallback</ng-content>
</div>
`,
})
class ProjectorCmp {
expr = 123;
}
@Component({
standalone: true,
imports: [ProjectorCmp],
selector: 'app',
template: `
<projector-cmp>
<header>Header override</header>
<footer>
<h1>Footer override {{expr}}</h1>
</footer>
</projector-cmp>
`,
})
class SimpleComponent {
expr = 321;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, ProjectorCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
const content = clientRootNode.innerHTML;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(content).toContain('Header slot: <!--container--><header>Header override</header>');
expect(content).toContain('Main slot: <main>Main fallback</main>');
expect(content).toContain(
'Footer slot: <!--container--><footer><h1>Footer override 321</h1></footer>',
);
expect(content).toContain('Wildcard fallback');
});
});
describe('unsupported Zone.js config', () => {
it('should log a warning when a noop zone is used', async () => {
@Component({
standalone: true,
selector: 'app',
template: `Hi!`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [{provide: NgZone, useValue: new NoopNgZone()}, withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyHasLog(
appRef,
'NG05000: Angular detected that hydration was enabled for an application ' +
'that uses a custom or a noop Zone.js implementation.',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should log a warning when a custom zone is used', async () => {
@Component({
standalone: true,
selector: 'app',
template: `Hi!`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
class CustomNgZone extends NgZone {}
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [{provide: NgZone, useValue: new CustomNgZone({})}, withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyHasLog(
appRef,
'NG05000: Angular detected that hydration was enabled for an application ' +
'that uses a custom or a noop Zone.js implementation.',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
d | {
"end_byte": 222319,
"start_byte": 217922,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_222325_230860 | e('error handling', () => {
it('should handle text node mismatch', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div id="abc">This is an original content</div>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const div = this.doc.querySelector('div');
div!.innerHTML = '<span title="Hi!">This is an extra span causing a problem!</span>';
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a text node but found <span>',
);
expect(message).toContain('#text(This is an original content) <-- AT THIS LOCATION');
expect(message).toContain('<span title="Hi!">…</span> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should not crash when a node can not be found during hydration', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
Some text.
<div id="abc">This is an original content</div>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
private isServer = isPlatformServer(inject(PLATFORM_ID));
ngAfterViewInit() {
if (this.isServer) {
const div = this.doc.querySelector('div');
div!.remove();
}
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: withNoopErrorHandler(),
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected <div> but the node was not found',
);
expect(message).toContain('<div id="abc">…</div> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should handle element node mismatch', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div id="abc">
<p>This is an original content</p>
<b>Bold text</b>
<i>Italic text</i>
</div>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const b = this.doc.querySelector('b');
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
b?.parentNode?.replaceChild(span, b);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain('During hydration Angular expected <b> but found <span>');
expect(message).toContain('<b>…</b> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should handle <ng-container> node mismatch', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<b>Bold text</b>
<ng-container>
<p>This is an original content</p>
</ng-container>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const p = this.doc.querySelector('p');
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
p?.parentNode?.insertBefore(span, p.nextSibling);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- ng-container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
});
});
it(
'should handle <ng-container> node mismatch ' +
'(when it is wrapped into a non-container node)',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div id="abc" class="wrapper">
<ng-container>
<p>This is an original content</p>
</ng-container>
</div>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const p = this.doc.querySelector('p');
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
p?.parentNode?.insertBefore(span, p.nextSibling);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- ng-container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
});
},
);
it('should handle <ng-template> node mismatch', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule],
template: `
<b *ngIf="true">Bold text</b>
<i *ngIf="false">Italic text</i>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const b = this.doc.querySelector('b');
const firstCommentNode = b!.nextSibling;
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
firstCommentNode?.parentNode?.insertBefore(span, firstCommentNode.nextSibling);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should ha | {
"end_byte": 230860,
"start_byte": 222325,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_230868_239963 | e mismatches in nested components', async () => {
@Component({
standalone: true,
selector: 'nested-cmp',
imports: [CommonModule],
template: `
<b *ngIf="true">Bold text</b>
<i *ngIf="false">Italic text</i>
`,
})
class NestedComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const b = this.doc.querySelector('b');
const firstCommentNode = b!.nextSibling;
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
firstCommentNode?.parentNode?.insertBefore(span, firstCommentNode.nextSibling);
}
}
@Component({
standalone: true,
selector: 'app',
imports: [NestedComponent],
template: `<nested-cmp />`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
expect(message).toContain('check the "NestedComponent" component');
verifyNodeHasMismatchInfo(doc, 'nested-cmp');
});
});
it('should handle sibling count mismatch', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule],
template: `
<ng-container *ngIf="true">
<b>Bold text</b>
<i>Italic text</i>
</ng-container>
<main>Main content</main>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
this.doc.querySelector('b')?.remove();
this.doc.querySelector('i')?.remove();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected more sibling nodes to be present',
);
expect(message).toContain('<main>…</main> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should handle ViewContainerRef node mismatch', async () => {
@Directive({
standalone: true,
selector: 'b',
})
class SimpleDir {
vcr = inject(ViewContainerRef);
}
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule, SimpleDir],
template: `
<b>Bold text</b>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const b = this.doc.querySelector('b');
const firstCommentNode = b!.nextSibling;
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
firstCommentNode?.parentNode?.insertBefore(span, firstCommentNode);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should handle a mismatch for a node that goes after a ViewContainerRef node', async () => {
@Directive({
standalone: true,
selector: 'b',
})
class SimpleDir {
vcr = inject(ViewContainerRef);
}
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule, SimpleDir],
template: `
<b>Bold text</b>
<i>Italic text</i>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterViewInit() {
const b = this.doc.querySelector('b');
const span = this.doc.createElement('span');
span.textContent = 'This is an eeeeevil span causing a problem!';
b?.parentNode?.insertBefore(span, b.nextSibling);
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular expected a comment node but found <span>',
);
expect(message).toContain('<!-- container --> <-- AT THIS LOCATION');
expect(message).toContain('<span>…</span> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc);
});
});
it('should handle a case when a node is not found (removed)', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: '<ng-content />',
})
class ProjectorComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule, ProjectorComponent],
template: `
<projector-cmp>
<b>Bold text</b>
<i>Italic text</i>
</projector-cmp>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
ngAfterContentInit() {
this.doc.querySelector('b')?.remove();
this.doc.querySelector('i')?.remove();
}
}
await ssr(SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During serialization, Angular was unable to find an element in the DOM',
);
expect(message).toContain('<b>…</b> <-- AT THIS LOCATION');
verifyNodeHasMismatchInfo(doc, 'projector-cmp');
});
});
it('should handle a case when a node is not found (detached)', async () => {
@Component({
standalone: true,
selector: 'projector-cmp',
template: '<ng-content />',
})
class ProjectorComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule, ProjectorComponent],
template: `
<projector-cmp>
<b>Bold text</b>
</projector-cmp>
`,
})
class SimpleComponent {
private doc = inject(DOCUMENT);
isServer = isPlatformServer(inject(PLATFORM_ID));
constructor() {
if (!this.isServer) {
this.doc.querySelector('b')?.remove();
}
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withNoopErrorHandler()],
}).catch((err: unknown) => {
const message = (err as Error).message;
expect(message).toContain(
'During hydration Angular was unable to locate a node using the "firstChild" path, ' +
'starting from the <projector-cmp>…</projector-cmp> node',
);
verifyNodeHasMismatchInfo(doc, 'projector-cmp');
});
});
it('should handle a case | {
"end_byte": 239963,
"start_byte": 230868,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_239971_248959 | ode is not found (invalid DOM)', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [CommonModule],
template: `
<a>
<ng-container *ngTemplateOutlet="titleTemplate"></ng-container>
<ng-content *ngIf="true"></ng-content>
</a>
<ng-template #titleTemplate>
<ng-container *ngIf="true">
<a>test</a>
</ng-container>
</ng-template>
`,
})
class SimpleComponent {}
try {
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
fail('Expected the hydration process to throw.');
} catch (e: unknown) {
const message = (e as Error).toString();
expect(message).toContain(
'During hydration, Angular expected an element to be present at this location.',
);
expect(message).toContain('<!-- container --> <-- AT THIS LOCATION');
expect(message).toContain('check to see if your template has valid HTML structure');
verifyNodeHasMismatchInfo(doc);
}
});
it('should log a warning when there was no hydration info in the TransferState', async () => {
@Component({
standalone: true,
selector: 'app',
template: `Hi!`,
})
class SimpleComponent {}
// Note: SSR *without* hydration logic enabled.
const html = await ssr(SimpleComponent, {enableHydration: false});
const ssrContents = getAppContents(html);
expect(ssrContents).not.toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyHasLog(
appRef,
'NG0505: Angular hydration was requested on the client, ' +
'but there was no serialized information present in the server response',
);
const clientRootNode = compRef.location.nativeElement;
// Make sure that no hydration logic was activated,
// effectively re-rendering from scratch happened and
// all the content inside the <app> host element was
// cleared on the client (as it usually happens in client
// rendering mode).
verifyNoNodesWereClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should not log a warning when there was no hydration info in the TransferState, ' +
'but a client mode marker is present',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `Hi!`,
})
class SimpleComponent {}
const html = `<html><head></head><body ${CLIENT_RENDER_MODE_FLAG}><app></app></body></html>`;
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [withDebugConsole()],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
verifyEmptyConsole(appRef);
const clientRootNode = compRef.location.nativeElement;
expect(clientRootNode.textContent).toContain('Hi!');
},
);
});
describe('@if', () => {
it('should work with `if`s that have different value on the client and on the server', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@if (isServer) { <b>This is a SERVER-ONLY content</b> }
@if (!isServer) { <i>This is a CLIENT-ONLY content</i> }
@if (alwaysTrue) { <p>CLIENT and SERVER content</p> }
`,
})
class SimpleComponent {
alwaysTrue = true;
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('<i>This is a CLIENT-ONLY content</i>');
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content</b>');
// Content that should be rendered on both client and server should also be present.
expect(ssrContents).toContain('<p>CLIENT and SERVER content</p>');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content</i>');
expect(clientContents).not.toContain('<b>This is a SERVER-ONLY content</b>');
// Content that should be rendered on both client and server should still be present.
expect(clientContents).toContain('<p>CLIENT and SERVER content</p>');
const clientOnlyNode = clientRootNode.querySelector('i');
verifyAllNodesClaimedForHydration(clientRootNode, [clientOnlyNode]);
});
it('should support nested `if`s', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
This is a non-empty block:
@if (true) {
@if (true) {
<h1>
@if (true) {
<span>Hello world!</span>
}
</h1>
}
}
<div>Post-container element</div>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate `else` blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@if (conditionA) {
if block
} @else {
else block
}
`,
})
class SimpleComponent {
conditionA = false;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
expect(ssrContents).toContain(`else block`);
expect(ssrContents).not.toContain(`if block`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
// Verify that we still have expected content rendered.
expect(clientRootNode.innerHTML).toContain(`else block`);
expect(clientRootNode.innerHTML).not.toContain(`if block`);
// Verify that switching `if` condition results
// in an update to the DOM which was previously hydrated.
compRef.instance.conditionA = true;
compRef.changeDetectorRef.detectChanges();
expect(clientRootNode.innerHTML).not.toContain(`else block`);
expect(clientRootNode.innerHTML).toContain(`if block`);
});
});
describe('@switch', () => { | {
"end_byte": 248959,
"start_byte": 239971,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_248965_252739 | it('should work with `switch`es that have different value on the client and on the server', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@switch (isServer) {
@case (true) { <b>This is a SERVER-ONLY content</b> }
@case (false) { <i>This is a CLIENT-ONLY content</i> }
}
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
// In the SSR output we expect to see SERVER content, but not CLIENT.
expect(ssrContents).not.toContain('<i>This is a CLIENT-ONLY content</i>');
expect(ssrContents).toContain('<b>This is a SERVER-ONLY content</b>');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect to see CLIENT content, but not SERVER.
expect(clientContents).toContain('<i>This is a CLIENT-ONLY content</i>');
expect(clientContents).not.toContain('<b>This is a SERVER-ONLY content</b>');
const clientOnlyNode = clientRootNode.querySelector('i');
verifyAllNodesClaimedForHydration(clientRootNode, [clientOnlyNode]);
});
it('should cleanup rendered case if none of the cases match on the client', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@switch (label) {
@case ('A') { This is A }
@case ('B') { This is B }
}
`,
})
class SimpleComponent {
// This flag is intentionally different between the client
// and the server: we use it to test the logic to cleanup
// dehydrated views.
label = isPlatformServer(inject(PLATFORM_ID)) ? 'A' : 'Not A';
}
const html = await ssr(SimpleComponent);
let ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
ssrContents = stripExcessiveSpaces(stripUtilAttributes(ssrContents, false));
expect(ssrContents).toContain('This is A');
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
const clientContents = stripExcessiveSpaces(
stripUtilAttributes(clientRootNode.outerHTML, false),
);
// After the cleanup, we expect that the contents is removed and none
// of the cases are rendered, since they don't match the condition.
expect(clientContents).not.toContain('This is A');
expect(clientContents).not.toContain('This is B');
verifyAllNodesClaimedForHydration(clientRootNode);
});
});
describe('@for', () => {
| {
"end_byte": 252739,
"start_byte": 248965,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_252745_261202 | ('should hydrate for loop content', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@for (item of items; track item) {
<div>
<h1>Item #{{ item }}</h1>
</div>
}
`,
})
class SimpleComponent {
items = [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Check whether serialized hydration info has a multiplier
// (which avoids repeated views serialization).
const hydrationInfo = getHydrationInfoFromTransferState(ssrContents);
expect(hydrationInfo).toContain('"x":3');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate @empty block content', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@for (item of items; track item) {
<p>Item #{{ item }}</p>
} @empty {
<div>This is an "empty" block</div>
}
`,
})
class SimpleComponent {
items = [];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it(
'should handle a case when @empty block is rendered ' +
'on the server and main content on the client',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@for (item of items; track item) {
<p>Item #{{ item }}</p>
} @empty {
<div>This is an "empty" block</div>
}
`,
})
class SimpleComponent {
items = isPlatformServer(inject(PLATFORM_ID)) ? [] : [1, 2, 3];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
// Expect only the `@empty` block to be rendered on the server.
expect(ssrContents).not.toContain('Item #1');
expect(ssrContents).not.toContain('Item #2');
expect(ssrContents).not.toContain('Item #3');
expect(ssrContents).toContain('This is an "empty" block');
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// After hydration and post-hydration cleanup,
// expect items to be present, but `@empty` block to be removed.
expect(clientRootNode.innerHTML).toContain('Item #1');
expect(clientRootNode.innerHTML).toContain('Item #2');
expect(clientRootNode.innerHTML).toContain('Item #3');
expect(clientRootNode.innerHTML).not.toContain('This is an "empty" block');
const clientRenderedItems = compRef.location.nativeElement.querySelectorAll('p');
verifyAllNodesClaimedForHydration(clientRootNode, Array.from(clientRenderedItems));
},
);
it(
'should handle a case when @empty block is rendered ' +
'on the client and main content on the server',
async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@for (item of items; track item) {
<p>Item #{{ item }}</p>
} @empty {
<div>This is an "empty" block</div>
}
`,
})
class SimpleComponent {
items = isPlatformServer(inject(PLATFORM_ID)) ? [1, 2, 3] : [];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
// Expect items to be rendered on the server.
expect(ssrContents).toContain('Item #1');
expect(ssrContents).toContain('Item #2');
expect(ssrContents).toContain('Item #3');
expect(ssrContents).not.toContain('This is an "empty" block');
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// After hydration and post-hydration cleanup,
// expect an `@empty` block to be present and items to be removed.
expect(clientRootNode.innerHTML).not.toContain('Item #1');
expect(clientRootNode.innerHTML).not.toContain('Item #2');
expect(clientRootNode.innerHTML).not.toContain('Item #3');
expect(clientRootNode.innerHTML).toContain('This is an "empty" block');
const clientRenderedItems = compRef.location.nativeElement.querySelectorAll('div');
verifyAllNodesClaimedForHydration(clientRootNode, Array.from(clientRenderedItems));
},
);
it('should handle different number of items rendered on the client and on the server', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@for (item of items; track item) {
<p id="{{ item }}">Item #{{ item }}</p>
}
`,
})
class SimpleComponent {
// Item '3' is the same, the rest of the items are different.
items = isPlatformServer(inject(PLATFORM_ID)) ? [3, 2, 1] : [3, 4, 5];
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
expect(ssrContents).toContain('Item #1');
expect(ssrContents).toContain('Item #2');
expect(ssrContents).toContain('Item #3');
expect(ssrContents).not.toContain('Item #4');
expect(ssrContents).not.toContain('Item #5');
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// After hydration and post-hydration cleanup,
// expect items to be present, but `@empty` block to be removed.
expect(clientRootNode.innerHTML).not.toContain('Item #1');
expect(clientRootNode.innerHTML).not.toContain('Item #2');
expect(clientRootNode.innerHTML).toContain('Item #3');
expect(clientRootNode.innerHTML).toContain('Item #4');
expect(clientRootNode.innerHTML).toContain('Item #5');
// Note: we exclude item '3', since it's the same (and at the same location)
// on the server and on the client, so it was hydrated.
const clientRenderedItems = [4, 5].map((id) =>
compRef.location.nativeElement.querySelector(`[id=${id}]`),
);
verifyAllNodesClaimedForHydration(clientRootNode, Array.from(clientRenderedItems));
});
it('should handle a recon | {
"end_byte": 261202,
"start_byte": 252745,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_261210_262674 | n with swaps', async () => {
@Component({
selector: 'app',
standalone: true,
template: `
@for(item of items; track item) {
<div>{{ item }}</div>
}
`,
})
class SimpleComponent {
items = ['a', 'b', 'c'];
swap() {
// Reshuffling of the array will result in
// "swap" operations in repeater.
this.items = ['b', 'c', 'a'];
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
expect(ssrContents).toContain('a');
expect(ssrContents).toContain('b');
expect(ssrContents).toContain('c');
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const root: HTMLElement = compRef.location.nativeElement;
const divs = root.querySelectorAll('div');
expect(divs.length).toBe(3);
compRef.instance.swap();
compRef.changeDetectorRef.detectChanges();
const divsAfterSwap = root.querySelectorAll('div');
expect(divsAfterSwap.length).toBe(3);
});
});
describe('@let', () => {
| {
"end_byte": 262674,
"start_byte": 261210,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_262680_270959 | ('should handle a let declaration', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@let greeting = name + '!!!';
Hello, {{greeting}}
`,
})
class SimpleComponent {
name = 'Frodo';
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('Hello, Frodo!!!');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('Hello, Frodo!!!');
compRef.instance.name = 'Bilbo';
compRef.changeDetectorRef.detectChanges();
expect(clientRootNode.textContent).toContain('Hello, Bilbo!!!');
});
it('should handle multiple let declarations that depend on each other', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@let plusOne = value + 1;
@let plusTwo = plusOne + 1;
@let result = plusTwo + 1;
Result: {{result}}
`,
})
class SimpleComponent {
value = 1;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('Result: 4');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('Result: 4');
compRef.instance.value = 2;
compRef.changeDetectorRef.detectChanges();
expect(clientRootNode.textContent).toContain('Result: 5');
});
it('should handle a let declaration using a pipe that injects ChangeDetectorRef', async () => {
@Pipe({
name: 'double',
standalone: true,
})
class DoublePipe implements PipeTransform {
changeDetectorRef = inject(ChangeDetectorRef);
transform(value: number) {
return value * 2;
}
}
@Component({
standalone: true,
selector: 'app',
imports: [DoublePipe],
template: `
@let result = value | double;
Result: {{result}}
`,
})
class SimpleComponent {
value = 1;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('Result: 2');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('Result: 2');
compRef.instance.value = 2;
compRef.changeDetectorRef.detectChanges();
expect(clientRootNode.textContent).toContain('Result: 4');
});
it('should handle let declarations referenced through multiple levels of views', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@if (true) {
@if (true) {
@let three = two + 1;
The result is {{three}}
}
@let two = one + 1;
}
@let one = value + 1;
`,
})
class SimpleComponent {
value = 0;
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('The result is 3');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('The result is 3');
compRef.instance.value = 2;
compRef.changeDetectorRef.detectChanges();
expect(clientRootNode.textContent).toContain('The result is 5');
});
it('should handle non-projected let declarations', async () => {
@Component({
selector: 'inner',
template: `
<ng-content select="header">Fallback header</ng-content>
<ng-content>Fallback content</ng-content>
<ng-content select="footer">Fallback footer</ng-content>
`,
standalone: true,
})
class InnerComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<inner>
@let one = 1;
<footer>|Footer value {{one}}</footer>
@let two = one + 1;
<header>Header value {{two}}|</header>
</inner>
`,
imports: [InnerComponent],
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
const expectedContent =
'<!--container--><header>Header value 2|</header>' +
'Fallback content<!--container--><!--container-->' +
'<footer>|Footer value 1</footer>';
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain(`<inner ngh="0">${expectedContent}</inner>`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.innerHTML).toContain(`<inner>${expectedContent}</inner>`);
});
it('should handle let declaration before and directly inside of an embedded view', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@let before = 'before';
@if (true) {
@let inside = 'inside';
{{before}}|{{inside}}
}
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('before|inside');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('before|inside');
});
it('should handle let dec | {
"end_byte": 270959,
"start_byte": 262680,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/full_app_hydration_spec.ts_270967_278696 | before, directly inside of and after an embedded view', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@let before = 'before';
@if (true) {
@let inside = 'inside';
{{inside}}
}
@let after = 'after';
{{before}}|{{after}}
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('inside <!--container--> before|after');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('inside before|after');
});
it('should handle let declaration with array inside of an embedded view', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
@let foo = ['foo'];
@if (true) {
{{foo}}
}
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
expect(ssrContents).toContain('foo');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
expect(clientRootNode.textContent).toContain('foo');
});
});
describe('zoneless', () => {
it('should not produce "unsupported configuration" warnings for zoneless mode', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<header>Header</header>
<footer>Footer</footer>
`,
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [
withDebugConsole(),
provideExperimentalZonelessChangeDetection() as unknown as Provider[],
],
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Make sure there are no extra logs in case zoneless mode is enabled.
verifyHasNoLog(
appRef,
'NG05000: Angular detected that hydration was enabled for an application ' +
'that uses a custom or a noop Zone.js implementation.',
);
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
});
describe('Router', () => {
it('should wait for lazy routes before triggering post-hydration cleanup', async () => {
const ngZone = TestBed.inject(NgZone);
@Component({
standalone: true,
selector: 'lazy',
template: `LazyCmp content`,
})
class LazyCmp {}
const routes: Routes = [
{
path: '',
loadComponent: () => {
return ngZone.runOutsideAngular(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(LazyCmp), 100);
});
});
},
},
];
@Component({
standalone: true,
selector: 'app',
imports: [RouterOutlet],
template: `
Works!
<router-outlet />
`,
})
class SimpleComponent {}
const envProviders = [
{provide: PlatformLocation, useClass: MockPlatformLocation},
provideRouter(routes),
] as unknown as Provider[];
const html = await ssr(SimpleComponent, {envProviders});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
// Expect serialization to happen once a lazy-loaded route completes loading
// and a lazy component is rendered.
expect(ssrContents).toContain(`<lazy ${NGH_ATTR_NAME}="0">LazyCmp content</lazy>`);
resetTViewsFor(SimpleComponent, LazyCmp);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
await whenStable(appRef);
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should cleanup dehydrated views in routed components that use ViewContainerRef', async () => {
@Component({
standalone: true,
selector: 'cmp-a',
template: `
@if (isServer) {
<p>Server view</p>
} @else {
<p>Client view</p>
}
`,
})
class CmpA {
isServer = isPlatformServer(inject(PLATFORM_ID));
viewContainerRef = inject(ViewContainerRef);
}
const routes: Routes = [
{
path: '',
component: CmpA,
},
];
@Component({
standalone: true,
selector: 'app',
imports: [RouterOutlet],
template: `
<router-outlet />
`,
})
class SimpleComponent {}
const envProviders = [
{provide: PlatformLocation, useClass: MockPlatformLocation},
provideRouter(routes),
] as unknown as Provider[];
const html = await ssr(SimpleComponent, {envProviders});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain(`<app ${NGH_ATTR_NAME}`);
expect(ssrContents).toContain('Server view');
expect(ssrContents).not.toContain('Client view');
resetTViewsFor(SimpleComponent, CmpA);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const clientRootNode = compRef.location.nativeElement;
// <p> tag is used in a view that is different on a server and
// on a client, so it gets re-created (not hydrated) on a client
const p = clientRootNode.querySelector('p');
verifyAllNodesClaimedForHydration(clientRootNode, [p]);
expect(clientRootNode.innerHTML).not.toContain('Server view');
expect(clientRootNode.innerHTML).toContain('Client view');
});
});
});
});
| {
"end_byte": 278696,
"start_byte": 270967,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/full_app_hydration_spec.ts"
} |
angular/packages/platform-server/test/event_replay_spec.ts_0_7428 | /**
* @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 {
Component,
destroyPlatform,
ErrorHandler,
getPlatform,
PLATFORM_ID,
Type,
} from '@angular/core';
import {
withEventReplay,
bootstrapApplication,
provideClientHydration,
} from '@angular/platform-browser';
import {provideServerRendering} from '../public_api';
import {EVENT_DISPATCH_SCRIPT_ID, renderApplication} from '../src/utils';
import {EventPhase} from '@angular/core/primitives/event-dispatch';
import {
getAppContents,
hydrate,
prepareEnvironment,
prepareEnvironmentAndHydrate,
resetTViewsFor,
} from './dom_utils';
import {getDocument} from '@angular/core/src/render3/interfaces/document';
/**
* Represents the <script> tag added by the build process to inject
* event dispatch (JSAction) logic.
*/
const EVENT_DISPATCH_SCRIPT = `<script type="text/javascript" id="${EVENT_DISPATCH_SCRIPT_ID}"></script>`;
const DEFAULT_DOCUMENT = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
/** Checks whether event dispatch script is present in the generated HTML */
function hasEventDispatchScript(content: string) {
return content.includes(EVENT_DISPATCH_SCRIPT_ID);
}
/** Checks whether there are any `jsaction` attributes present in the generated HTML */
function hasJSActionAttrs(content: string) {
return content.includes('jsaction="');
}
/**
* Enables strict error handler that fails a test
* if there was an error reported to the ErrorHandler.
*/
function withStrictErrorHandler() {
class StrictErrorHandler extends ErrorHandler {
override handleError(error: any): void {
fail(error);
}
}
return [
{
provide: ErrorHandler,
useClass: StrictErrorHandler,
},
];
}
describe('event replay', () => {
const originalDocument = globalThis.document;
const originalWindow = globalThis.window;
beforeAll(async () => {
globalThis.window = globalThis as unknown as Window & typeof globalThis;
await import('@angular/core/primitives/event-dispatch/contract_bundle_min.js' as string);
});
beforeEach(() => {
if (getPlatform()) destroyPlatform();
});
afterAll(() => {
globalThis.window = originalWindow;
globalThis.document = originalDocument;
destroyPlatform();
});
afterEach(() => {
window._ejsas = {};
});
/**
* This renders the application with server side rendering logic.
*
* @param component the test component to be rendered
* @param doc the document
* @param envProviders the environment providers
* @returns a promise containing the server rendered app as a string
*/
async function ssr(
component: Type<unknown>,
options: {doc?: string; enableEventReplay?: boolean; hydrationDisabled?: boolean} = {},
): Promise<string> {
const {enableEventReplay = true, hydrationDisabled, doc = DEFAULT_DOCUMENT} = options;
const hydrationProviders = hydrationDisabled
? []
: enableEventReplay
? provideClientHydration(withEventReplay())
: provideClientHydration();
const bootstrap = () =>
bootstrapApplication(component, {
providers: [provideServerRendering(), hydrationProviders],
});
return renderApplication(bootstrap, {
document: doc,
});
}
it('should work for elements with local refs', async () => {
const onClickSpy = jasmine.createSpy();
@Component({
selector: 'app',
standalone: true,
template: `
<button id="btn" (click)="onClick()" #localRef></button>
`,
})
class AppComponent {
onClick = onClickSpy;
}
const html = await ssr(AppComponent);
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
resetTViewsFor(AppComponent);
const btn = doc.getElementById('btn')!;
btn.click();
const appRef = await hydrate(doc, AppComponent, {
hydrationFeatures: [withEventReplay()],
});
appRef.tick();
expect(onClickSpy).toHaveBeenCalled();
});
it('should route to the appropriate component with content projection', async () => {
const outerOnClickSpy = jasmine.createSpy();
const innerOnClickSpy = jasmine.createSpy();
@Component({
selector: 'app-card',
standalone: true,
template: `
<div class="card">
<button id="inner-button" (click)="onClick()"></button>
<ng-content></ng-content>
</div>
`,
})
class CardComponent {
onClick = innerOnClickSpy;
}
@Component({
selector: 'app',
imports: [CardComponent],
standalone: true,
template: `
<app-card>
<h2>Card Title</h2>
<p>This is some card content.</p>
<button id="outer-button" (click)="onClick()">Click Me</button>
</app-card>
`,
})
class AppComponent {
onClick = outerOnClickSpy;
}
const html = await ssr(AppComponent);
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
resetTViewsFor(AppComponent);
const outer = doc.getElementById('outer-button')!;
const inner = doc.getElementById('inner-button')!;
outer.click();
inner.click();
const appRef = await hydrate(doc, AppComponent, {
envProviders: [{provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures: [withEventReplay()],
});
expect(outerOnClickSpy).toHaveBeenCalledBefore(innerOnClickSpy);
});
it('should remove jsaction attributes, but continue listening to events.', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div (click)="onClick()" id="1">
<div (click)="onClick()" id="2"></div>
</div>
`,
})
class SimpleComponent {
onClick() {}
}
const docContents = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
const html = await ssr(SimpleComponent, {doc: docContents});
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
const el = doc.getElementById('1')!;
expect(el.hasAttribute('jsaction')).toBeTrue();
expect((el.firstChild as Element).hasAttribute('jsaction')).toBeTrue();
resetTViewsFor(SimpleComponent);
const appRef = await hydrate(doc, SimpleComponent, {
hydrationFeatures: [withEventReplay()],
});
expect(el.hasAttribute('jsaction')).toBeFalse();
expect((el.firstChild as Element).hasAttribute('jsaction')).toBeFalse();
});
it(`should add 'nonce' attribute to event record script when 'ngCspNonce' is provided`, async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div (click)="onClick()">
<div (blur)="onClick()"></div>
</div>
`,
})
class SimpleComponent {
onClick() {}
}
const doc =
`<html><head></head><body>${EVENT_DISPATCH_SCRIPT}` +
`<app ngCspNonce="{{nonce}}"></app></body></html>`;
const html = await ssr(SimpleComponent, {doc});
expect(getAppContents(html)).toContain('<script nonce="{{nonce}}">window.__jsaction_bootstrap');
}); | {
"end_byte": 7428,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/event_replay_spec.ts"
} |
angular/packages/platform-server/test/event_replay_spec.ts_7432_15211 | describe('bubbling behavior', () => {
it('should propagate events', async () => {
const onClickSpy = jasmine.createSpy();
@Component({
standalone: true,
selector: 'app',
template: `
<div id="top" (click)="onClick()">
<div id="bottom" (click)="onClick()"></div>
</div>
`,
})
class SimpleComponent {
onClick = onClickSpy;
}
const docContents = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
const html = await ssr(SimpleComponent, {doc: docContents});
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
resetTViewsFor(SimpleComponent);
const bottomEl = doc.getElementById('bottom')!;
bottomEl.click();
const appRef = await hydrate(doc, SimpleComponent, {
envProviders: [{provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures: [withEventReplay()],
});
expect(onClickSpy).toHaveBeenCalledTimes(2);
onClickSpy.calls.reset();
bottomEl.click();
expect(onClickSpy).toHaveBeenCalledTimes(2);
});
it('should not propagate events if stopPropagation is called', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<div id="top" (click)="onClick($event)">
<div id="bottom" (click)="onClick($event)"></div>
</div>
`,
})
class SimpleComponent {
onClick(e: Event) {
e.stopPropagation();
}
}
const onClickSpy = spyOn(SimpleComponent.prototype, 'onClick').and.callThrough();
const docContents = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
const html = await ssr(SimpleComponent, {doc: docContents});
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
resetTViewsFor(SimpleComponent);
const bottomEl = doc.getElementById('bottom')!;
bottomEl.click();
const appRef = await hydrate(doc, SimpleComponent, {
hydrationFeatures: [withEventReplay()],
});
expect(onClickSpy).toHaveBeenCalledTimes(1);
onClickSpy.calls.reset();
bottomEl.click();
expect(onClickSpy).toHaveBeenCalledTimes(1);
});
it('should not have differences in event fields', async () => {
let currentEvent!: Event;
let latestTarget: EventTarget | null = null;
let latestCurrentTarget: EventTarget | null = null;
@Component({
standalone: true,
selector: 'app',
template: `
<div id="top" (click)="onClick($event)">
<div id="bottom" (click)="onClick($event)"></div>
</div>
`,
})
class SimpleComponent {
onClick(event: Event) {
currentEvent = event;
latestTarget = event.target;
latestCurrentTarget = event.currentTarget;
}
}
const docContents = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
const html = await ssr(SimpleComponent, {doc: docContents});
const ssrContents = getAppContents(html);
const doc = getDocument();
prepareEnvironment(doc, ssrContents);
resetTViewsFor(SimpleComponent);
const bottomEl = doc.getElementById('bottom')!;
bottomEl.click();
await hydrate(doc, SimpleComponent, {
envProviders: [{provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures: [withEventReplay()],
});
const replayedEvent = currentEvent;
expect(replayedEvent.target).not.toBeNull();
expect(replayedEvent.currentTarget).not.toBeNull();
expect(replayedEvent.eventPhase).toBe(EventPhase.REPLAY);
bottomEl.click();
const normalEvent = currentEvent;
expect(replayedEvent.target).toBe(latestTarget);
expect(replayedEvent.currentTarget).toBe(latestCurrentTarget);
});
});
describe('event dispatch script', () => {
it('should not be present on a page when hydration is disabled', async () => {
@Component({
standalone: true,
selector: 'app',
template: '<input (click)="onClick()" />',
})
class SimpleComponent {
onClick() {}
}
const doc = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
const html = await ssr(SimpleComponent, {doc, hydrationDisabled: true});
const ssrContents = getAppContents(html);
expect(hasJSActionAttrs(ssrContents)).toBeFalse();
expect(hasEventDispatchScript(ssrContents)).toBeFalse();
});
it('should not be present on a page if there are no events to replay', async () => {
@Component({
standalone: true,
selector: 'app',
template: 'Some text',
})
class SimpleComponent {}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(hasJSActionAttrs(ssrContents)).toBeFalse();
expect(hasEventDispatchScript(ssrContents)).toBeFalse();
resetTViewsFor(SimpleComponent);
const doc = getDocument();
await prepareEnvironmentAndHydrate(doc, ssrContents, SimpleComponent, {
envProviders: [
{provide: PLATFORM_ID, useValue: 'browser'},
// This ensures that there are no errors while bootstrapping an application
// that has no events, but enables Event Replay feature.
withStrictErrorHandler(),
],
hydrationFeatures: [withEventReplay()],
});
});
it('should not replay mouse events', async () => {
@Component({
standalone: true,
selector: 'app',
template: '<div (mouseenter)="doThing()"><div>',
})
class SimpleComponent {
doThing() {}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(hasJSActionAttrs(ssrContents)).toBeFalse();
expect(hasEventDispatchScript(ssrContents)).toBeFalse();
});
it('should not be present on a page where event replay is not enabled', async () => {
@Component({
standalone: true,
selector: 'app',
template: '<input (click)="onClick()" />',
})
class SimpleComponent {
onClick() {}
}
const html = await ssr(SimpleComponent, {enableEventReplay: false});
const ssrContents = getAppContents(html);
// Expect that there are no JSAction artifacts in the HTML
// (even though there are events in a template), since event
// replay is disabled in the config.
expect(hasJSActionAttrs(ssrContents)).toBeFalse();
expect(hasEventDispatchScript(ssrContents)).toBeFalse();
});
it('should be retained if there are events to replay', async () => {
@Component({
standalone: true,
selector: 'app',
template: '<input (click)="onClick()" />',
})
class SimpleComponent {
onClick() {}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(hasJSActionAttrs(ssrContents)).toBeTrue();
expect(hasEventDispatchScript(ssrContents)).toBeTrue();
// Verify that inlined event delegation script goes first and
// event contract setup goes second (since it uses some code from
// the inlined script).
expect(ssrContents).toContain(
`<script type="text/javascript" id="ng-event-dispatch-contract"></script>` +
`<script>window.__jsaction_bootstrap(document.body,"ng",["click"],[]);</script>`,
);
});
});
}); | {
"end_byte": 15211,
"start_byte": 7432,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/event_replay_spec.ts"
} |
angular/packages/platform-server/test/dom_utils.ts_0_5583 | /**
* @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 {DOCUMENT} from '@angular/common';
import {ApplicationRef, PLATFORM_ID, Provider, Type, ɵsetDocument} from '@angular/core';
import {CLIENT_RENDER_MODE_FLAG} from '@angular/core/src/hydration/api';
import {getComponentDef} from '@angular/core/src/render3/def_getters';
import {
bootstrapApplication,
HydrationFeature,
HydrationFeatureKind,
provideClientHydration,
} from '@angular/platform-browser';
/**
* The name of the attribute that contains a slot index
* inside the TransferState storage where hydration info
* could be found.
*/
const NGH_ATTR_NAME = 'ngh';
const EMPTY_TEXT_NODE_COMMENT = 'ngetn';
const TEXT_NODE_SEPARATOR_COMMENT = 'ngtns';
const NGH_ATTR_REGEXP = new RegExp(` ${NGH_ATTR_NAME}=".*?"`, 'g');
const EMPTY_TEXT_NODE_REGEXP = new RegExp(`<!--${EMPTY_TEXT_NODE_COMMENT}-->`, 'g');
const TEXT_NODE_SEPARATOR_REGEXP = new RegExp(`<!--${TEXT_NODE_SEPARATOR_COMMENT}-->`, 'g');
/**
* Drop utility attributes such as `ng-version`, `ng-server-context` and `ngh`,
* so that it's easier to make assertions in tests.
*/
export function stripUtilAttributes(html: string, keepNgh: boolean): string {
html = html
.replace(/ ng-version=".*?"/g, '')
.replace(/ ng-server-context=".*?"/g, '')
.replace(/ ng-reflect-(.*?)=".*?"/g, '')
.replace(/ _nghost(.*?)=""/g, '')
.replace(/ _ngcontent(.*?)=""/g, '');
if (!keepNgh) {
html = html
.replace(NGH_ATTR_REGEXP, '')
.replace(EMPTY_TEXT_NODE_REGEXP, '')
.replace(TEXT_NODE_SEPARATOR_REGEXP, '');
}
return html;
}
/**
* Extracts a portion of HTML located inside of the `<body>` element.
* This content belongs to the application view (and supporting TransferState
* scripts) rendered on the server.
*/
export function getAppContents(html: string): string {
const result = stripUtilAttributes(html, true).match(/<body>(.*?)<\/body>/s);
return result ? result[1] : html;
}
/**
* Converts a static HTML to a DOM structure.
*
* @param html the rendered html in test
* @param doc the document object
* @returns a div element containing a copy of the app contents
*/
function convertHtmlToDom(html: string, doc: Document): HTMLElement {
const contents = getAppContents(html);
const container = doc.createElement('div');
container.innerHTML = contents;
return container;
}
/**
* Reset TView, so that we re-enter the first create pass as
* we would normally do when we hydrate on the client. Otherwise,
* hydration info would not be applied to T data structures.
*/
export function resetTViewsFor(...types: Type<unknown>[]) {
for (const type of types) {
getComponentDef(type)!.tView = null;
}
}
export function hydrate(
doc: Document,
component: Type<unknown>,
options?: {
envProviders?: Provider[];
hydrationFeatures?: HydrationFeature<HydrationFeatureKind>[];
},
) {
function _document(): any {
ɵsetDocument(doc);
global.document = doc; // needed for `DefaultDomRenderer2`
return doc;
}
const envProviders = options?.envProviders ?? [];
const hydrationFeatures = options?.hydrationFeatures ?? [];
const providers = [
...envProviders,
{provide: PLATFORM_ID, useValue: 'browser'},
{provide: DOCUMENT, useFactory: _document, deps: []},
provideClientHydration(...hydrationFeatures),
];
return bootstrapApplication(component, {providers});
}
export function insertDomInDocument(doc: Document, html: string) {
// Get HTML contents of the `<app>`, create a DOM element and append it into the body.
const container = convertHtmlToDom(html, doc);
// If there was a client render mode marker present in HTML - apply it to the <body>
// element as well.
const hasClientModeMarker = new RegExp(` ${CLIENT_RENDER_MODE_FLAG}`, 'g').test(html);
if (hasClientModeMarker) {
doc.body.setAttribute(CLIENT_RENDER_MODE_FLAG, '');
}
Array.from(container.childNodes).forEach((node) => doc.body.appendChild(node));
}
/**
* This prepares the environment before hydration begins.
*
* @param doc the document object
* @param html the server side rendered DOM string to be hydrated
* @returns a promise with the application ref
*/
export function prepareEnvironment(doc: Document, html: string) {
insertDomInDocument(doc, html);
globalThis.document = doc;
const scripts = doc.getElementsByTagName('script');
for (const script of Array.from(scripts)) {
if (script?.textContent?.startsWith('window.__jsaction_bootstrap')) {
eval(script.textContent);
}
}
}
/**
* This bootstraps an application with existing html and enables hydration support
* causing hydration to be invoked.
*
* @param html the server side rendered DOM string to be hydrated
* @param component the root component
* @param envProviders the environment providers
* @returns a promise with the application ref
*/
export async function prepareEnvironmentAndHydrate(
doc: Document,
html: string,
component: Type<unknown>,
options?: {
envProviders?: Provider[];
hydrationFeatures?: HydrationFeature<HydrationFeatureKind>[];
},
): Promise<ApplicationRef> {
prepareEnvironment(doc, html);
return hydrate(doc, component, options);
}
/**
* Clears document contents to have a clean state for the next test.
*/
export function clearDocument(doc: Document) {
doc.body.textContent = '';
doc.body.removeAttribute(CLIENT_RENDER_MODE_FLAG);
}
| {
"end_byte": 5583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/dom_utils.ts"
} |
angular/packages/platform-server/test/hydration_utils.ts_0_8647 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
ApplicationRef,
ComponentRef,
ErrorHandler,
Injectable,
Provider,
Type,
} from '@angular/core';
import {Console} from '@angular/core/src/console';
import {
HydrationStatus,
readHydrationInfo,
SSR_CONTENT_INTEGRITY_MARKER,
} from '@angular/core/src/hydration/utils';
import {
bootstrapApplication,
HydrationFeature,
provideClientHydration,
} from '@angular/platform-browser';
import {HydrationFeatureKind} from '@angular/platform-browser/src/hydration';
import {provideServerRendering} from '../public_api';
import {EVENT_DISPATCH_SCRIPT_ID, renderApplication} from '../src/utils';
import {getAppContents, stripUtilAttributes} from './dom_utils';
/**
* The name of the attribute that contains a slot index
* inside the TransferState storage where hydration info
* could be found.
*/
export const NGH_ATTR_NAME = 'ngh';
export const EMPTY_TEXT_NODE_COMMENT = 'ngetn';
export const TEXT_NODE_SEPARATOR_COMMENT = 'ngtns';
export const SKIP_HYDRATION_ATTR_NAME = 'ngSkipHydration';
export const SKIP_HYDRATION_ATTR_NAME_LOWER_CASE = SKIP_HYDRATION_ATTR_NAME.toLowerCase();
export const TRANSFER_STATE_TOKEN_ID = '__nghData__';
/**
* Represents the <script> tag added by the build process to inject
* event dispatch (JSAction) logic.
*/
export const EVENT_DISPATCH_SCRIPT = `<script type="text/javascript" id="${EVENT_DISPATCH_SCRIPT_ID}"></script>`;
export const DEFAULT_DOCUMENT = `<html><head></head><body>${EVENT_DISPATCH_SCRIPT}<app></app></body></html>`;
export function getComponentRef<T>(appRef: ApplicationRef): ComponentRef<T> {
return appRef.components[0];
}
export function stripSsrIntegrityMarker(input: string): string {
return input.replace(`<!--${SSR_CONTENT_INTEGRITY_MARKER}-->`, '');
}
export function stripTransferDataScript(input: string): string {
return input.replace(/<script (.*?)<\/script>/s, '');
}
export function stripExcessiveSpaces(html: string): string {
return html.replace(/\s+/g, ' ');
}
export function verifyClientAndSSRContentsMatch(
ssrContents: string,
clientAppRootElement: HTMLElement,
) {
const clientContents = stripSsrIntegrityMarker(
stripTransferDataScript(stripUtilAttributes(clientAppRootElement.outerHTML, false)),
);
ssrContents = stripSsrIntegrityMarker(
stripTransferDataScript(stripUtilAttributes(ssrContents, false)),
);
expect(getAppContents(clientContents)).toBe(ssrContents, 'Client and server contents mismatch');
}
export function verifyNodeHasMismatchInfo(doc: Document, selector = 'app'): void {
expect(readHydrationInfo(doc.querySelector(selector)!)?.status).toBe(HydrationStatus.Mismatched);
}
/** Checks whether a given element is a <script> that contains transfer state data. */
export function isTransferStateScript(el: HTMLElement): boolean {
return (
el.nodeType === Node.ELEMENT_NODE &&
el.tagName.toLowerCase() === 'script' &&
el.getAttribute('id') === 'ng-state'
);
}
export function isSsrContentsIntegrityMarker(el: Node): boolean {
return (
el.nodeType === Node.COMMENT_NODE && el.textContent?.trim() === SSR_CONTENT_INTEGRITY_MARKER
);
}
/**
* Walks over DOM nodes starting from a given node and checks
* whether all nodes were claimed for hydration, i.e. annotated
* with a special monkey-patched flag (which is added in dev mode
* only). It skips any nodes with the skip hydration attribute.
*/
export function verifyAllNodesClaimedForHydration(el: HTMLElement, exceptions: HTMLElement[] = []) {
if (
(el.nodeType === Node.ELEMENT_NODE && el.hasAttribute(SKIP_HYDRATION_ATTR_NAME_LOWER_CASE)) ||
exceptions.includes(el) ||
isTransferStateScript(el) ||
isSsrContentsIntegrityMarker(el)
) {
return;
}
if (readHydrationInfo(el)?.status !== HydrationStatus.Hydrated) {
fail('Hydration error: the node is *not* hydrated: ' + el.outerHTML);
}
verifyAllChildNodesClaimedForHydration(el, exceptions);
}
export function verifyAllChildNodesClaimedForHydration(
el: HTMLElement,
exceptions: HTMLElement[] = [],
) {
let current = el.firstChild;
while (current) {
verifyAllNodesClaimedForHydration(current as HTMLElement, exceptions);
current = current.nextSibling;
}
}
/**
* Walks over DOM nodes starting from a given node and make sure
* those nodes were not annotated as "claimed" by hydration.
* This helper function is needed to verify that the non-destructive
* hydration feature can be turned off.
*/
export function verifyNoNodesWereClaimedForHydration(el: HTMLElement) {
if (readHydrationInfo(el)?.status === HydrationStatus.Hydrated) {
fail(
'Unexpected state: the following node was hydrated, when the test ' +
'expects the node to be re-created instead: ' +
el.outerHTML,
);
}
let current = el.firstChild;
while (current) {
verifyNoNodesWereClaimedForHydration(current as HTMLElement);
current = current.nextSibling;
}
}
export function verifyNodeHasSkipHydrationMarker(element: HTMLElement): void {
expect(readHydrationInfo(element)?.status).toBe(HydrationStatus.Skipped);
}
/**
* Verifies whether a console has a log entry that contains a given message.
*/
export function verifyHasLog(appRef: ApplicationRef, message: string) {
const console = appRef.injector.get(Console) as DebugConsole;
const context =
`Expected '${message}' to be present in the log, but it was not found. ` +
`Logs content: ${JSON.stringify(console.logs)}`;
expect(console.logs.some((log) => log.includes(message)))
.withContext(context)
.toBe(true);
}
/**
* Verifies that there is no message with a particular content in a console.
*/
export function verifyHasNoLog(appRef: ApplicationRef, message: string) {
const console = appRef.injector.get(Console) as DebugConsole;
const context =
`Expected '${message}' to be present in the log, but it was not found. ` +
`Logs content: ${JSON.stringify(console.logs)}`;
expect(console.logs.some((log) => log.includes(message)))
.withContext(context)
.toBe(false);
}
export function timeout(delay: number): Promise<void> {
return new Promise<void>((resolve) => {
setTimeout(resolve, delay);
});
}
export function getHydrationInfoFromTransferState(input: string): string | undefined {
return input.match(/<script[^>]+>(.*?)<\/script>/)?.[1];
}
export function withNoopErrorHandler() {
class NoopErrorHandler extends ErrorHandler {
override handleError(error: any): void {
// noop
}
}
return [
{
provide: ErrorHandler,
useClass: NoopErrorHandler,
},
];
}
@Injectable()
export class DebugConsole extends Console {
logs: string[] = [];
override log(message: string) {
this.logs.push(message);
}
override warn(message: string) {
this.logs.push(message);
}
}
export function withDebugConsole() {
return [{provide: Console, useClass: DebugConsole}];
}
/**
* This renders the application with server side rendering logic.
*
* @param component the test component to be rendered
* @param doc the document
* @param envProviders the environment providers
* @returns a promise containing the server rendered app as a string
*/
export async function ssr(
component: Type<unknown>,
options?: {
doc?: string;
envProviders?: Provider[];
hydrationFeatures?: HydrationFeature<HydrationFeatureKind>[];
enableHydration?: boolean;
},
): Promise<string> {
const defaultHtml = DEFAULT_DOCUMENT;
const enableHydration = options?.enableHydration ?? true;
const envProviders = options?.envProviders ?? [];
const hydrationFeatures = options?.hydrationFeatures ?? [];
const providers = [
...envProviders,
provideServerRendering(),
enableHydration ? provideClientHydration(...hydrationFeatures) : [],
];
const bootstrap = () => bootstrapApplication(component, {providers});
return renderApplication(bootstrap, {
document: options?.doc ?? defaultHtml,
});
}
/**
* Verifies that there are no messages in a console.
*/
export function verifyEmptyConsole(appRef: ApplicationRef) {
const console = appRef.injector.get(Console) as DebugConsole;
const logs = console.logs.filter(
(msg) => !msg.startsWith('Angular is running in development mode'),
);
expect(logs).toEqual([]);
}
/**
* Clears the Debug console
*/
export function clearConsole(appRef: ApplicationRef) {
const console = appRef.injector.get(Console) as DebugConsole;
console.logs = [];
}
| {
"end_byte": 8647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/hydration_utils.ts"
} |
angular/packages/platform-server/test/BUILD.bazel_0_2310 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/platform-server/index.mjs",
deps = ["//packages/platform-server"],
)
circular_dependency_test(
name = "testing_circular_deps_test",
entry_point = "angular/packages/platform-server/testing/index.mjs",
deps = ["//packages/platform-server/testing"],
)
ts_library(
name = "dom_utils",
srcs = ["dom_utils.ts"],
deps = [
"//packages/common",
"//packages/core",
"//packages/platform-browser",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(
["*.ts"],
exclude = [
"event_replay_spec.ts",
"dom_utils.ts",
],
),
deps = [
":dom_utils",
"//packages:types",
"//packages/animations",
"//packages/common",
"//packages/common/http",
"//packages/common/http/testing",
"//packages/common/testing",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/localize",
"//packages/localize/init",
"//packages/platform-browser",
"//packages/platform-server",
"//packages/private/testing",
"//packages/router",
"@npm//rxjs",
],
)
ts_library(
name = "event_replay_test_lib",
testonly = True,
srcs = ["event_replay_spec.ts"],
deps = [
":dom_utils",
"//packages/common",
"//packages/core",
"//packages/core/primitives/event-dispatch",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-server",
"//packages/private/testing",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
data = [
"//packages/core/primitives/event-dispatch:contract_bundle_min",
],
deps = [
":test_lib",
],
)
jasmine_node_test(
name = "event_replay_test",
bootstrap = ["//tools/testing:node"],
data = ["//packages/core/primitives/event-dispatch:contract_bundle_min"],
deps = [
":event_replay_test_lib",
],
)
| {
"end_byte": 2310,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/BUILD.bazel"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_0_8347 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
APP_ID,
Component,
destroyPlatform,
getPlatform,
inject,
NgZone,
PLATFORM_ID,
signal,
ɵwhenStable as whenStable,
} from '@angular/core';
import {getAppContents, prepareEnvironmentAndHydrate, resetTViewsFor} from './dom_utils';
import {getComponentRef, ssr, timeout} from './hydration_utils';
import {getDocument} from '@angular/core/src/render3/interfaces/document';
import {isPlatformServer} from '@angular/common';
import {withEventReplay, withIncrementalHydration} from '@angular/platform-browser';
describe('platform-server partial hydration integration', () => {
const originalWindow = globalThis.window;
beforeAll(async () => {
globalThis.window = globalThis as unknown as Window & typeof globalThis;
await import('@angular/core/primitives/event-dispatch/contract_bundle_min.js' as string);
});
beforeEach(() => {
if (getPlatform()) destroyPlatform();
});
afterAll(() => {
globalThis.window = originalWindow;
destroyPlatform();
});
afterEach(() => {
window._ejsas = {};
});
describe('annotation', () => {
it('should annotate inner components with defer block id', async () => {
@Component({
standalone: true,
selector: 'dep-a',
template: '<button (click)="null">Click A</button>',
})
class DepA {}
@Component({
standalone: true,
selector: 'dep-b',
imports: [DepA],
template: `
<dep-a />
<button (click)="null">Click B</button>
`,
})
class DepB {}
@Component({
standalone: true,
selector: 'app',
imports: [DepB],
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<div (click)="fnA()">
Main defer block rendered!
@if (visible) {
Defer events work!
}
<div id="outer-trigger" (mouseover)="showMessage()"></div>
@defer (on viewport; hydrate on interaction) {
<p (click)="fnA()">Nested defer block</p>
<dep-b />
} @placeholder {
<span>Inner block placeholder</span>
}
</div>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
items = [1, 2, 3];
visible = false;
fnA() {}
showMessage() {
this.visible = true;
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration(), withEventReplay()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<main jsaction="click:;">');
// Buttons inside nested components inherit parent defer block namespace.
expect(ssrContents).toContain('<button jsaction="click:;" ngb="d1">Click A</button>');
expect(ssrContents).toContain('<button jsaction="click:;" ngb="d1">Click B</button>');
expect(ssrContents).toContain('<!--ngh=d0-->');
expect(ssrContents).toContain('<!--ngh=d1-->');
}, 100_000);
});
describe('basic hydration behavior', () => {
it('should SSR and hydrate top-level `@defer` blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<article (click)="fnA()">
Main defer block rendered!
@if (visible) {
Defer events work!
}
<aside id="outer-trigger" (mouseover)="showMessage()"></aside>
@defer (on viewport; hydrate on interaction) {
<p (click)="fnA()">Nested defer block</p>
} @placeholder {
<span>Inner block placeholder</span>
}
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
items = [1, 2, 3];
visible = false;
fnA() {}
showMessage() {
this.visible = true;
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// Assert that we have `jsaction` annotations and
// defer blocks are triggered and rendered.
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article jsaction="click:;keydown:;" ngb="d0');
expect(ssrContents).toContain('<aside id="outer-trigger" jsaction="mouseover:;" ngb="d0');
// <p> is inside a nested defer block -> different namespace.
expect(ssrContents).toContain('<p jsaction="click:;keydown:;" ngb="d1');
// There is an extra annotation in the TransferState data.
expect(ssrContents).toContain(
'"__nghDeferData__":{"d0":{"p":null,"r":1,"s":2,"t":[]},"d1":{"p":"d0","r":1,"s":2,"t":[]}}',
);
// Outer defer block is rendered.
expect(ssrContents).toContain('Main defer block rendered');
// Inner defer block is rendered as well.
expect(ssrContents).toContain('Nested defer block');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
// At this point an eager part of an app is hydrated,
// but defer blocks are still in dehydrated state.
// <main> no longer has `jsaction` attribute.
expect(appHostNode.outerHTML).toContain('<main>');
// Elements from @defer blocks still have `jsaction` annotations,
// since they were not triggered yet.
expect(appHostNode.outerHTML).toContain('<article jsaction="click:;keydown:;" ngb="d0');
expect(appHostNode.outerHTML).toContain(
'<aside id="outer-trigger" jsaction="mouseover:;" ngb="d0',
);
expect(appHostNode.outerHTML).toContain('<p jsaction="click:;keydown:;" ngb="d1');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const inner = doc.getElementById('outer-trigger')!;
const clickEvent2 = new CustomEvent('mouseover', {bubbles: true});
inner.dispatchEvent(clickEvent2);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
// An event was replayed after hydration, which resulted in
// an `@if` block becoming active and its inner content got
// rendered/
expect(appHostNode.outerHTML).toContain('Defer events work');
// All outer defer block elements no longer have `jsaction` annotations.
expect(appHostNode.outerHTML).not.toContain('<div jsaction="click:;" ngb="d0');
expect(appHostNode.outerHTML).not.toContain(
'<div id="outer-trigger" jsaction="mouseover:;" ngb="d0',
);
// Inner defer block was not triggered, thus it retains `jsaction` attributes.
expect(appHostNode.outerHTML).toContain('<p jsaction="click:;keydown:;" ngb="d1');
}, 100_000);
| {
"end_byte": 8347,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_8353_12831 | t('should SSR and hydrate nested `@defer` blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<div (click)="fnA()">
Main defer block rendered!
@if (visible) {
Defer events work!
}
<div id="outer-trigger" (mouseover)="showMessage()"></div>
@defer (on viewport; hydrate on interaction) {
<p (click)="showMessage()">Nested defer block</p>
} @placeholder {
<span>Inner block placeholder</span>
}
</div>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
items = [1, 2, 3];
visible = false;
fnA() {}
showMessage() {
this.visible = true;
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// Assert that we have `jsaction` annotations and
// defer blocks are triggered and rendered.
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(ssrContents).toContain('<div id="outer-trigger" jsaction="mouseover:;" ngb="d0"');
// <p> is inside a nested defer block -> different namespace.
expect(ssrContents).toContain('<p jsaction="click:;keydown:;" ngb="d1');
// There is an extra annotation in the TransferState data.
expect(ssrContents).toContain(
'"__nghDeferData__":{"d0":{"p":null,"r":1,"s":2,"t":[]},"d1":{"p":"d0","r":1,"s":2,"t":[]}}',
);
// Outer defer block is rendered.
expect(ssrContents).toContain('Main defer block rendered');
// Inner defer block is rendered as well.
expect(ssrContents).toContain('Nested defer block');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
// At this point an eager part of an app is hydrated,
// but defer blocks are still in dehydrated state.
// <main> no longer has `jsaction` attribute.
expect(appHostNode.outerHTML).toContain('<main>');
// Elements from @defer blocks still have `jsaction` annotations,
// since they were not triggered yet.
expect(appHostNode.outerHTML).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(appHostNode.outerHTML).toContain(
'<div id="outer-trigger" jsaction="mouseover:;" ngb="d0',
);
expect(appHostNode.outerHTML).toContain('<p jsaction="click:;keydown:;" ngb="d1"');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const inner = doc.body.querySelector('p')!;
const clickEvent = new CustomEvent('click', {bubbles: true});
inner.dispatchEvent(clickEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
// An event was replayed after hydration, which resulted in
// an `@if` block becoming active and its inner content got
// rendered/
expect(appHostNode.outerHTML).toContain('Defer events work');
// Since inner `@defer` block was triggered, all parent blocks
// were hydrated as well, so all `jsaction` attributes are removed.
expect(appHostNode.outerHTML).not.toContain('jsaction="');
}, 100_000);
| {
"end_byte": 12831,
"start_byte": 8353,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_12837_17607 | t('should SSR and hydrate only defer blocks with hydrate syntax', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on interaction) {
<div (click)="fnA()">
Main defer block rendered!
@if (visible) {
Defer events work!
}
<div id="outer-trigger" (mouseover)="showMessage()"></div>
@defer (on interaction) {
<p (click)="showMessage()">Nested defer block</p>
} @placeholder {
<span>Inner block placeholder</span>
}
</div>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
items = [1, 2, 3];
visible = false;
fnA() {}
showMessage() {
this.visible = true;
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// Assert that we have `jsaction` annotations and
// defer blocks are triggered and rendered.
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(ssrContents).toContain('<div id="outer-trigger" jsaction="mouseover:;" ngb="d0"');
// <p> is inside a nested defer block -> different namespace.
// expect(ssrContents).toContain('<p jsaction="click:;" ngb="d1');
// There is an extra annotation in the TransferState data.
expect(ssrContents).toContain(
'"__nghDeferData__":{"d0":{"p":null,"r":1,"s":2,"t":[]},"d1":{"p":"d0","r":1,"s":0,"t":null}}',
);
// Outer defer block is rendered.
expect(ssrContents).toContain('Main defer block rendered');
// Inner defer block should only display placeholder.
expect(ssrContents).toContain('Inner block placeholder');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
// At this point an eager part of an app is hydrated,
// but defer blocks are still in dehydrated state.
// <main> no longer has `jsaction` attribute.
expect(appHostNode.outerHTML).toContain('<main>');
// Elements from @defer blocks still have `jsaction` annotations,
// since they were not triggered yet.
expect(appHostNode.outerHTML).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(appHostNode.outerHTML).toContain(
'<div id="outer-trigger" jsaction="mouseover:;" ngb="d0',
);
// expect(appHostNode.outerHTML).toContain('<p jsaction="click:;" ngb="d1"');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const inner = doc.getElementById('outer-trigger')!;
const clickEvent2 = new CustomEvent('mouseover', {bubbles: true});
inner.dispatchEvent(clickEvent2);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
const innerParagraph = doc.body.querySelector('p')!;
expect(innerParagraph).toBeUndefined();
// An event was replayed after hydration, which resulted in
// an `@if` block becoming active and its inner content got
// rendered/
expect(appHostNode.outerHTML).toContain('Defer events work');
expect(appHostNode.outerHTML).toContain('Inner block placeholder');
// Since inner `@defer` block was triggered, all parent blocks
// were hydrated as well, so all `jsaction` attributes are removed.
expect(appHostNode.outerHTML).not.toContain('jsaction="');
}, 100_000);
});
/* TODO: tests to add
3. transfer state data is correct for parent / child defer blocks
*/
| {
"end_byte": 17607,
"start_byte": 12837,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_17611_22927 | escribe('triggers', () => {
describe('hydrate on interaction', () => {
it('click', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<article>
defer block rendered!
</article>
<span id="test" (click)="fnB()">{{value()}}</span>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article jsaction="click:;keydown:;"');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article jsaction="click:;keydown:;"');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const article = doc.getElementsByTagName('article')![0];
const clickEvent = new CustomEvent('click', {bubbles: true});
article.dispatchEvent(clickEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).not.toContain('<div jsaction="click:;keydown:;"');
}, 100_000);
it('keydown', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article jsaction="click:;keydown:;"');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article jsaction="click:;keydown:;"');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const article = doc.getElementsByTagName('article')![0];
const keydownEvent = new KeyboardEvent('keydown');
article.dispatchEvent(keydownEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).not.toContain('<div jsaction="click:;keydown:;"');
}, 100_000);
});
| {
"end_byte": 22927,
"start_byte": 17611,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_22933_28372 | escribe('hydrate on hover', () => {
it('mouseover', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on hover) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article jsaction="mouseenter:;mouseover:;focusin:;"');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain(
'<article jsaction="mouseenter:;mouseover:;focusin:;"',
);
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const article = doc.getElementsByTagName('article')![0];
const hoverEvent = new CustomEvent('mouseover', {bubbles: true});
article.dispatchEvent(hoverEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).not.toContain(
'<div jsaction="mouseenter:;mouseover:;focusin:;"',
);
}, 100_000);
it('focusin', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on hover) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article jsaction="mouseenter:;mouseover:;focusin:;"');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain(
'<article jsaction="mouseenter:;mouseover:;focusin:;"',
);
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const article = doc.getElementsByTagName('article')![0];
const focusEvent = new CustomEvent('focusin', {bubbles: true});
article.dispatchEvent(focusEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).not.toContain(
'<div jsaction="mouseenter:;mouseover:;focusin:;"',
);
}, 100_000);
});
| {
"end_byte": 28372,
"start_byte": 22933,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_28378_36194 | escribe('viewport', () => {
let activeObservers: MockIntersectionObserver[] = [];
let nativeIntersectionObserver: typeof IntersectionObserver;
beforeEach(() => {
nativeIntersectionObserver = globalThis.IntersectionObserver;
globalThis.IntersectionObserver = MockIntersectionObserver;
});
afterEach(() => {
globalThis.IntersectionObserver = nativeIntersectionObserver;
activeObservers = [];
});
/**
* Mocked out implementation of the native IntersectionObserver API. We need to
* mock it out for tests, because it's unsupported in Domino and we can't trigger
* it reliably in the browser.
*/
class MockIntersectionObserver implements IntersectionObserver {
root = null;
rootMargin = null!;
thresholds = null!;
observedElements = new Set<Element>();
private elementsInView = new Set<Element>();
constructor(private callback: IntersectionObserverCallback) {
activeObservers.push(this);
}
static invokeCallbacksForElement(element: Element, isInView: boolean) {
for (const observer of activeObservers) {
const elements = observer.elementsInView;
const wasInView = elements.has(element);
if (isInView) {
elements.add(element);
} else {
elements.delete(element);
}
observer.invokeCallback();
if (wasInView) {
elements.add(element);
} else {
elements.delete(element);
}
}
}
private invokeCallback() {
for (const el of this.observedElements) {
this.callback(
[
{
target: el,
isIntersecting: this.elementsInView.has(el),
// Unsupported properties.
boundingClientRect: null!,
intersectionRatio: null!,
intersectionRect: null!,
rootBounds: null,
time: null!,
},
],
this,
);
}
}
observe(element: Element) {
this.observedElements.add(element);
// Native observers fire their callback as soon as an
// element is observed so we try to mimic it here.
this.invokeCallback();
}
unobserve(element: Element) {
this.observedElements.delete(element);
}
disconnect() {
this.observedElements.clear();
this.elementsInView.clear();
}
takeRecords(): IntersectionObserverEntry[] {
throw new Error('Not supported');
}
}
it('viewport', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on viewport) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<!--ngh=d0-->');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain(
'<span id="test" jsaction="click:;" ngb="d0">start</span>',
);
const article: HTMLElement = document.getElementsByTagName('article')[0];
MockIntersectionObserver.invokeCallbacksForElement(article, false);
appRef.tick();
const testElement = doc.getElementById('test')!;
const clickEvent = new CustomEvent('click');
testElement.dispatchEvent(clickEvent);
appRef.tick();
expect(appHostNode.outerHTML).toContain(
'<span id="test" jsaction="click:;" ngb="d0">start</span>',
);
MockIntersectionObserver.invokeCallbacksForElement(article, true);
await timeout(1000); // wait for defer blocks to resolve
const clickEvent2 = new CustomEvent('click');
testElement.dispatchEvent(clickEvent2);
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">end</span>');
}, 100_000);
});
it('immediate', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on immediate) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<span id="test">start</span>');
const testElement = doc.getElementById('test')!;
const clickEvent2 = new CustomEvent('click');
testElement.dispatchEvent(clickEvent2);
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">end</span>');
}, 100_000);
| {
"end_byte": 36194,
"start_byte": 28378,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_36200_45272 | escribe('idle', () => {
/**
* Sets up interceptors for when an idle callback is requested
* and when it's cancelled. This is needed to keep track of calls
* made to `requestIdleCallback` and `cancelIdleCallback` APIs.
*/
let id = 0;
let idleCallbacksRequested: number;
let idleCallbacksInvoked: number;
let idleCallbacksCancelled: number;
const onIdleCallbackQueue: Map<number, IdleRequestCallback> = new Map();
function resetCounters() {
idleCallbacksRequested = 0;
idleCallbacksInvoked = 0;
idleCallbacksCancelled = 0;
}
resetCounters();
let nativeRequestIdleCallback: (
callback: IdleRequestCallback,
options?: IdleRequestOptions,
) => number;
let nativeCancelIdleCallback: (id: number) => void;
const mockRequestIdleCallback = (
callback: IdleRequestCallback,
options?: IdleRequestOptions,
): number => {
onIdleCallbackQueue.set(id, callback);
expect(idleCallbacksRequested).toBe(0);
expect(NgZone.isInAngularZone()).toBe(true);
idleCallbacksRequested++;
return id++;
};
const mockCancelIdleCallback = (id: number) => {
onIdleCallbackQueue.delete(id);
idleCallbacksRequested--;
idleCallbacksCancelled++;
};
const triggerIdleCallbacks = () => {
for (const [_, callback] of onIdleCallbackQueue) {
idleCallbacksInvoked++;
callback(null!);
}
onIdleCallbackQueue.clear();
};
beforeEach(() => {
nativeRequestIdleCallback = globalThis.requestIdleCallback;
nativeCancelIdleCallback = globalThis.cancelIdleCallback;
globalThis.requestIdleCallback = mockRequestIdleCallback;
globalThis.cancelIdleCallback = mockCancelIdleCallback;
resetCounters();
});
afterEach(() => {
globalThis.requestIdleCallback = nativeRequestIdleCallback;
globalThis.cancelIdleCallback = nativeCancelIdleCallback;
onIdleCallbackQueue.clear();
resetCounters();
});
it('idle', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on idle) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article>');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article>');
triggerIdleCallbacks();
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">start</span>');
const testElement = doc.getElementById('test')!;
const clickEvent2 = new CustomEvent('click');
testElement.dispatchEvent(clickEvent2);
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">end</span>');
}, 100_000);
});
it('timer', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate on timer(500)) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article>');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article>');
await timeout(500); // wait for timer
appRef.tick();
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">start</span>');
const testElement = doc.getElementById('test')!;
const clickEvent2 = new CustomEvent('click');
testElement.dispatchEvent(clickEvent2);
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span id="test">end</span>');
}, 100_000);
it('never', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (hydrate never) {
<article>
defer block rendered!
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article>');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article>');
await timeout(500); // wait for timer
appRef.tick();
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).not.toContain('Outer block placeholder');
}, 100_000);
| {
"end_byte": 45272,
"start_byte": 36200,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/test/incremental_hydration_spec.ts_45278_52584 | t('defer triggers should not fire when hydrate never is used', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on timer(1s); hydrate never) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<article>');
// Outer defer block is rendered.
expect(ssrContents).toContain('defer block rendered');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain('<article>');
expect(appHostNode.outerHTML).toContain('>start</span>');
await timeout(500); // wait for timer
appRef.tick();
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
const testElement = doc.getElementById('test')!;
const clickEvent2 = new CustomEvent('click');
testElement.dispatchEvent(clickEvent2);
appRef.tick();
expect(appHostNode.outerHTML).toContain('>start</span>');
expect(appHostNode.outerHTML).not.toContain('<span id="test">end</span>');
expect(appHostNode.outerHTML).not.toContain('Outer block placeholder');
}, 100_000);
it('should not annotate jsaction events for events inside a hydrate never block', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on timer(1s); hydrate never) {
<article>
defer block rendered!
<span id="test" (click)="fnB()">{{value()}}</span>
@defer(on immediate; hydrate on idle) {
<p id="test2" (click)="fnB()">shouldn't be annotated</p>
} @placeholder {
<p>blah de blah</p>
}
</article>
} @placeholder {
<span>Outer block placeholder</span>
}
@defer (on timer(1s); hydrate on viewport) {
<div>
viewport section
<p (click)="fnA()">has a binding</p>
</div>
} @placeholder {
<span>another placeholder</span>
}
</main>
`,
})
class SimpleComponent {
value = signal('start');
fnA() {}
fnB() {
this.value.set('end');
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
expect(ssrContents).not.toContain('<span id="test" jsaction="click:;');
expect(ssrContents).toContain('<span id="test">start</span>');
expect(ssrContents).toContain('<p jsaction="click:;" ngb="d1">has a binding</p>');
expect(ssrContents).not.toContain('<p id="test2" jsaction="click:;');
expect(ssrContents).toContain('<p id="test2">shouldn\'t be annotated</p>');
}, 100_000);
});
describe('cleanup', () => {
it('should cleanup partial hydration blocks appropriately', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on idle; hydrate on interaction) {
<p id="test">inside defer block</p>
@if (isServer) {
<span>Server!</span>
} @else {
<span>Client!</span>
}
} @loading {
<span>Loading...</span>
} @placeholder {
<p>Placeholder!</p>
}
</main>
`,
})
class SimpleComponent {
fnA() {}
isServer = isPlatformServer(inject(PLATFORM_ID));
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain(
'<p id="test" jsaction="click:;keydown:;" ngb="d0">inside defer block</p>',
);
// Outer defer block is rendered.
expect(ssrContents).toContain('<span jsaction="click:;keydown:;" ngb="d0">Server!</span>');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
expect(appHostNode.outerHTML).toContain(
'<p id="test" jsaction="click:;keydown:;" ngb="d0">inside defer block</p>',
);
expect(appHostNode.outerHTML).toContain(
'<span jsaction="click:;keydown:;" ngb="d0">Server!</span>',
);
const testElement = doc.getElementById('test')!;
const clickEvent = new CustomEvent('click', {bubbles: true});
testElement.dispatchEvent(clickEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
expect(appHostNode.outerHTML).toContain('<span>Client!</span>');
expect(appHostNode.outerHTML).not.toContain('>Server!</span>');
}, 100_000);
});
});
| {
"end_byte": 52584,
"start_byte": 45278,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/test/incremental_hydration_spec.ts"
} |
angular/packages/platform-server/testing/PACKAGE.md_0_68 | Supplies a testing module for the Angular platform server subsystem. | {
"end_byte": 68,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-server/testing/PACKAGE.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.