_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/zone.js/doc/task.md_0_3189 | ## Task lifecycle
We handle several kinds of tasks in zone.js,
- MacroTask
- MicroTask
- EventTask
For details, please refer to [here](../dist/zone.js.d.ts)
This document will explain the lifecycle (state-transition) of different types of tasks and also the triggering of various zonespec's callback during that cycle.
The motivation to write this document has come from this [PR](https://github.com/angular/zone.js/pull/629) of @mhevery. This has made the task's state more clear. Also, tasks can now be cancelled and rescheduled in different zone.
### MicroTask
Such as Promise.then, process.nextTick, they are microTasks, the lifecycle(state transition)
looks like this.

ZoneSpec's onHasTask callback will be triggered when the first microTask were scheduled or the
last microTask was invoked.
### EventTask
Such as EventTarget's EventListener, EventEmitter's EventListener, their lifecycle(state transition)
looks like this.

ZoneSpec's onHasTask callback will be triggered when the first eventTask were scheduled or the
last eventTask was cancelled.
EventTask will go back to scheduled state after invoked(running state), and will become notScheduled after cancelTask(such as removeEventListener)
### MacroTask
#### Non Periodical MacroTask
Such as setTimeout/XMLHttpRequest, their lifecycle(state transition)
looks like this.

ZoneSpec's onHasTask callback will be triggered when the first macroTask were scheduled or the
last macroTask was invoked or cancelled.
Non periodical macroTask will become notScheduled after being invoked or being cancelled(such as clearTimeout)
#### Periodical MacroTask
Such as setInterval, their lifecycle(state transition)
looks like this.

ZoneSpec's onHasTask callback will be triggered when first macroTask was scheduled or last macroTask
was cancelled, it will not triggered after invoke, because it is periodical and become scheduled again.
Periodical macroTask will go back to scheduled state after invoked(running state), and will become notScheduled after cancelTask(such as clearInterval)
### Reschedule Task to a new zone
Sometimes you may want to reschedule task into different zone, the lifecycle looks like

the ZoneTask's cancelScheduleRequest method can be only called in onScheduleTask callback of ZoneSpec,
because it is still under scheduling state.
And after rescheduling, the task will be scheduled to new zone(the otherZoneSpec in the graph),
and will have nothing todo with the original zone.
### Override zone when scheduling
Sometimes you may want to just override the zone when scheduling, the lifecycle looks like

After overriding, the task will be invoked/cancelled in the new zone(the otherZoneSpec in the graph),
but hasTask callback will still be invoked in original zone.
### Error occurs in task lifecycle

| {
"end_byte": 3189,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/task.md"
} |
angular/packages/zone.js/doc/periodical-macrotask.puml_0_469 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: setInterval
scheduling: zoneSpec.onScheduleTask
scheduling: zoneSpec.onHasTask
scheduling --> scheduled
scheduled --> running: interval\n callback
running: zoneSpec:onInvokeTask
scheduled --> canceling: clearInterval
canceling: zoneSpec.onCancelTask
canceling --> notScheduled
canceling: zoneSpec.onHasTask
running --> scheduled: callback\n finished
running --> canceling: clearInterval
@enduml | {
"end_byte": 469,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/periodical-macrotask.puml"
} |
angular/packages/zone.js/doc/reschedule-task.puml_0_596 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: ①current zone\n scheduleTask
notScheduled --> scheduling: ③anotherZone\n scheduleTask
scheduling: anotherZoneSpec.onScheduleTask
scheduling: anotherZoneSpec.onHasTask
scheduling --> notScheduled: ②cancelScheduleRequest
scheduling --> scheduled
scheduled --> running: callback
running: anotherZoneSpec:onInvokeTask
scheduled --> canceling: cancelTask
canceling: anotherZoneSpec.onCancelTask
canceling --> notScheduled
canceling: anotherZoneSpec.onHasTask
running --> notScheduled
running: anotherZoneSpec.onHasTask
@enduml | {
"end_byte": 596,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/reschedule-task.puml"
} |
angular/packages/zone.js/doc/non-periodical-macrotask.puml_0_515 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: setTimeout/\nXMLHttpRequest.send\nand so on
scheduling: zoneSpec.onScheduleTask
scheduling: zoneSpec.onHasTask
scheduling --> scheduled
scheduled --> running: timeout callback\nreadystatechange\ncallback
running: zoneSpec:onInvokeTask
scheduled --> canceling: clearTimeout\n/abort request
canceling: zoneSpec.onCancelTask
canceling --> notScheduled
canceling: zoneSpec.onHasTask
running --> notScheduled
running: zoneSpec.onHasTask
@enduml
| {
"end_byte": 515,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/non-periodical-macrotask.puml"
} |
angular/packages/zone.js/bundles/BUILD.bazel_0_223 | load("//packages/zone.js:tools.bzl", "generate_dist")
load("//packages/zone.js:bundles.bzl", "BUNDLES_ENTRY_POINTS")
generate_dist(
bundles = BUNDLES_ENTRY_POINTS.items(),
output_format = "es5",
umd = "umd",
)
| {
"end_byte": 223,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/bundles/BUILD.bazel"
} |
angular/packages/platform-browser/PACKAGE.md_0_356 | Supports execution of Angular apps on different supported browsers.
The `BrowserModule` is included by default in any app created through the CLI,
and it re-exports the `CommonModule` and `ApplicationModule` exports,
making basic Angular functionality available to the app.
For more information, see [Browser Support](reference/versions#browser-support). | {
"end_byte": 356,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/PACKAGE.md"
} |
angular/packages/platform-browser/BUILD.bazel_0_2334 | load("//tools:defaults.bzl", "api_golden_test", "api_golden_test_npm_package", "generate_api_docs", "ng_module", "ng_package", "tsec_test")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "platform-browser",
package_name = "@angular/platform-browser",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages:types",
"//packages/common",
"//packages/common/http",
"//packages/core",
"//packages/zone.js/lib:zone_d_ts",
"@npm//@types/hammerjs",
],
)
tsec_test(
name = "tsec_test",
target = "platform-browser",
tsconfig = "//packages:tsec_config",
)
ng_package(
name = "npm_package",
srcs = [
"package.json",
],
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__",
"//packages/compiler-cli/test:__pkg__",
],
deps = [
":platform-browser",
"//packages/platform-browser/animations",
"//packages/platform-browser/animations/async",
"//packages/platform-browser/testing",
],
)
api_golden_test_npm_package(
name = "platform-browser_api",
data = [
":npm_package",
"//goldens:public-api",
],
golden_dir = "angular/goldens/public-api/platform-browser",
npm_package = "angular/packages/platform-browser/npm_package",
)
api_golden_test(
name = "platform-browser_errors",
data = [
"//goldens:public-api",
"//packages/platform-browser",
],
entry_point = "angular/packages/platform-browser/src/errors.d.ts",
golden = "angular/goldens/public-api/platform-browser/errors.api.md",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-browser_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-browser",
)
| {
"end_byte": 2334,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/BUILD.bazel"
} |
angular/packages/platform-browser/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-browser/index.ts"
} |
angular/packages/platform-browser/public_api.ts_0_406 | /**
* @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/platform-browser';
// This file only reexports content of the `src` folder. Keep it that way.
| {
"end_byte": 406,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/public_api.ts"
} |
angular/packages/platform-browser/test/hydration_spec.ts_0_5113 | /**
* @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 {HttpClient, HttpTransferCacheOptions, provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {
ApplicationRef,
Component,
Injectable,
PLATFORM_ID,
ɵSSR_CONTENT_INTEGRITY_MARKER as SSR_CONTENT_INTEGRITY_MARKER,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {withBody} from '@angular/private/testing';
import {BehaviorSubject} from 'rxjs';
import {provideClientHydration, withNoHttpTransferCache} from '../public_api';
import {withHttpTransferCacheOptions} from '../src/hydration';
describe('provideClientHydration', () => {
@Component({
selector: 'test-hydrate-app',
template: '',
standalone: false,
})
class SomeComponent {}
function makeRequestAndExpectOne(
url: string,
body: string,
options: HttpTransferCacheOptions | boolean = true,
): void {
TestBed.inject(HttpClient).get(url, {transferCache: options}).subscribe();
TestBed.inject(HttpTestingController).expectOne(url).flush(body);
}
function makeRequestAndExpectNone(
url: string,
options: HttpTransferCacheOptions | boolean = true,
): void {
TestBed.inject(HttpClient).get(url, {transferCache: options}).subscribe();
TestBed.inject(HttpTestingController).expectNone(url);
}
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
describe('default', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should use cached HTTP calls`, () => {
makeRequestAndExpectOne('/test-1', 'foo');
// Do the same call, this time it should served from cache.
makeRequestAndExpectNone('/test-1');
});
});
describe('withNoHttpTransferCache', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(withNoHttpTransferCache()),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should not cache HTTP calls`, () => {
makeRequestAndExpectOne('/test-1', 'foo', false);
// Do the same call, this time should pass through as cache is disabled.
makeRequestAndExpectOne('/test-1', 'foo');
});
});
describe('withHttpTransferCacheOptions', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(
withHttpTransferCacheOptions({includePostRequests: true, includeHeaders: ['foo']}),
),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should cache HTTP POST calls`, () => {
const url = '/test-1';
const body = 'foo';
TestBed.inject(HttpClient).post(url, body).subscribe();
TestBed.inject(HttpTestingController).expectOne(url).flush(body);
TestBed.inject(HttpClient).post(url, body).subscribe();
TestBed.inject(HttpTestingController).expectNone(url);
});
});
});
| {
"end_byte": 5113,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/hydration_spec.ts"
} |
angular/packages/platform-browser/test/testing_public_spec.ts_0_7958 | /**
* @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 {ResourceLoader} from '@angular/compiler';
import {
Compiler,
Component,
ComponentFactoryResolver,
CUSTOM_ELEMENTS_SCHEMA,
Directive,
Inject,
Injectable,
InjectionToken,
Injector,
Input,
NgModule,
Optional,
Pipe,
TransferState,
SkipSelf,
Type,
} from '@angular/core';
import {
fakeAsync,
getTestBed,
inject,
TestBed,
tick,
waitForAsync,
withModule,
} from '@angular/core/testing';
import {expect} from '@angular/platform-browser/testing/src/matchers';
// Services, and components for the tests.
@Component({
selector: 'child-comp',
template: `<span>Original {{childBinding}}</span>`,
standalone: false,
})
@Injectable()
class ChildComp {
childBinding: string;
constructor() {
this.childBinding = 'Child';
}
}
@Component({
selector: 'child-comp',
template: `<span>Mock</span>`,
standalone: false,
})
@Injectable()
class MockChildComp {}
@Component({
selector: 'parent-comp',
template: `Parent(<child-comp></child-comp>)`,
standalone: false,
})
@Injectable()
class ParentComp {}
@Component({
selector: 'my-if-comp',
template: `MyIf(<span *ngIf="showMore">More</span>)`,
standalone: false,
})
@Injectable()
class MyIfComp {
showMore: boolean = false;
}
@Component({
selector: 'child-child-comp',
template: `<span>ChildChild</span>`,
standalone: false,
})
@Injectable()
class ChildChildComp {}
class FancyService {
value: string = 'real value';
getAsyncValue() {
return Promise.resolve('async value');
}
getTimeoutValue() {
return new Promise<string>((resolve, reject) => setTimeout(() => resolve('timeout value'), 10));
}
}
class MockFancyService extends FancyService {
override value: string = 'mocked out value';
}
@Component({
selector: 'my-service-comp',
providers: [FancyService],
template: `injected value: {{fancyService.value}}`,
standalone: false,
})
class TestProvidersComp {
constructor(private fancyService: FancyService) {}
}
@Component({
selector: 'my-service-comp',
viewProviders: [FancyService],
template: `injected value: {{fancyService.value}}`,
standalone: false,
})
class TestViewProvidersComp {
constructor(private fancyService: FancyService) {}
}
@Directive({
selector: '[someDir]',
host: {'[title]': 'someDir'},
standalone: false,
})
class SomeDirective {
@Input() someDir!: string;
}
@Pipe({
name: 'somePipe',
standalone: false,
})
class SomePipe {
transform(value: string) {
return `transformed ${value}`;
}
}
@Component({
selector: 'comp',
template: `<div [someDir]="'someValue' | somePipe"></div>`,
standalone: false,
})
class CompUsingModuleDirectiveAndPipe {}
@NgModule()
class SomeLibModule {}
const aTok = new InjectionToken<string>('a');
const bTok = new InjectionToken<string>('b');
describe('public testing API', () => {
describe('using the async helper with context passing', () => {
type TestContext = {actuallyDone: boolean};
beforeEach(function (this: TestContext) {
this.actuallyDone = false;
});
afterEach(function (this: TestContext) {
expect(this.actuallyDone).toEqual(true);
});
it('should run normal tests', function (this: TestContext) {
this.actuallyDone = true;
});
it('should run normal async tests', function (this: TestContext, done) {
setTimeout(() => {
this.actuallyDone = true;
done();
}, 0);
});
it('should run async tests with tasks', waitForAsync(function (this: TestContext) {
setTimeout(() => (this.actuallyDone = true), 0);
}));
it('should run async tests with promises', waitForAsync(function (this: TestContext) {
const p = new Promise((resolve, reject) => setTimeout(resolve, 10));
p.then(() => (this.actuallyDone = true));
}));
});
describe('basic context passing to inject, fakeAsync and withModule helpers', () => {
const moduleConfig = {
providers: [FancyService],
};
type TestContext = {contextModified: boolean};
beforeEach(function (this: TestContext) {
this.contextModified = false;
});
afterEach(function (this: TestContext) {
expect(this.contextModified).toEqual(true);
});
it('should pass context to inject helper', inject([], function (this: TestContext) {
this.contextModified = true;
}));
it('should pass context to fakeAsync helper', fakeAsync(function (this: TestContext) {
this.contextModified = true;
}));
it(
'should pass context to withModule helper - simple',
withModule(moduleConfig, function (this: TestContext) {
this.contextModified = true;
}),
);
it(
'should pass context to withModule helper - advanced',
withModule(moduleConfig).inject(
[FancyService],
function (this: TestContext, service: FancyService) {
expect(service.value).toBe('real value');
this.contextModified = true;
},
),
);
it('should preserve context when async and inject helpers are combined', waitForAsync(
inject([], function (this: TestContext) {
setTimeout(() => (this.contextModified = true), 0);
}),
));
it('should preserve context when fakeAsync and inject helpers are combined', fakeAsync(
inject([], function (this: TestContext) {
setTimeout(() => (this.contextModified = true), 0);
tick(1);
}),
));
});
describe('using the test injector with the inject helper', () => {
describe('setting up Providers', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: FancyService, useValue: new FancyService()}],
});
});
it('should use set up providers', inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('real value');
}));
it('should wait until returned promises', waitForAsync(
inject([FancyService], (service: FancyService) => {
service.getAsyncValue().then((value) => expect(value).toEqual('async value'));
service.getTimeoutValue().then((value) => expect(value).toEqual('timeout value'));
}),
));
it('should allow the use of fakeAsync', fakeAsync(
inject([FancyService], (service: FancyService) => {
let value: string = undefined!;
service.getAsyncValue().then((val) => (value = val));
tick();
expect(value).toEqual('async value');
}),
));
it('should allow use of "done"', (done) => {
inject([FancyService], (service: FancyService) => {
let count = 0;
const id = setInterval(() => {
count++;
if (count > 2) {
clearInterval(id);
done();
}
}, 5);
})(); // inject needs to be invoked explicitly with ().
});
describe('using beforeEach', () => {
beforeEach(inject([FancyService], (service: FancyService) => {
service.value = 'value modified in beforeEach';
}));
it('should use modified providers', inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('value modified in beforeEach');
}));
});
describe('using async beforeEach', () => {
beforeEach(waitForAsync(
inject([FancyService], (service: FancyService) => {
service.getAsyncValue().then((value) => (service.value = value));
}),
));
it('should use asynchronously modified value', inject(
[FancyService],
(service: FancyService) => {
expect(service.value).toEqual('async value');
},
));
});
});
}); | {
"end_byte": 7958,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/testing_public_spec.ts"
} |
angular/packages/platform-browser/test/testing_public_spec.ts_7962_15152 | describe('using the test injector with modules', () => {
const moduleConfig = {
providers: [FancyService],
imports: [SomeLibModule],
declarations: [SomeDirective, SomePipe, CompUsingModuleDirectiveAndPipe],
};
describe('setting up a module', () => {
beforeEach(() => TestBed.configureTestingModule(moduleConfig));
it('should use set up providers', inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('real value');
}));
it('should be able to create any declared components', () => {
const compFixture = TestBed.createComponent(CompUsingModuleDirectiveAndPipe);
expect(compFixture.componentInstance).toBeInstanceOf(CompUsingModuleDirectiveAndPipe);
});
it('should use set up directives and pipes', () => {
const compFixture = TestBed.createComponent(CompUsingModuleDirectiveAndPipe);
const el = compFixture.debugElement;
compFixture.detectChanges();
expect(el.children[0].properties['title']).toBe('transformed someValue');
});
it('should use set up imported modules', inject(
[SomeLibModule],
(libModule: SomeLibModule) => {
expect(libModule).toBeInstanceOf(SomeLibModule);
},
));
describe('provided schemas', () => {
@Component({
template: '<some-element [someUnknownProp]="true"></some-element>',
standalone: false,
})
class ComponentUsingInvalidProperty {}
beforeEach(() => {
TestBed.configureTestingModule({
schemas: [CUSTOM_ELEMENTS_SCHEMA],
declarations: [ComponentUsingInvalidProperty],
});
});
it('should not error on unknown bound properties on custom elements when using the CUSTOM_ELEMENTS_SCHEMA', () => {
expect(
TestBed.createComponent(ComponentUsingInvalidProperty).componentInstance,
).toBeInstanceOf(ComponentUsingInvalidProperty);
});
});
});
describe('per test modules', () => {
it(
'should use set up providers',
withModule(moduleConfig).inject([FancyService], (service: FancyService) => {
expect(service.value).toEqual('real value');
}),
);
it(
'should use set up directives and pipes',
withModule(moduleConfig, () => {
const compFixture = TestBed.createComponent(CompUsingModuleDirectiveAndPipe);
const el = compFixture.debugElement;
compFixture.detectChanges();
expect(el.children[0].properties['title']).toBe('transformed someValue');
}),
);
it(
'should use set up library modules',
withModule(moduleConfig).inject([SomeLibModule], (libModule: SomeLibModule) => {
expect(libModule).toBeInstanceOf(SomeLibModule);
}),
);
});
xdescribe('components with template url', () => {
let TestComponent!: Type<unknown>;
beforeEach(waitForAsync(async () => {
@Component({
selector: 'comp',
templateUrl: '/base/angular/packages/platform-browser/test/static_assets/test.html',
standalone: false,
})
class CompWithUrlTemplate {}
TestComponent = CompWithUrlTemplate;
TestBed.configureTestingModule({declarations: [CompWithUrlTemplate]});
await TestBed.compileComponents();
}));
isBrowser &&
it('should allow to createSync components with templateUrl after explicit async compilation', () => {
const fixture = TestBed.createComponent(TestComponent);
expect(fixture.nativeElement).toHaveText('from external template');
});
it('should always pass to satisfy jasmine always wanting an `it` block under a `describe`', () => {});
});
describe('overwriting metadata', () => {
@Pipe({
name: 'undefined',
standalone: false,
})
class SomePipe {
transform(value: string): string {
return `transformed ${value}`;
}
}
@Directive({
selector: '[undefined]',
standalone: false,
})
class SomeDirective {
someProp = 'hello';
}
@Component({
selector: 'comp',
template: 'someText',
standalone: false,
})
class SomeComponent {}
@Component({
selector: 'comp',
template: 'someOtherText',
standalone: false,
})
class SomeOtherComponent {}
@NgModule({declarations: [SomeComponent, SomeDirective, SomePipe]})
class SomeModule {}
beforeEach(() => TestBed.configureTestingModule({imports: [SomeModule]}));
describe('module', () => {
beforeEach(() => {
TestBed.overrideModule(SomeModule, {set: {declarations: [SomeOtherComponent]}});
});
it('should work', () => {
expect(TestBed.createComponent(SomeOtherComponent).componentInstance).toBeInstanceOf(
SomeOtherComponent,
);
});
});
describe('component', () => {
beforeEach(() => {
TestBed.overrideComponent(SomeComponent, {set: {selector: 'comp', template: 'newText'}});
});
it('should work', () => {
expect(TestBed.createComponent(SomeComponent).nativeElement).toHaveText('newText');
});
});
describe('directive', () => {
beforeEach(() => {
TestBed.overrideComponent(SomeComponent, {
set: {selector: 'comp', template: `<div someDir></div>`},
}).overrideDirective(SomeDirective, {
set: {selector: '[someDir]', host: {'[title]': 'someProp'}},
});
});
it('should work', () => {
const compFixture = TestBed.createComponent(SomeComponent);
compFixture.detectChanges();
expect(compFixture.debugElement.children[0].properties['title']).toEqual('hello');
});
});
describe('pipe', () => {
beforeEach(() => {
TestBed.overrideComponent(SomeComponent, {
set: {selector: 'comp', template: `{{'hello' | somePipe}}`},
})
.overridePipe(SomePipe, {set: {name: 'somePipe'}})
.overridePipe(SomePipe, {add: {pure: false}});
});
it('should work', () => {
const compFixture = TestBed.createComponent(SomeComponent);
compFixture.detectChanges();
expect(compFixture.nativeElement).toHaveText('transformed hello');
});
});
describe('template', () => {
let testBedSpy: any;
beforeEach(() => {
testBedSpy = spyOn(getTestBed(), 'overrideComponent').and.callThrough();
TestBed.overrideTemplate(SomeComponent, 'newText');
});
it(`should override component's template`, () => {
const fixture = TestBed.createComponent(SomeComponent);
expect(fixture.nativeElement).toHaveText('newText');
expect(testBedSpy).toHaveBeenCalledWith(SomeComponent, {
set: {template: 'newText', templateUrl: null},
});
});
});
}); | {
"end_byte": 15152,
"start_byte": 7962,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/testing_public_spec.ts"
} |
angular/packages/platform-browser/test/testing_public_spec.ts_15158_19926 | describe('overriding providers', () => {
describe('in core', () => {
it('ComponentFactoryResolver', () => {
const componentFactoryMock = jasmine.createSpyObj('componentFactory', [
'resolveComponentFactory',
]);
TestBed.overrideProvider(ComponentFactoryResolver, {useValue: componentFactoryMock});
expect(TestBed.get(ComponentFactoryResolver)).toEqual(componentFactoryMock);
});
});
describe('in NgModules', () => {
it('should support useValue', () => {
TestBed.configureTestingModule({
providers: [{provide: aTok, useValue: 'aValue'}],
});
TestBed.overrideProvider(aTok, {useValue: 'mockValue'});
expect(TestBed.inject(aTok)).toBe('mockValue');
});
it('should support useFactory', () => {
TestBed.configureTestingModule({
providers: [
{provide: 'dep', useValue: 'depValue'},
{provide: aTok, useValue: 'aValue'},
],
});
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: ['dep'],
});
expect(TestBed.inject(aTok)).toBe('mockA: depValue');
});
it('should support @Optional without matches', () => {
TestBed.configureTestingModule({
providers: [{provide: aTok, useValue: 'aValue'}],
});
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new Optional(), 'dep']],
});
expect(TestBed.inject(aTok)).toBe('mockA: null');
});
it('should support Optional with matches', () => {
TestBed.configureTestingModule({
providers: [
{provide: 'dep', useValue: 'depValue'},
{provide: aTok, useValue: 'aValue'},
],
});
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new Optional(), 'dep']],
});
expect(TestBed.inject(aTok)).toBe('mockA: depValue');
});
it('should support SkipSelf', () => {
@NgModule({
providers: [
{provide: aTok, useValue: 'aValue'},
{provide: 'dep', useValue: 'depValue'},
],
})
class MyModule {}
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new SkipSelf(), 'dep']],
});
TestBed.configureTestingModule({
providers: [{provide: 'dep', useValue: 'parentDepValue'}],
});
const compiler = TestBed.inject(Compiler);
const modFactory = compiler.compileModuleSync(MyModule);
expect(modFactory.create(getTestBed()).injector.get(aTok)).toBe('mockA: parentDepValue');
});
it('should keep imported NgModules eager', () => {
let someModule: SomeModule | undefined;
@NgModule()
class SomeModule {
constructor() {
someModule = this;
}
}
TestBed.configureTestingModule({
providers: [{provide: aTok, useValue: 'aValue'}],
imports: [SomeModule],
});
TestBed.overrideProvider(aTok, {useValue: 'mockValue'});
expect(TestBed.inject(aTok)).toBe('mockValue');
expect(someModule).toBeInstanceOf(SomeModule);
});
describe('injecting eager providers into an eager overwritten provider', () => {
@NgModule({
providers: [
{provide: aTok, useFactory: () => 'aValue'},
{provide: bTok, useFactory: () => 'bValue'},
],
})
class MyModule {
// NgModule is eager, which makes all of its deps eager
constructor(@Inject(aTok) a: any, @Inject(bTok) b: any) {}
}
it('should inject providers that were declared before', () => {
TestBed.configureTestingModule({imports: [MyModule]});
TestBed.overrideProvider(bTok, {
useFactory: (a: string) => `mockB: ${a}`,
deps: [aTok],
});
expect(TestBed.inject(bTok)).toBe('mockB: aValue');
});
it('should inject providers that were declared afterwards', () => {
TestBed.configureTestingModule({imports: [MyModule]});
TestBed.overrideProvider(aTok, {
useFactory: (b: string) => `mockA: ${b}`,
deps: [bTok],
});
expect(TestBed.inject(aTok)).toBe('mockA: bValue');
});
});
}); | {
"end_byte": 19926,
"start_byte": 15158,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/testing_public_spec.ts"
} |
angular/packages/platform-browser/test/testing_public_spec.ts_19934_29238 | describe('in Components', () => {
it('should support useValue', () => {
@Component({
template: '',
providers: [{provide: aTok, useValue: 'aValue'}],
standalone: false,
})
class MComp {}
TestBed.overrideProvider(aTok, {useValue: 'mockValue'});
const ctx = TestBed.configureTestingModule({declarations: [MComp]}).createComponent(
MComp,
);
expect(ctx.debugElement.injector.get(aTok)).toBe('mockValue');
});
it('should support useFactory', () => {
@Component({
template: '',
providers: [
{provide: 'dep', useValue: 'depValue'},
{provide: aTok, useValue: 'aValue'},
],
standalone: false,
})
class MyComp {}
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: ['dep'],
});
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get(aTok)).toBe('mockA: depValue');
});
it('should support @Optional without matches', () => {
@Component({
template: '',
providers: [{provide: aTok, useValue: 'aValue'}],
standalone: false,
})
class MyComp {}
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new Optional(), 'dep']],
});
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get(aTok)).toBe('mockA: null');
});
it('should support Optional with matches', () => {
@Component({
template: '',
providers: [
{provide: 'dep', useValue: 'depValue'},
{provide: aTok, useValue: 'aValue'},
],
standalone: false,
})
class MyComp {}
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new Optional(), 'dep']],
});
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get(aTok)).toBe('mockA: depValue');
});
it('should support SkipSelf', () => {
@Directive({
selector: '[myDir]',
providers: [
{provide: aTok, useValue: 'aValue'},
{provide: 'dep', useValue: 'depValue'},
],
standalone: false,
})
class MyDir {}
@Component({
template: '<div myDir></div>',
providers: [{provide: 'dep', useValue: 'parentDepValue'}],
standalone: false,
})
class MyComp {}
TestBed.overrideProvider(aTok, {
useFactory: (dep: any) => `mockA: ${dep}`,
deps: [[new SkipSelf(), 'dep']],
});
const ctx = TestBed.configureTestingModule({
declarations: [MyComp, MyDir],
}).createComponent(MyComp);
expect(ctx.debugElement.children[0].injector.get(aTok)).toBe('mockA: parentDepValue');
});
it('should support multiple providers in a template', () => {
@Directive({
selector: '[myDir1]',
providers: [{provide: aTok, useValue: 'aValue1'}],
standalone: false,
})
class MyDir1 {}
@Directive({
selector: '[myDir2]',
providers: [{provide: aTok, useValue: 'aValue2'}],
standalone: false,
})
class MyDir2 {}
@Component({
template: '<div myDir1></div><div myDir2></div>',
standalone: false,
})
class MyComp {}
TestBed.overrideProvider(aTok, {useValue: 'mockA'});
const ctx = TestBed.configureTestingModule({
declarations: [MyComp, MyDir1, MyDir2],
}).createComponent(MyComp);
expect(ctx.debugElement.children[0].injector.get(aTok)).toBe('mockA');
expect(ctx.debugElement.children[1].injector.get(aTok)).toBe('mockA');
});
describe('injecting eager providers into an eager overwritten provider', () => {
@Component({
template: '',
providers: [
{provide: aTok, useFactory: () => 'aValue'},
{provide: bTok, useFactory: () => 'bValue'},
],
standalone: false,
})
class MyComp {
// Component is eager, which makes all of its deps eager
constructor(@Inject(aTok) a: any, @Inject(bTok) b: any) {}
}
it('should inject providers that were declared before it', () => {
TestBed.overrideProvider(bTok, {
useFactory: (a: string) => `mockB: ${a}`,
deps: [aTok],
});
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get(bTok)).toBe('mockB: aValue');
});
it('should inject providers that were declared after it', () => {
TestBed.overrideProvider(aTok, {
useFactory: (b: string) => `mockA: ${b}`,
deps: [bTok],
});
const ctx = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
expect(ctx.debugElement.injector.get(aTok)).toBe('mockA: bValue');
});
});
});
it('should reset overrides when the testing modules is resetted', () => {
TestBed.overrideProvider(aTok, {useValue: 'mockValue'});
TestBed.resetTestingModule();
TestBed.configureTestingModule({providers: [{provide: aTok, useValue: 'aValue'}]});
expect(TestBed.inject(aTok)).toBe('aValue');
});
});
describe('overrideTemplateUsingTestingModule', () => {
it('should compile the template in the context of the testing module', () => {
@Component({
selector: 'comp',
template: 'a',
standalone: false,
})
class MyComponent {
prop = 'some prop';
}
let testDir: TestDir | undefined;
@Directive({
selector: '[test]',
standalone: false,
})
class TestDir {
constructor() {
testDir = this;
}
@Input('test') test!: string;
}
TestBed.overrideTemplateUsingTestingModule(
MyComponent,
'<div [test]="prop">Hello world!</div>',
);
const fixture = TestBed.configureTestingModule({
declarations: [MyComponent, TestDir],
}).createComponent(MyComponent);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Hello world!');
expect(testDir).toBeInstanceOf(TestDir);
expect(testDir!.test).toBe('some prop');
});
it('should reset overrides when the testing module is resetted', () => {
@Component({
selector: 'comp',
template: 'a',
standalone: false,
})
class MyComponent {}
TestBed.overrideTemplateUsingTestingModule(MyComponent, 'b');
const fixture = TestBed.resetTestingModule()
.configureTestingModule({declarations: [MyComponent]})
.createComponent(MyComponent);
expect(fixture.nativeElement).toHaveText('a');
});
});
describe('setting up the compiler', () => {
describe('providers', () => {
// TODO(alxhub): disable while we figure out how this should work
xit('should use set up providers', fakeAsync(() => {
// Keeping this component inside the test is needed to make sure it's not resolved
// prior to this test, thus having ɵcmp and a reference in resource
// resolution queue. This is done to check external resoution logic in isolation by
// configuring TestBed with the necessary ResourceLoader instance.
@Component({
selector: 'comp',
templateUrl: '/base/angular/packages/platform-browser/test/static_assets/test.html',
standalone: false,
})
class InternalCompWithUrlTemplate {}
const resourceLoaderGet = jasmine
.createSpy('resourceLoaderGet')
.and.returnValue(Promise.resolve('Hello world!'));
TestBed.configureTestingModule({declarations: [InternalCompWithUrlTemplate]});
TestBed.configureCompiler({
providers: [{provide: ResourceLoader, useValue: {get: resourceLoaderGet}}],
});
TestBed.compileComponents();
tick();
const compFixture = TestBed.createComponent(InternalCompWithUrlTemplate);
expect(compFixture.nativeElement).toHaveText('Hello world!');
}));
});
});
});
| {
"end_byte": 29238,
"start_byte": 19934,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/testing_public_spec.ts"
} |
angular/packages/platform-browser/test/testing_public_spec.ts_29242_38157 | escribe('errors', () => {
let originalJasmineIt: (description: string, func: () => void) => jasmine.Spec;
const patchJasmineIt = () => {
let resolve: (result: any) => void;
let reject: (error: any) => void;
const promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
const jasmineEnv = jasmine.getEnv() as any;
originalJasmineIt = jasmineEnv.it;
jasmineEnv.it = (description: string, fn: (done: DoneFn) => void): any => {
const done = <DoneFn>(() => resolve(null));
done.fail = (err) => reject(err);
fn(done);
return null;
};
return promise;
};
const restoreJasmineIt = () => ((jasmine.getEnv() as any).it = originalJasmineIt);
it('should fail when an asynchronous error is thrown', (done) => {
const itPromise = patchJasmineIt();
const barError = new Error('bar');
it('throws an async error', waitForAsync(
inject([], () =>
setTimeout(() => {
throw barError;
}, 0),
),
));
itPromise.then(
() => done.fail('Expected test to fail, but it did not'),
(err) => {
expect(err).toEqual(barError);
done();
},
);
restoreJasmineIt();
});
it('should fail when a returned promise is rejected', (done) => {
const itPromise = patchJasmineIt();
it('should fail with an error from a promise', waitForAsync(
inject([], () => {
let reject: (error: any) => void = undefined!;
const promise = new Promise((_, rej) => (reject = rej));
const p = promise.then(() => expect(1).toEqual(2));
reject('baz');
return p;
}),
));
itPromise.then(
() => done.fail('Expected test to fail, but it did not'),
(err) => {
expect(err.message).toEqual('baz');
done();
},
);
restoreJasmineIt();
});
describe('components', () => {
let resourceLoaderGet: jasmine.Spy;
beforeEach(() => {
resourceLoaderGet = jasmine
.createSpy('resourceLoaderGet')
.and.returnValue(Promise.resolve('Hello world!'));
TestBed.configureCompiler({
providers: [{provide: ResourceLoader, useValue: {get: resourceLoaderGet}}],
});
});
// TODO(alxhub): disable while we figure out how this should work
xit('should report an error for declared components with templateUrl which never call TestBed.compileComponents', () => {
@Component({
selector: 'comp',
templateUrl: '/base/angular/packages/platform-browser/test/static_assets/test.html',
standalone: false,
})
class InlineCompWithUrlTemplate {}
expect(
withModule({declarations: [InlineCompWithUrlTemplate]}, () =>
TestBed.createComponent(InlineCompWithUrlTemplate),
),
).toThrowError(`Component 'InlineCompWithUrlTemplate' is not resolved:
- templateUrl: /base/angular/packages/platform-browser/test/static_assets/test.html
Did you run and wait for 'resolveComponentResources()'?`);
});
});
it('should error on unknown bound properties on custom elements by default', () => {
@Component({
template: '<div [someUnknownProp]="true"></div>',
standalone: false,
})
class ComponentUsingInvalidProperty {}
const spy = spyOn(console, 'error');
withModule({declarations: [ComponentUsingInvalidProperty]}, () => {
const fixture = TestBed.createComponent(ComponentUsingInvalidProperty);
fixture.detectChanges();
})();
expect(spy.calls.mostRecent().args[0]).toMatch(/Can't bind to 'someUnknownProp'/);
});
});
describe('creating components', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
ChildComp,
MyIfComp,
ChildChildComp,
ParentComp,
TestProvidersComp,
TestViewProvidersComp,
],
});
});
it('should instantiate a component with valid DOM', waitForAsync(() => {
const fixture = TestBed.createComponent(ChildComp);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Original Child');
}));
it('should allow changing members of the component', waitForAsync(() => {
const componentFixture = TestBed.createComponent(MyIfComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf()');
componentFixture.componentInstance.showMore = true;
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('MyIf(More)');
}));
it('should override a template', waitForAsync(() => {
TestBed.overrideComponent(ChildComp, {set: {template: '<span>Mock</span>'}});
const componentFixture = TestBed.createComponent(ChildComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Mock');
}));
it('should override a provider', waitForAsync(() => {
TestBed.overrideComponent(TestProvidersComp, {
set: {providers: [{provide: FancyService, useClass: MockFancyService}]},
});
const componentFixture = TestBed.createComponent(TestProvidersComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('injected value: mocked out value');
}));
it('should override a viewProvider', waitForAsync(() => {
TestBed.overrideComponent(TestViewProvidersComp, {
set: {viewProviders: [{provide: FancyService, useClass: MockFancyService}]},
});
const componentFixture = TestBed.createComponent(TestViewProvidersComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('injected value: mocked out value');
}));
});
describe('using alternate components', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MockChildComp, ParentComp],
});
});
it('should override component dependencies', waitForAsync(() => {
const componentFixture = TestBed.createComponent(ParentComp);
componentFixture.detectChanges();
expect(componentFixture.nativeElement).toHaveText('Parent(Mock)');
}));
});
describe('calling override methods after TestBed initialization', () => {
const getExpectedErrorMessage = (methodName: string, methodDescription: string) =>
`Cannot ${methodDescription} when the test module has already been instantiated. Make sure you are not using \`inject\` before \`${methodName}\`.`;
it('should throw if TestBed.overrideProvider is called after TestBed initialization', () => {
TestBed.inject(Injector);
expect(() =>
TestBed.overrideProvider(aTok, {
useValue: 'mockValue',
}),
).toThrowError(getExpectedErrorMessage('overrideProvider', 'override provider'));
});
it('should throw if TestBed.overrideModule is called after TestBed initialization', () => {
@NgModule()
class MyModule {}
TestBed.inject(Injector);
expect(() => TestBed.overrideModule(MyModule, {})).toThrowError(
getExpectedErrorMessage('overrideModule', 'override module metadata'),
);
});
it('should throw if TestBed.overridePipe is called after TestBed initialization', () => {
@Pipe({
name: 'myPipe',
standalone: false,
})
class MyPipe {
transform(value: any) {
return value;
}
}
TestBed.inject(Injector);
expect(() => TestBed.overridePipe(MyPipe, {})).toThrowError(
getExpectedErrorMessage('overridePipe', 'override pipe metadata'),
);
});
it('should throw if TestBed.overrideDirective is called after TestBed initialization', () => {
@Directive()
class MyDirective {}
TestBed.inject(Injector);
expect(() => TestBed.overrideDirective(MyDirective, {})).toThrowError(
getExpectedErrorMessage('overrideDirective', 'override directive metadata'),
);
});
it('should throw if TestBed.overrideTemplateUsingTestingModule is called after TestBed initialization', () => {
@Component({
selector: 'comp',
template: 'a',
standalone: false,
})
class MyComponent {}
TestBed.inject(Injector);
expect(() => TestBed.overrideTemplateUsingTestingModule(MyComponent, 'b')).toThrowError(
/Cannot override template when the test module has already been instantiated/,
);
});
});
it('TransferState re-export can be used as a type and contructor', () => {
const transferState: TransferState = new TransferState();
expect(transferState).toBeDefined();
});
});
| {
"end_byte": 38157,
"start_byte": 29242,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/testing_public_spec.ts"
} |
angular/packages/platform-browser/test/BUILD.bazel_0_1843 | load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
exports_files([
"browser/static_assets/200.html",
"static_assets/test.html",
])
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/platform-browser/index.mjs",
deps = ["//packages/platform-browser"],
)
circular_dependency_test(
name = "testing_circular_deps_test",
entry_point = "angular/packages/platform-browser/testing/index.mjs",
deps = ["//packages/platform-browser/testing"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/common/http",
"//packages/common/http/testing",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/platform-browser/animations",
"//packages/platform-browser/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
js_library(
name = "zone_event_unpatched_init_lib",
srcs = ["dom/events/zone_event_unpatched.init.mjs"],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
bootstrap = [
":zone_event_unpatched_init_lib",
],
static_files = [
":static_assets/test.html",
],
deps = [
":test_lib",
],
)
| {
"end_byte": 1843,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/BUILD.bazel"
} |
angular/packages/platform-browser/test/static_assets/test.html_0_36 | <span>from external template</span>
| {
"end_byte": 36,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/static_assets/test.html"
} |
angular/packages/platform-browser/test/security/dom_sanitization_service_spec.ts_0_684 | /**
* @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 {SecurityContext} from '@angular/core';
import {DomSanitizerImpl} from '@angular/platform-browser/src/security/dom_sanitization_service';
describe('DOM Sanitization Service', () => {
it('accepts resource URL values for resource contexts', () => {
const svc = new DomSanitizerImpl(null);
const resourceUrl = svc.bypassSecurityTrustResourceUrl('http://hello/world');
expect(svc.sanitize(SecurityContext.URL, resourceUrl)).toBe('http://hello/world');
});
});
| {
"end_byte": 684,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/security/dom_sanitization_service_spec.ts"
} |
angular/packages/platform-browser/test/browser/bootstrap_spec.ts_0_3937 | /**
* @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 {animate, style, transition, trigger} from '@angular/animations';
import {DOCUMENT, isPlatformBrowser, ɵgetDOM as getDOM} from '@angular/common';
import {
ANIMATION_MODULE_TYPE,
APP_INITIALIZER,
Compiler,
Component,
createPlatformFactory,
CUSTOM_ELEMENTS_SCHEMA,
Directive,
ErrorHandler,
importProvidersFrom,
Inject,
inject as _inject,
InjectionToken,
Injector,
LOCALE_ID,
NgModule,
NgModuleRef,
NgZone,
OnDestroy,
PLATFORM_ID,
PLATFORM_INITIALIZER,
Provider,
provideZoneChangeDetection,
Sanitizer,
StaticProvider,
Testability,
TestabilityRegistry,
TransferState,
Type,
VERSION,
EnvironmentProviders,
} from '@angular/core';
import {ApplicationRef} from '@angular/core/src/application/application_ref';
import {Console} from '@angular/core/src/console';
import {ComponentRef} from '@angular/core/src/linker/component_factory';
import {
createOrReusePlatformInjector,
destroyPlatform,
providePlatformInitializer,
} from '@angular/core/src/platform/platform';
import {inject, TestBed} from '@angular/core/testing';
import {Log} from '@angular/core/testing/src/testing_internal';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {provideAnimations, provideNoopAnimations} from '@angular/platform-browser/animations';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {bootstrapApplication} from '../../src/browser';
@Component({
selector: 'non-existent',
template: '',
standalone: false,
})
class NonExistentComp {}
@Component({
selector: 'hello-app',
template: '{{greeting}} world!',
standalone: false,
})
class HelloRootCmp {
greeting: string;
constructor() {
this.greeting = 'hello';
}
}
@Component({
selector: 'hello-app-2',
template: '{{greeting}} world, again!',
standalone: false,
})
class HelloRootCmp2 {
greeting: string;
constructor() {
this.greeting = 'hello';
}
}
@Component({
selector: 'hello-app',
template: '',
standalone: false,
})
class HelloRootCmp3 {
appBinding: string;
constructor(@Inject('appBinding') appBinding: string) {
this.appBinding = appBinding;
}
}
@Component({
selector: 'hello-app',
template: '',
standalone: false,
})
class HelloRootCmp4 {
appRef: ApplicationRef;
constructor(@Inject(ApplicationRef) appRef: ApplicationRef) {
this.appRef = appRef;
}
}
@Directive({
selector: 'hello-app',
standalone: false,
})
class HelloRootDirectiveIsNotCmp {}
@Component({
selector: 'hello-app',
template: '',
standalone: false,
})
class HelloOnDestroyTickCmp implements OnDestroy {
appRef: ApplicationRef;
constructor(@Inject(ApplicationRef) appRef: ApplicationRef) {
this.appRef = appRef;
}
ngOnDestroy(): void {
this.appRef.tick();
}
}
@Component({
selector: 'hello-app',
template: '<some-el [someProp]="true">hello world!</some-el>',
standalone: false,
})
class HelloCmpUsingCustomElement {}
class MockConsole {
res: any[][] = [];
error(...s: any[]): void {
this.res.push(s);
}
}
class DummyConsole implements Console {
public warnings: string[] = [];
log(message: string) {}
warn(message: string) {
this.warnings.push(message);
}
}
function bootstrap(
cmpType: any,
providers: Provider[] = [],
platformProviders: StaticProvider[] = [],
imports: Type<any>[] = [],
): Promise<any> {
@NgModule({
imports: [BrowserModule, ...imports],
declarations: [cmpType],
bootstrap: [cmpType],
providers: providers,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
class TestModule {}
return platformBrowserDynamic(platformProviders).bootstrapModule(TestModule);
}
| {
"end_byte": 3937,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/bootstrap_spec.ts"
} |
angular/packages/platform-browser/test/browser/bootstrap_spec.ts_3939_12586 | escribe('bootstrap factory method', () => {
let el: HTMLElement;
let el2: HTMLElement;
let testProviders: Provider[];
let lightDom: HTMLElement;
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
let compilerConsole: DummyConsole;
beforeEach(() => {
TestBed.configureTestingModule({providers: [Log]});
});
beforeEach(inject([DOCUMENT], (doc: any) => {
destroyPlatform();
compilerConsole = new DummyConsole();
testProviders = [{provide: Console, useValue: compilerConsole}];
const oldRoots = doc.querySelectorAll('hello-app,hello-app-2,light-dom-el');
for (let i = 0; i < oldRoots.length; i++) {
getDOM().remove(oldRoots[i]);
}
el = getDOM().createElement('hello-app', doc);
el2 = getDOM().createElement('hello-app-2', doc);
lightDom = getDOM().createElement('light-dom-el', doc);
doc.body.appendChild(el);
doc.body.appendChild(el2);
el.appendChild(lightDom);
lightDom.textContent = 'loading';
}));
afterEach(destroyPlatform);
describe('bootstrapApplication', () => {
const NAME = new InjectionToken<string>('name');
@Component({
standalone: true,
selector: 'hello-app',
template: 'Hello from {{ name }}!',
})
class SimpleComp {
name = 'SimpleComp';
}
@Component({
standalone: true,
selector: 'hello-app-2',
template: 'Hello from {{ name }}!',
})
class SimpleComp2 {
name = 'SimpleComp2';
}
@Component({
standalone: true,
selector: 'hello-app',
template: 'Hello from {{ name }}!',
})
class ComponentWithDeps {
constructor(@Inject(NAME) public name: string) {}
}
@Component({
selector: 'hello-app-2',
template: 'Hello from {{ name }}!',
standalone: false,
})
class NonStandaloneComp {
name = 'NonStandaloneComp';
}
@NgModule({
declarations: [NonStandaloneComp],
})
class NonStandaloneCompModule {}
it('should work for simple standalone components', async () => {
await bootstrapApplication(SimpleComp);
expect(el.innerText).toBe('Hello from SimpleComp!');
});
it('should allow passing providers during the bootstrap', async () => {
const providers = [{provide: NAME, useValue: 'Name via DI'}];
await bootstrapApplication(ComponentWithDeps, {providers});
expect(el.innerText).toBe('Hello from Name via DI!');
});
it('should reuse existing platform', async () => {
const platformProviders = [{provide: NAME, useValue: 'Name via DI (Platform level)'}];
platformBrowserDynamic(platformProviders);
await bootstrapApplication(ComponentWithDeps);
expect(el.innerText).toBe('Hello from Name via DI (Platform level)!');
});
it('should allow bootstrapping multiple apps', async () => {
await bootstrapApplication(SimpleComp);
await bootstrapApplication(SimpleComp2);
expect(el.innerText).toBe('Hello from SimpleComp!');
expect(el2.innerText).toBe('Hello from SimpleComp2!');
});
it('should keep change detection isolated for separately bootstrapped apps', async () => {
const appRef1 = await bootstrapApplication(SimpleComp);
const appRef2 = await bootstrapApplication(SimpleComp2);
expect(el.innerText).toBe('Hello from SimpleComp!');
expect(el2.innerText).toBe('Hello from SimpleComp2!');
// Update name in both components, but trigger change detection only in the first one.
appRef1.components[0].instance.name = 'Updated SimpleComp';
appRef2.components[0].instance.name = 'Updated SimpleComp2';
// Trigger change detection for the first app.
appRef1.tick();
// Expect that the first component content is updated, but the second one remains the same.
expect(el.innerText).toBe('Hello from Updated SimpleComp!');
expect(el2.innerText).toBe('Hello from SimpleComp2!');
// Trigger change detection for the second app.
appRef2.tick();
// Now the second component should be updated as well.
expect(el.innerText).toBe('Hello from Updated SimpleComp!');
expect(el2.innerText).toBe('Hello from Updated SimpleComp2!');
});
it('should allow bootstrapping multiple standalone components within the same app', async () => {
const appRef = await bootstrapApplication(SimpleComp);
appRef.bootstrap(SimpleComp2);
expect(el.innerText).toBe('Hello from SimpleComp!');
expect(el2.innerText).toBe('Hello from SimpleComp2!');
// Update name in both components.
appRef.components[0].instance.name = 'Updated SimpleComp';
appRef.components[1].instance.name = 'Updated SimpleComp2';
// Run change detection for the app.
appRef.tick();
// Expect both components to be updated, since they belong to the same app.
expect(el.innerText).toBe('Hello from Updated SimpleComp!');
expect(el2.innerText).toBe('Hello from Updated SimpleComp2!');
});
it('should allow bootstrapping non-standalone components within the same app', async () => {
const appRef = await bootstrapApplication(SimpleComp);
// ApplicationRef should still allow bootstrapping non-standalone
// components into the same application.
appRef.bootstrap(NonStandaloneComp);
expect(el.innerText).toBe('Hello from SimpleComp!');
expect(el2.innerText).toBe('Hello from NonStandaloneComp!');
// Update name in both components.
appRef.components[0].instance.name = 'Updated SimpleComp';
appRef.components[1].instance.name = 'Updated NonStandaloneComp';
// Run change detection for the app.
appRef.tick();
// Expect both components to be updated, since they belong to the same app.
expect(el.innerText).toBe('Hello from Updated SimpleComp!');
expect(el2.innerText).toBe('Hello from Updated NonStandaloneComp!');
});
it('should throw when trying to bootstrap a non-standalone component', async () => {
const msg =
'NG0907: The NonStandaloneComp component is not marked as standalone, ' +
'but Angular expects to have a standalone component here. Please make sure the ' +
'NonStandaloneComp component has the `standalone: true` flag in the decorator.';
let bootstrapError: string | null = null;
try {
await bootstrapApplication(NonStandaloneComp);
} catch (e) {
bootstrapError = (e as Error).message;
}
expect(bootstrapError).toBe(msg);
});
it('should throw when trying to bootstrap a standalone directive', async () => {
@Directive({
standalone: true,
selector: '[dir]',
})
class StandaloneDirective {}
const msg = //
'NG0906: The StandaloneDirective is not an Angular component, ' +
'make sure it has the `@Component` decorator.';
let bootstrapError: string | null = null;
try {
await bootstrapApplication(StandaloneDirective);
} catch (e) {
bootstrapError = (e as Error).message;
}
expect(bootstrapError).toBe(msg);
});
it('should throw when trying to bootstrap a non-annotated class', async () => {
class NonAnnotatedClass {}
const msg = //
'NG0906: The NonAnnotatedClass is not an Angular component, ' +
'make sure it has the `@Component` decorator.';
let bootstrapError: string | null = null;
try {
await bootstrapApplication(NonAnnotatedClass);
} catch (e) {
bootstrapError = (e as Error).message;
}
expect(bootstrapError).toBe(msg);
});
it('should have the TransferState token available', async () => {
let state: TransferState | undefined;
@Component({
selector: 'hello-app',
standalone: true,
template: '...',
})
class StandaloneComponent {
constructor() {
state = _inject(TransferState);
}
}
await bootstrapApplication(StandaloneComponent);
expect(state).toBeInstanceOf(TransferState);
});
it('should reject the bootstrapApplication promise if an imported module throws', (done) => {
@NgModule()
class ErrorModule {
constructor() {
throw new Error('This error should be in the promise rejection');
}
}
bootstrapApplication(SimpleComp, {
providers: [importProvidersFrom(ErrorModule)],
}).then(
() => done.fail('Expected bootstrap promised to be rejected'),
() => done(),
);
});
| {
"end_byte": 12586,
"start_byte": 3939,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/bootstrap_spec.ts"
} |
angular/packages/platform-browser/test/browser/bootstrap_spec.ts_12592_21150 | escribe('with animations', () => {
@Component({
standalone: true,
selector: 'hello-app',
template:
'<div @myAnimation (@myAnimation.start)="onStart($event)">Hello from AnimationCmp!</div>',
animations: [
trigger('myAnimation', [transition('void => *', [style({opacity: 1}), animate(5)])]),
],
})
class AnimationCmp {
renderer = _inject(ANIMATION_MODULE_TYPE, {optional: true}) ?? 'not found';
startEvent?: {};
onStart(event: {}) {
this.startEvent = event;
}
}
it('should enable animations when using provideAnimations()', async () => {
const appRef = await bootstrapApplication(AnimationCmp, {
providers: [provideAnimations()],
});
const cmp = appRef.components[0].instance;
// Wait until animation is completed.
await new Promise((resolve) => setTimeout(resolve, 10));
expect(cmp.renderer).toBe('BrowserAnimations');
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(el.innerText).toBe('Hello from AnimationCmp!');
});
it('should use noop animations renderer when using provideNoopAnimations()', async () => {
const appRef = await bootstrapApplication(AnimationCmp, {
providers: [provideNoopAnimations()],
});
const cmp = appRef.components[0].instance;
// Wait until animation is completed.
await new Promise((resolve) => setTimeout(resolve, 10));
expect(cmp.renderer).toBe('NoopAnimations');
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(el.innerText).toBe('Hello from AnimationCmp!');
});
});
it('initializes modules inside the NgZone when using `provideZoneChangeDetection`', async () => {
let moduleInitialized = false;
@NgModule({})
class SomeModule {
constructor() {
expect(NgZone.isInAngularZone()).toBe(true);
moduleInitialized = true;
}
}
@Component({
template: '',
selector: 'hello-app',
imports: [SomeModule],
standalone: true,
})
class AnimationCmp {}
await bootstrapApplication(AnimationCmp, {
providers: [provideZoneChangeDetection({eventCoalescing: true})],
});
expect(moduleInitialized).toBe(true);
});
});
it('should throw if bootstrapped Directive is not a Component', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
bootstrap(HelloRootDirectiveIsNotCmp, [{provide: ErrorHandler, useValue: errorHandler}]).catch(
(error: Error) => {
expect(error).toEqual(
new Error(`HelloRootDirectiveIsNotCmp cannot be used as an entry component.`),
);
done();
},
);
});
it('should have the TransferState token available in NgModule bootstrap', async () => {
let state: TransferState | undefined;
@Component({
selector: 'hello-app',
template: '...',
standalone: false,
})
class NonStandaloneComponent {
constructor() {
state = _inject(TransferState);
}
}
await bootstrap(NonStandaloneComponent);
expect(state).toBeInstanceOf(TransferState);
});
it('should retrieve sanitizer', inject([Injector], (injector: Injector) => {
const sanitizer: Sanitizer | null = injector.get(Sanitizer, null);
// We don't want to have sanitizer in DI. We use DI only to overwrite the
// sanitizer, but not for default one. The default one is pulled in by the Ivy
// instructions as needed.
expect(sanitizer).toBe(null);
}));
it('should throw if no element is found', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]).then(
null,
(reason) => {
expect(reason.message).toContain('The selector "non-existent" did not match any elements');
done();
return null;
},
);
});
it('should throw if no provider', async () => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
class IDontExist {}
@Component({
selector: 'cmp',
template: 'Cmp',
standalone: false,
})
class CustomCmp {
constructor(iDontExist: IDontExist) {}
}
@Component({
selector: 'hello-app',
template: '<cmp></cmp>',
standalone: false,
})
class RootCmp {}
@NgModule({declarations: [CustomCmp], exports: [CustomCmp]})
class CustomModule {}
await expectAsync(
bootstrap(RootCmp, [{provide: ErrorHandler, useValue: errorHandler}], [], [CustomModule]),
).toBeRejected();
});
if (getDOM().supportsDOMEvents) {
it('should forward the error to promise when bootstrap fails', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
const refPromise = bootstrap(NonExistentComp, [
{provide: ErrorHandler, useValue: errorHandler},
]);
refPromise.then(null, (reason: any) => {
expect(reason.message).toContain('The selector "non-existent" did not match any elements');
done();
});
});
it('should invoke the default exception handler when bootstrap fails', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
const refPromise = bootstrap(NonExistentComp, [
{provide: ErrorHandler, useValue: errorHandler},
]);
refPromise.then(null, (reason) => {
expect(logger.res[0].join('#')).toContain(
'ERROR#Error: NG05104: The selector "non-existent" did not match any elements',
);
done();
return null;
});
});
}
it('should create an injector promise', async () => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
expect(refPromise).toEqual(jasmine.any(Promise));
await refPromise; // complete component initialization before switching to the next test
});
it('should set platform name to browser', (done) => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
refPromise.then((ref) => {
expect(isPlatformBrowser(ref.injector.get(PLATFORM_ID))).toBe(true);
done();
}, done.fail);
});
it('should display hello world', (done) => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
refPromise.then((ref) => {
expect(el).toHaveText('hello world!');
expect(el.getAttribute('ng-version')).toEqual(VERSION.full);
done();
}, done.fail);
});
it('should throw a descriptive error if BrowserModule is installed again via a lazily loaded module', (done) => {
@NgModule({imports: [BrowserModule]})
class AsyncModule {}
bootstrap(HelloRootCmp, testProviders)
.then((ref: ComponentRef<HelloRootCmp>) => {
const compiler: Compiler = ref.injector.get(Compiler);
return compiler.compileModuleAsync(AsyncModule).then((factory) => {
expect(() => factory.create(ref.injector)).toThrowError(
'NG05100: Providers from the `BrowserModule` have already been loaded. ' +
'If you need access to common directives such as NgIf and NgFor, ' +
'import the `CommonModule` instead.',
);
});
})
.then(
() => done(),
(err) => done.fail(err),
);
});
it('should support multiple calls to bootstrap', (done) => {
const refPromise1 = bootstrap(HelloRootCmp, testProviders);
const refPromise2 = bootstrap(HelloRootCmp2, testProviders);
Promise.all([refPromise1, refPromise2]).then((refs) => {
expect(el).toHaveText('hello world!');
expect(el2).toHaveText('hello world, again!');
done();
}, done.fail);
});
it('should not crash if change detection is invoked when the root component is disposed', (done) => {
bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => {
expect(() => ref.destroy()).not.toThrow();
done();
});
});
| {
"end_byte": 21150,
"start_byte": 12592,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/bootstrap_spec.ts"
} |
angular/packages/platform-browser/test/browser/bootstrap_spec.ts_21154_28485 | t('should unregister change detectors when components are disposed', (done) => {
bootstrap(HelloRootCmp, testProviders).then((ref) => {
const appRef = ref.injector.get(ApplicationRef);
ref.destroy();
expect(() => appRef.tick()).not.toThrow();
done();
}, done.fail);
});
it('should make the provided bindings available to the application component', (done) => {
const refPromise = bootstrap(HelloRootCmp3, [
testProviders,
{provide: 'appBinding', useValue: 'BoundValue'},
]);
refPromise.then((ref) => {
expect(ref.injector.get('appBinding')).toEqual('BoundValue');
done();
}, done.fail);
});
it('should not override locale provided during bootstrap', (done) => {
const refPromise = bootstrap(
HelloRootCmp,
[testProviders],
[{provide: LOCALE_ID, useValue: 'fr-FR'}],
);
refPromise.then((ref) => {
expect(ref.injector.get(LOCALE_ID)).toEqual('fr-FR');
done();
}, done.fail);
});
it('should avoid cyclic dependencies when root component requires Lifecycle through DI', (done) => {
const refPromise = bootstrap(HelloRootCmp4, testProviders);
refPromise.then((ref) => {
const appRef = ref.injector.get(ApplicationRef);
expect(appRef).toBeDefined();
done();
}, done.fail);
});
it('should run platform initializers', (done) => {
inject([Log], (log: Log) => {
const p = createPlatformFactory(platformBrowserDynamic, 'someName', [
{provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init1'), multi: true},
{provide: PLATFORM_INITIALIZER, useValue: log.fn('platform_init2'), multi: true},
])();
@NgModule({
imports: [BrowserModule],
providers: [
{provide: APP_INITIALIZER, useValue: log.fn('app_init1'), multi: true},
{provide: APP_INITIALIZER, useValue: log.fn('app_init2'), multi: true},
],
})
class SomeModule {
ngDoBootstrap() {}
}
expect(log.result()).toEqual('platform_init1; platform_init2');
log.clear();
p.bootstrapModule(SomeModule).then(() => {
expect(log.result()).toEqual('app_init1; app_init2');
done();
}, done.fail);
})();
});
it('should allow provideZoneChangeDetection in bootstrapModule', async () => {
@NgModule({imports: [BrowserModule], providers: [provideZoneChangeDetection()]})
class SomeModule {
ngDoBootstrap() {}
}
await expectAsync(platformBrowserDynamic().bootstrapModule(SomeModule)).toBeResolved();
});
it('should register each application with the testability registry', async () => {
const ngModuleRef1: NgModuleRef<unknown> = await bootstrap(HelloRootCmp, testProviders);
const ngModuleRef2: NgModuleRef<unknown> = await bootstrap(HelloRootCmp2, testProviders);
// The `TestabilityRegistry` is provided in the "platform", so the same instance is available
// to both `NgModuleRef`s and it can be retrieved from any ref (we use the first one).
const registry = ngModuleRef1.injector.get(TestabilityRegistry);
expect(registry.findTestabilityInTree(el)).toEqual(ngModuleRef1.injector.get(Testability));
expect(registry.findTestabilityInTree(el2)).toEqual(ngModuleRef2.injector.get(Testability));
});
it('should allow to pass schemas', (done) => {
bootstrap(HelloCmpUsingCustomElement, testProviders).then(() => {
expect(el).toHaveText('hello world!');
done();
}, done.fail);
});
describe('change detection', () => {
const log: string[] = [];
@Component({
selector: 'hello-app',
template: '<div id="button-a" (click)="onClick()">{{title}}</div>',
standalone: false,
})
class CompA {
title: string = '';
ngDoCheck() {
log.push('CompA:ngDoCheck');
}
onClick() {
this.title = 'CompA';
log.push('CompA:onClick');
}
}
@Component({
selector: 'hello-app-2',
template: '<div id="button-b" (click)="onClick()">{{title}}</div>',
standalone: false,
})
class CompB {
title: string = '';
ngDoCheck() {
log.push('CompB:ngDoCheck');
}
onClick() {
this.title = 'CompB';
log.push('CompB:onClick');
}
}
it('should be triggered for all bootstrapped components in case change happens in one of them', (done) => {
@NgModule({
imports: [BrowserModule],
declarations: [CompA, CompB],
bootstrap: [CompA, CompB],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
class TestModuleA {}
platformBrowserDynamic()
.bootstrapModule(TestModuleA)
.then((ref) => {
log.length = 0;
el.querySelectorAll<HTMLElement>('#button-a')[0].click();
expect(log).toContain('CompA:onClick');
expect(log).toContain('CompA:ngDoCheck');
expect(log).toContain('CompB:ngDoCheck');
log.length = 0;
el2.querySelectorAll<HTMLElement>('#button-b')[0].click();
expect(log).toContain('CompB:onClick');
expect(log).toContain('CompA:ngDoCheck');
expect(log).toContain('CompB:ngDoCheck');
done();
}, done.fail);
});
it('should work in isolation for each component bootstrapped individually', (done) => {
const refPromise1 = bootstrap(CompA);
const refPromise2 = bootstrap(CompB);
Promise.all([refPromise1, refPromise2]).then((refs) => {
log.length = 0;
el.querySelectorAll<HTMLElement>('#button-a')[0].click();
expect(log).toContain('CompA:onClick');
expect(log).toContain('CompA:ngDoCheck');
expect(log).not.toContain('CompB:ngDoCheck');
log.length = 0;
el2.querySelectorAll<HTMLElement>('#button-b')[0].click();
expect(log).toContain('CompB:onClick');
expect(log).toContain('CompB:ngDoCheck');
expect(log).not.toContain('CompA:ngDoCheck');
done();
}, done.fail);
});
});
});
describe('providePlatformInitializer', () => {
beforeEach(() => destroyPlatform());
afterEach(() => destroyPlatform());
it('should call the provided function when platform is initialized', () => {
let initialized = false;
createPlatformInjector([providePlatformInitializer(() => (initialized = true))]);
expect(initialized).toBe(true);
});
it('should be able to inject dependencies', () => {
const TEST_TOKEN = new InjectionToken<string>('TEST_TOKEN');
let injectedValue!: string;
createPlatformInjector([
{provide: TEST_TOKEN, useValue: 'test'},
providePlatformInitializer(() => {
injectedValue = _inject(TEST_TOKEN);
}),
]);
expect(injectedValue).toBe('test');
});
function createPlatformInjector(providers: Array<EnvironmentProviders | Provider>) {
/* TODO: should we change `createOrReusePlatformInjector` type to allow `EnvironmentProviders`?
*/
return createOrReusePlatformInjector(providers as any);
}
});
/**
* Typing tests.
*/
@Component({
template: '',
// @ts-expect-error: `providePlatformInitializer()` should not work with Component.providers, as
// it wouldn't be executed anyway.
providers: [providePlatformInitializer(() => {})],
})
class Test {}
| {
"end_byte": 28485,
"start_byte": 21154,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/bootstrap_spec.ts"
} |
angular/packages/platform-browser/test/browser/title_spec.ts_0_1679 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {Injectable} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {BrowserModule, Title} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('title service', () => {
let doc: Document;
let initialTitle: string;
let titleService: Title;
beforeEach(() => {
doc = getDOM().createHtmlDocument();
initialTitle = doc.title;
titleService = new Title(doc);
});
afterEach(() => {
doc.title = initialTitle;
});
it('should allow reading initial title', () => {
expect(titleService.getTitle()).toEqual(initialTitle);
});
it('should set a title on the injected document', () => {
titleService.setTitle('test title');
expect(doc.title).toEqual('test title');
expect(titleService.getTitle()).toEqual('test title');
});
it('should reset title to empty string if title not provided', () => {
titleService.setTitle(null!);
expect(doc.title).toEqual('');
});
});
describe('integration test', () => {
@Injectable()
class DependsOnTitle {
constructor(public title: Title) {}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BrowserModule],
providers: [DependsOnTitle],
});
});
it('should inject Title service when using BrowserModule', () => {
expect(TestBed.inject(DependsOnTitle).title).toBeInstanceOf(Title);
});
});
| {
"end_byte": 1679,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/title_spec.ts"
} |
angular/packages/platform-browser/test/browser/bootstrap_standalone_spec.ts_0_7787 | /**
* @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,
Inject,
Injectable,
InjectionToken,
NgModule,
NgZone,
PlatformRef,
} from '@angular/core';
import {R3Injector} from '@angular/core/src/di/r3_injector';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {withBody} from '@angular/private/testing';
import {bootstrapApplication, BrowserModule} from '../../src/browser';
describe('bootstrapApplication for standalone components', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
class SilentErrorHandler extends ErrorHandler {
override handleError() {
// the error is already re-thrown by the application ref.
// we don't want to print it, but instead catch it in tests.
}
}
it(
'should create injector where ambient providers shadow explicit providers',
withBody('<test-app></test-app>', async () => {
const testToken = new InjectionToken('test token');
@NgModule({
providers: [{provide: testToken, useValue: 'Ambient'}],
})
class AmbientModule {}
@Component({
selector: 'test-app',
standalone: true,
template: `({{testToken}})`,
imports: [AmbientModule],
})
class StandaloneCmp {
constructor(@Inject(testToken) readonly testToken: String) {}
}
const appRef = await bootstrapApplication(StandaloneCmp, {
providers: [{provide: testToken, useValue: 'Bootstrap'}],
});
appRef.tick();
// make sure that ambient providers "shadow" ones explicitly provided during bootstrap
expect(document.body.textContent).toBe('(Ambient)');
}),
);
it(
'should be able to provide a custom zone implementation in DI',
withBody('<test-app></test-app>', async () => {
@Component({
selector: 'test-app',
standalone: true,
template: ``,
})
class StandaloneCmp {}
class CustomZone extends NoopNgZone {}
const instance = new CustomZone();
const appRef = await bootstrapApplication(StandaloneCmp, {
providers: [{provide: NgZone, useValue: instance}],
});
appRef.tick();
expect(appRef.injector.get(NgZone)).toEqual(instance);
}),
);
/*
This test verifies that ambient providers for the standalone component being bootstrapped
(providers collected from the import graph of a standalone component) are instantiated in a
dedicated standalone injector. As the result we are ending up with the following injectors
hierarchy:
- platform injector (platform specific providers go here);
- application injector (providers specified in the bootstrap options go here);
- standalone injector (ambient providers go here);
*/
it(
'should create a standalone injector for standalone components with ambient providers',
withBody('<test-app></test-app>', async () => {
const ambientToken = new InjectionToken('ambient token');
@NgModule({
providers: [{provide: ambientToken, useValue: 'Only in AmbientNgModule'}],
})
class AmbientModule {}
@Injectable()
class NeedsAmbientProvider {
constructor(@Inject(ambientToken) readonly ambientToken: String) {}
}
@Component({
selector: 'test-app',
template: `({{service.ambientToken}})`,
standalone: true,
imports: [AmbientModule],
})
class StandaloneCmp {
constructor(readonly service: NeedsAmbientProvider) {}
}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}, NeedsAmbientProvider],
});
// we expect the bootstrap process to fail since the "NeedsAmbientProvider" service
// (located in the application injector) can't "see" ambient providers (located in a
// standalone injector that is a child of the application injector).
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain('No provider for InjectionToken ambient token!');
}
}),
);
it(
'should throw if `BrowserModule` is imported in the standalone bootstrap scenario',
withBody('<test-app></test-app>', async () => {
@Component({
selector: 'test-app',
template: '...',
standalone: true,
imports: [BrowserModule],
})
class StandaloneCmp {}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}],
});
// The `bootstrapApplication` already includes the set of providers from the
// `BrowserModule`, so including the `BrowserModule` again will bring duplicate
// providers and we want to avoid it.
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain(
'NG05100: Providers from the `BrowserModule` have already been loaded.',
);
}
}),
);
it(
'should throw if `BrowserModule` is imported indirectly in the standalone bootstrap scenario',
withBody('<test-app></test-app>', async () => {
@NgModule({
imports: [BrowserModule],
})
class SomeDependencyModule {}
@Component({
selector: 'test-app',
template: '...',
standalone: true,
imports: [SomeDependencyModule],
})
class StandaloneCmp {}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}],
});
// The `bootstrapApplication` already includes the set of providers from the
// `BrowserModule`, so including the `BrowserModule` again will bring duplicate
// providers and we want to avoid it.
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain(
'NG05100: Providers from the `BrowserModule` have already been loaded.',
);
}
}),
);
it(
'should trigger an app destroy when a platform is destroyed',
withBody('<test-app></test-app>', async () => {
let compOnDestroyCalled = false;
let serviceOnDestroyCalled = false;
let injectorOnDestroyCalled = false;
@Injectable({providedIn: 'root'})
class ServiceWithOnDestroy {
ngOnDestroy() {
serviceOnDestroyCalled = true;
}
}
@Component({
selector: 'test-app',
standalone: true,
template: 'Hello',
})
class ComponentWithOnDestroy {
constructor(service: ServiceWithOnDestroy) {}
ngOnDestroy() {
compOnDestroyCalled = true;
}
}
const appRef = await bootstrapApplication(ComponentWithOnDestroy);
const injector = (appRef as unknown as {injector: R3Injector}).injector;
injector.onDestroy(() => (injectorOnDestroyCalled = true));
expect(document.body.textContent).toBe('Hello');
const platformRef = injector.get(PlatformRef);
platformRef.destroy();
// Verify the callbacks were invoked.
expect(compOnDestroyCalled).toBe(true);
expect(serviceOnDestroyCalled).toBe(true);
expect(injectorOnDestroyCalled).toBe(true);
// Make sure the DOM has been cleaned up as well.
expect(document.body.textContent).toBe('');
}),
);
});
| {
"end_byte": 7787,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/bootstrap_standalone_spec.ts"
} |
angular/packages/platform-browser/test/browser/meta_spec.ts_0_7487 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {Injectable} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {BrowserModule, Meta} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('Meta service', () => {
let doc: Document;
let metaService: Meta;
let defaultMeta: HTMLMetaElement;
beforeEach(() => {
doc = getDOM().createHtmlDocument();
metaService = new Meta(doc);
defaultMeta = getDOM().createElement('meta', doc) as HTMLMetaElement;
defaultMeta.setAttribute('property', 'fb:app_id');
defaultMeta.setAttribute('content', '123456789');
doc.getElementsByTagName('head')[0].appendChild(defaultMeta);
});
afterEach(() => getDOM().remove(defaultMeta));
it('should return meta tag matching selector', () => {
const actual: HTMLMetaElement = metaService.getTag('property="fb:app_id"')!;
expect(actual).not.toBeNull();
expect(actual.getAttribute('content')).toEqual('123456789');
});
it('should return all meta tags matching selector', () => {
const tag1 = metaService.addTag({name: 'author', content: 'page author'})!;
const tag2 = metaService.addTag({name: 'author', content: 'another page author'})!;
const actual: HTMLMetaElement[] = metaService.getTags('name=author');
expect(actual.length).toEqual(2);
expect(actual[0].getAttribute('content')).toEqual('page author');
expect(actual[1].getAttribute('content')).toEqual('another page author');
// clean up
metaService.removeTagElement(tag1);
metaService.removeTagElement(tag2);
});
it('should return null if meta tag does not exist', () => {
const actual: HTMLMetaElement = metaService.getTag('fake=fake')!;
expect(actual).toBeNull();
});
it('should remove meta tag by the given selector', () => {
const selector = 'name=author';
expect(metaService.getTag(selector)).toBeNull();
metaService.addTag({name: 'author', content: 'page author'});
expect(metaService.getTag(selector)).not.toBeNull();
metaService.removeTag(selector);
expect(metaService.getTag(selector)).toBeNull();
});
it('should remove meta tag by the given element', () => {
const selector = 'name=keywords';
expect(metaService.getTag(selector)).toBeNull();
metaService.addTags([{name: 'keywords', content: 'meta test'}]);
const meta = metaService.getTag(selector)!;
expect(meta).not.toBeNull();
metaService.removeTagElement(meta);
expect(metaService.getTag(selector)).toBeNull();
});
it('should update meta tag matching the given selector', () => {
const selector = 'property="fb:app_id"';
metaService.updateTag({content: '4321'}, selector);
const actual = metaService.getTag(selector);
expect(actual).not.toBeNull();
expect(actual!.getAttribute('content')).toEqual('4321');
});
it('should extract selector from the tag definition', () => {
const selector = 'property="fb:app_id"';
metaService.updateTag({property: 'fb:app_id', content: '666'});
const actual = metaService.getTag(selector);
expect(actual).not.toBeNull();
expect(actual!.getAttribute('content')).toEqual('666');
});
it('should create meta tag if it does not exist', () => {
const selector = 'name="twitter:title"';
metaService.updateTag({name: 'twitter:title', content: 'Content Title'}, selector);
const actual = metaService.getTag(selector)!;
expect(actual).not.toBeNull();
expect(actual.getAttribute('content')).toEqual('Content Title');
// clean up
metaService.removeTagElement(actual);
});
it('should add new meta tag', () => {
const selector = 'name="og:title"';
expect(metaService.getTag(selector)).toBeNull();
metaService.addTag({name: 'og:title', content: 'Content Title'});
const actual = metaService.getTag(selector)!;
expect(actual).not.toBeNull();
expect(actual.getAttribute('content')).toEqual('Content Title');
// clean up
metaService.removeTagElement(actual);
});
it('should add httpEquiv meta tag as http-equiv', () => {
metaService.addTag({httpEquiv: 'refresh', content: '3;url=http://test'});
const actual = metaService.getTag('http-equiv')!;
expect(actual).not.toBeNull();
expect(actual.getAttribute('http-equiv')).toEqual('refresh');
expect(actual.getAttribute('content')).toEqual('3;url=http://test');
// clean up
metaService.removeTagElement(actual);
});
it('should add multiple new meta tags', () => {
const nameSelector = 'name="twitter:title"';
const propertySelector = 'property="og:title"';
expect(metaService.getTag(nameSelector)).toBeNull();
expect(metaService.getTag(propertySelector)).toBeNull();
metaService.addTags([
{name: 'twitter:title', content: 'Content Title'},
{property: 'og:title', content: 'Content Title'},
]);
const twitterMeta = metaService.getTag(nameSelector)!;
const fbMeta = metaService.getTag(propertySelector)!;
expect(twitterMeta).not.toBeNull();
expect(fbMeta).not.toBeNull();
// clean up
metaService.removeTagElement(twitterMeta);
metaService.removeTagElement(fbMeta);
});
it('should not add meta tag if it is already present on the page and has the same attr', () => {
const selector = 'property="fb:app_id"';
expect(metaService.getTags(selector).length).toEqual(1);
metaService.addTag({property: 'fb:app_id', content: '123456789'});
expect(metaService.getTags(selector).length).toEqual(1);
});
it('should not add meta tag if it is already present on the page, even if the first tag with the same name has different other attributes', () => {
metaService.addTag({name: 'description', content: 'aaa'});
metaService.addTag({name: 'description', content: 'bbb'});
metaService.addTag({name: 'description', content: 'aaa'});
metaService.addTag({name: 'description', content: 'bbb'});
expect(metaService.getTags('name="description"').length).toEqual(2);
});
it('should add meta tag if it is already present on the page and but has different attr', () => {
const selector = 'property="fb:app_id"';
expect(metaService.getTags(selector).length).toEqual(1);
const meta = metaService.addTag({property: 'fb:app_id', content: '666'})!;
expect(metaService.getTags(selector).length).toEqual(2);
// clean up
metaService.removeTagElement(meta);
});
it('should add meta tag if it is already present on the page and force true', () => {
const selector = 'property="fb:app_id"';
expect(metaService.getTags(selector).length).toEqual(1);
const meta = metaService.addTag({property: 'fb:app_id', content: '123456789'}, true)!;
expect(metaService.getTags(selector).length).toEqual(2);
// clean up
metaService.removeTagElement(meta);
});
});
describe('integration test', () => {
@Injectable()
class DependsOnMeta {
constructor(public meta: Meta) {}
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BrowserModule],
providers: [DependsOnMeta],
});
});
it('should inject Meta service when using BrowserModule', () =>
expect(TestBed.inject(DependsOnMeta).meta).toBeInstanceOf(Meta));
});
| {
"end_byte": 7487,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/meta_spec.ts"
} |
angular/packages/platform-browser/test/browser/tools/tools_spec.ts_0_1487 | /**
* @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, Injector, ɵglobal as global} from '@angular/core';
import {ComponentRef} from '@angular/core/src/render3';
import {disableDebugTools, enableDebugTools} from '@angular/platform-browser';
import {AngularProfiler} from '../../../src/browser/tools/common_tools';
describe('profiler', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
beforeEach(() => {
enableDebugTools({
injector: Injector.create({
providers: [
{
provide: ApplicationRef,
useValue: jasmine.createSpyObj('ApplicationRef', [
'bootstrap',
'tick',
'attachView',
'detachView',
]),
deps: [],
},
],
}),
} as ComponentRef<any>);
});
afterEach(() => {
disableDebugTools();
});
it('should time change detection', () => {
callNgProfilerTimeChangeDetection();
});
it('should time change detection with recording', () => {
callNgProfilerTimeChangeDetection({'record': true});
});
});
export function callNgProfilerTimeChangeDetection(config?: {record: true}): void {
(global.ng.profiler as AngularProfiler).timeChangeDetection(config);
}
| {
"end_byte": 1487,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/tools/tools_spec.ts"
} |
angular/packages/platform-browser/test/browser/static_assets/200.html_0_11 | <p>hey</p>
| {
"end_byte": 11,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/browser/static_assets/200.html"
} |
angular/packages/platform-browser/test/dom/shared_styles_host_spec.ts_0_4127 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {SharedStylesHost} from '@angular/platform-browser/src/dom/shared_styles_host';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('SharedStylesHost', () => {
let doc: Document;
let ssh: SharedStylesHost;
let someHost: Element;
beforeEach(() => {
doc = getDOM().createHtmlDocument();
doc.title = '';
ssh = new SharedStylesHost(doc, 'app-id');
someHost = getDOM().createElement('div');
});
describe('inline', () => {
it('should add existing styles to new hosts', () => {
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual('<style>a {};</style>');
});
it('should add new styles to hosts', () => {
ssh.addHost(someHost);
ssh.addStyles(['a {};']);
expect(someHost.innerHTML).toEqual('<style>a {};</style>');
});
it('should add styles only once to hosts', () => {
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
ssh.addStyles(['a {};']);
expect(someHost.innerHTML).toEqual('<style>a {};</style>');
});
it('should use the document head as default host', () => {
ssh.addStyles(['a {};', 'b {};']);
expect(doc.head).toHaveText('a {};b {};');
});
it('should remove style nodes on destroy', () => {
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual('<style>a {};</style>');
ssh.ngOnDestroy();
expect(someHost.innerHTML).toEqual('');
});
it(`should add 'nonce' attribute when a nonce value is provided`, () => {
ssh = new SharedStylesHost(doc, 'app-id', '{% nonce %}');
ssh.addStyles(['a {};']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual('<style nonce="{% nonce %}">a {};</style>');
});
});
describe('external', () => {
it('should add existing styles to new hosts', () => {
ssh.addStyles([], ['component-1.css']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual('<link rel="stylesheet" href="component-1.css">');
});
it('should add new styles to hosts', () => {
ssh.addHost(someHost);
ssh.addStyles([], ['component-1.css']);
expect(someHost.innerHTML).toEqual('<link rel="stylesheet" href="component-1.css">');
});
it('should add styles only once to hosts', () => {
ssh.addStyles([], ['component-1.css']);
ssh.addHost(someHost);
ssh.addStyles([], ['component-1.css']);
expect(someHost.innerHTML).toEqual('<link rel="stylesheet" href="component-1.css">');
});
it('should use the document head as default host', () => {
ssh.addStyles([], ['component-1.css', 'component-2.css']);
expect(doc.head.innerHTML).toContain('<link rel="stylesheet" href="component-1.css">');
expect(doc.head.innerHTML).toContain('<link rel="stylesheet" href="component-2.css">');
});
it('should remove style nodes on destroy', () => {
ssh.addStyles([], ['component-1.css']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual('<link rel="stylesheet" href="component-1.css">');
ssh.ngOnDestroy();
expect(someHost.innerHTML).toEqual('');
});
it(`should add 'nonce' attribute when a nonce value is provided`, () => {
ssh = new SharedStylesHost(doc, 'app-id', '{% nonce %}');
ssh.addStyles([], ['component-1.css']);
ssh.addHost(someHost);
expect(someHost.innerHTML).toEqual(
'<link rel="stylesheet" href="component-1.css" nonce="{% nonce %}">',
);
});
it('should keep search parameters of urls', () => {
ssh.addHost(someHost);
ssh.addStyles([], ['component-1.css?ngcomp=ng-app-c123456789']);
expect(someHost.innerHTML).toEqual(
'<link rel="stylesheet" href="component-1.css?ngcomp=ng-app-c123456789">',
);
});
});
});
| {
"end_byte": 4127,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/shared_styles_host_spec.ts"
} |
angular/packages/platform-browser/test/dom/dom_renderer_spec.ts_0_594 | /**
* @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, Renderer2, ViewEncapsulation} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {
NAMESPACE_URIS,
REMOVE_STYLES_ON_COMPONENT_DESTROY,
} from '@angular/platform-browser/src/dom/dom_renderer';
import {expect} from '@angular/platform-browser/testing/src/matchers'; | {
"end_byte": 594,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/dom_renderer_spec.ts"
} |
angular/packages/platform-browser/test/dom/dom_renderer_spec.ts_596_9588 | describe('DefaultDomRendererV2', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
let renderer: Renderer2;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestCmp,
SomeApp,
SomeAppForCleanUp,
CmpEncapsulationEmulated,
CmpEncapsulationNone,
CmpEncapsulationShadow,
],
});
renderer = TestBed.createComponent(TestCmp).componentInstance.renderer;
});
describe('setAttribute', () => {
describe('with namespace', () => {
it('xmlns', () => shouldSetAttributeWithNs('xmlns'));
it('xml', () => shouldSetAttributeWithNs('xml'));
it('svg', () => shouldSetAttributeWithNs('svg'));
it('xhtml', () => shouldSetAttributeWithNs('xhtml'));
it('xlink', () => shouldSetAttributeWithNs('xlink'));
it('unknown', () => {
const div = document.createElement('div');
expect(div.hasAttribute('unknown:name')).toBe(false);
renderer.setAttribute(div, 'name', 'value', 'unknown');
expect(div.getAttribute('unknown:name')).toBe('value');
});
function shouldSetAttributeWithNs(namespace: string): void {
const namespaceUri = NAMESPACE_URIS[namespace];
const div = document.createElement('div');
expect(div.hasAttributeNS(namespaceUri, 'name')).toBe(false);
renderer.setAttribute(div, 'name', 'value', namespace);
expect(div.getAttributeNS(namespaceUri, 'name')).toBe('value');
}
});
});
describe('removeAttribute', () => {
describe('with namespace', () => {
it('xmlns', () => shouldRemoveAttributeWithNs('xmlns'));
it('xml', () => shouldRemoveAttributeWithNs('xml'));
it('svg', () => shouldRemoveAttributeWithNs('svg'));
it('xhtml', () => shouldRemoveAttributeWithNs('xhtml'));
it('xlink', () => shouldRemoveAttributeWithNs('xlink'));
it('unknown', () => {
const div = document.createElement('div');
div.setAttribute('unknown:name', 'value');
expect(div.hasAttribute('unknown:name')).toBe(true);
renderer.removeAttribute(div, 'name', 'unknown');
expect(div.hasAttribute('unknown:name')).toBe(false);
});
function shouldRemoveAttributeWithNs(namespace: string): void {
const namespaceUri = NAMESPACE_URIS[namespace];
const div = document.createElement('div');
div.setAttributeNS(namespaceUri, `${namespace}:name`, 'value');
expect(div.hasAttributeNS(namespaceUri, 'name')).toBe(true);
renderer.removeAttribute(div, 'name', namespace);
expect(div.hasAttributeNS(namespaceUri, 'name')).toBe(false);
}
});
});
describe('removeChild', () => {
it('should not error when removing a child without passing a parent', () => {
const parent = document.createElement('div');
const child = document.createElement('div');
parent.appendChild(child);
renderer.removeChild(null, child);
});
});
it('should allow to style components with emulated encapsulation and no encapsulation inside of components with shadow DOM', () => {
const fixture = TestBed.createComponent(SomeApp);
fixture.detectChanges();
const cmp = fixture.debugElement.query(By.css('cmp-shadow')).nativeElement;
const shadow = cmp.shadowRoot.querySelector('.shadow');
expect(window.getComputedStyle(shadow).color).toEqual('rgb(255, 0, 0)');
const emulated = cmp.shadowRoot.querySelector('.emulated');
expect(window.getComputedStyle(emulated).color).toEqual('rgb(0, 0, 255)');
const none = cmp.shadowRoot.querySelector('.none');
expect(window.getComputedStyle(none).color).toEqual('rgb(0, 255, 0)');
});
it('should be able to append children to a <template> element', () => {
const template = document.createElement('template');
const child = document.createElement('div');
renderer.appendChild(template, child);
expect(child.parentNode).toBe(template.content);
});
it('should be able to insert children before others in a <template> element', () => {
const template = document.createElement('template');
const child = document.createElement('div');
const otherChild = document.createElement('div');
template.content.appendChild(child);
renderer.insertBefore(template, otherChild, child);
expect(otherChild.parentNode).toBe(template.content);
});
describe('should not cleanup styles of destroyed components when `REMOVE_STYLES_ON_COMPONENT_DESTROY` is `false`', () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeAppForCleanUp, CmpEncapsulationEmulated, CmpEncapsulationNone],
providers: [
{
provide: REMOVE_STYLES_ON_COMPONENT_DESTROY,
useValue: false,
},
],
});
});
it('works for components without encapsulation emulated', async () => {
const fixture = TestBed.createComponent(SomeAppForCleanUp);
const compInstance = fixture.componentInstance;
compInstance.showEmulatedComponents = true;
fixture.detectChanges();
// verify style is in DOM
expect(await styleCount(fixture, '.emulated')).toBe(1);
// Remove a single instance of the component.
compInstance.componentOneInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.emulated')).toBe(1);
// Hide all instances of the component
compInstance.componentTwoInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.emulated')).toBe(1);
});
it('works for components without encapsulation none', async () => {
const fixture = TestBed.createComponent(SomeAppForCleanUp);
const compInstance = fixture.componentInstance;
compInstance.showEmulatedComponents = false;
fixture.detectChanges();
// verify style is in DOM
expect(await styleCount(fixture, '.none')).toBe(1);
// Remove a single instance of the component.
compInstance.componentOneInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.none')).toBe(1);
// Hide all instances of the component
compInstance.componentTwoInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.none')).toBe(1);
});
});
describe('should cleanup styles of destroyed components by default', () => {
it('works for components without encapsulation emulated', async () => {
const fixture = TestBed.createComponent(SomeAppForCleanUp);
const compInstance = fixture.componentInstance;
compInstance.showEmulatedComponents = true;
fixture.detectChanges();
// verify style is in DOM
expect(await styleCount(fixture, '.emulated')).toBe(1);
// Remove a single instance of the component.
compInstance.componentOneInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.emulated')).toBe(1);
// Hide all instances of the component
compInstance.componentTwoInstanceHidden = true;
fixture.detectChanges();
// Verify style is not in DOM
expect(await styleCount(fixture, '.emulated')).toBe(0);
});
it('works for components without encapsulation none', async () => {
const fixture = TestBed.createComponent(SomeAppForCleanUp);
const compInstance = fixture.componentInstance;
compInstance.showEmulatedComponents = false;
fixture.detectChanges();
// verify style is in DOM
expect(await styleCount(fixture, '.none')).toBe(1);
// Remove a single instance of the component.
compInstance.componentOneInstanceHidden = true;
fixture.detectChanges();
// Verify style is still in DOM
expect(await styleCount(fixture, '.none')).toBe(1);
// Hide all instances of the component
compInstance.componentTwoInstanceHidden = true;
fixture.detectChanges();
// Verify style is not in DOM
expect(await styleCount(fixture, '.emulated')).toBe(0);
});
});
describe('should support namespaces', () => {
it('should create SVG elements', () => {
expect(
document.createElementNS(NAMESPACE_URIS['svg'], 'math') instanceof SVGElement,
).toBeTrue();
});
it('should create MathML elements', () => {
// MathMLElement is fairly recent and doesn't exist on our Saucelabs test environments
if (typeof MathMLElement !== 'undefined') {
expect(
document.createElementNS(NAMESPACE_URIS['math'], 'math') instanceof MathMLElement,
).toBeTrue();
}
});
});
}); | {
"end_byte": 9588,
"start_byte": 596,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/dom_renderer_spec.ts"
} |
angular/packages/platform-browser/test/dom/dom_renderer_spec.ts_9590_11723 | async function styleCount(
fixture: ComponentFixture<unknown>,
cssContentMatcher: string,
): Promise<number> {
// flush
await new Promise<void>((resolve) => {
setTimeout(() => resolve(), 0);
});
const html = fixture.debugElement.parent?.parent;
const debugElements = html?.queryAll(By.css('style'));
if (!debugElements) {
return 0;
}
return debugElements.filter(({nativeElement}) =>
nativeElement.textContent.includes(cssContentMatcher),
).length;
}
@Component({
selector: 'cmp-emulated',
template: `<div class="emulated"></div>`,
styles: [`.emulated { color: blue; }`],
encapsulation: ViewEncapsulation.Emulated,
standalone: false,
})
class CmpEncapsulationEmulated {}
@Component({
selector: 'cmp-none',
template: `<div class="none"></div>`,
styles: [`.none { color: lime; }`],
encapsulation: ViewEncapsulation.None,
standalone: false,
})
class CmpEncapsulationNone {}
@Component({
selector: 'cmp-shadow',
template: `<div class="shadow"></div><cmp-emulated></cmp-emulated><cmp-none></cmp-none>`,
styles: [`.shadow { color: red; }`],
encapsulation: ViewEncapsulation.ShadowDom,
standalone: false,
})
class CmpEncapsulationShadow {}
@Component({
selector: 'some-app',
template: `
<cmp-shadow></cmp-shadow>
<cmp-emulated></cmp-emulated>
<cmp-none></cmp-none>
`,
standalone: false,
})
export class SomeApp {}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestCmp {
constructor(public renderer: Renderer2) {}
}
@Component({
selector: 'some-app',
template: `
<cmp-emulated *ngIf="!componentOneInstanceHidden && showEmulatedComponents"></cmp-emulated>
<cmp-emulated *ngIf="!componentTwoInstanceHidden && showEmulatedComponents"></cmp-emulated>
<cmp-none *ngIf="!componentOneInstanceHidden && !showEmulatedComponents"></cmp-none>
<cmp-none *ngIf="!componentTwoInstanceHidden && !showEmulatedComponents"></cmp-none>
`,
standalone: false,
})
export class SomeAppForCleanUp {
componentOneInstanceHidden = false;
componentTwoInstanceHidden = false;
showEmulatedComponents = true;
} | {
"end_byte": 11723,
"start_byte": 9590,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/dom_renderer_spec.ts"
} |
angular/packages/platform-browser/test/dom/shadow_dom_spec.ts_0_4591 | /**
* @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, NgModule, ViewEncapsulation} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {BrowserModule} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
describe('ShadowDOM Support', () => {
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
beforeEach(() => {
TestBed.configureTestingModule({imports: [TestModule]});
});
it('should attach and use a shadowRoot when ViewEncapsulation.ShadowDom is set', () => {
const compEl = TestBed.createComponent(ShadowComponent).nativeElement;
expect(compEl.shadowRoot!.textContent).toEqual('Hello World');
});
it('should use the shadow root to encapsulate styles', () => {
const compEl = TestBed.createComponent(StyledShadowComponent).nativeElement;
// Firefox and Chrome return different computed styles. Chrome supports CSS property
// shorthands in the computed style object while Firefox expects explicit CSS properties.
// e.g. we can't use the "border" CSS property for this test as "border" is a shorthand
// property and therefore would not work within Firefox.
expect(window.getComputedStyle(compEl).backgroundColor).toEqual('rgb(0, 0, 0)');
const redDiv = compEl.shadowRoot.querySelector('div.red');
expect(window.getComputedStyle(redDiv).backgroundColor).toEqual('rgb(255, 0, 0)');
});
it('should allow the usage of <slot> elements', () => {
const el = TestBed.createComponent(ShadowSlotComponent).nativeElement;
const projectedContent = document.createTextNode('Hello Slot!');
el.appendChild(projectedContent);
const slot = el.shadowRoot!.querySelector('slot');
expect(slot!.assignedNodes().length).toBe(1);
expect(slot!.assignedNodes()[0].textContent).toBe('Hello Slot!');
});
it('should allow the usage of named <slot> elements', () => {
const el = TestBed.createComponent(ShadowSlotsComponent).nativeElement;
const headerContent = document.createElement('h1');
headerContent.setAttribute('slot', 'header');
headerContent.textContent = 'Header Text!';
const articleContent = document.createElement('span');
articleContent.setAttribute('slot', 'article');
articleContent.textContent = 'Article Text!';
const articleSubcontent = document.createElement('span');
articleSubcontent.setAttribute('slot', 'article');
articleSubcontent.textContent = 'Article Subtext!';
el.appendChild(headerContent);
el.appendChild(articleContent);
el.appendChild(articleSubcontent);
const headerSlot = el.shadowRoot!.querySelector('slot[name=header]') as HTMLSlotElement;
const articleSlot = el.shadowRoot!.querySelector('slot[name=article]') as HTMLSlotElement;
expect(headerSlot!.assignedNodes().length).toBe(1);
expect(headerSlot!.assignedNodes()[0].textContent).toBe('Header Text!');
expect(headerContent.assignedSlot).toBe(headerSlot);
expect(articleSlot!.assignedNodes().length).toBe(2);
expect(articleSlot!.assignedNodes()[0].textContent).toBe('Article Text!');
expect(articleSlot!.assignedNodes()[1].textContent).toBe('Article Subtext!');
expect(articleContent.assignedSlot).toBe(articleSlot);
expect(articleSubcontent.assignedSlot).toBe(articleSlot);
});
});
@Component({
selector: 'shadow-comp',
template: 'Hello World',
encapsulation: ViewEncapsulation.ShadowDom,
standalone: false,
})
class ShadowComponent {}
@Component({
selector: 'styled-shadow-comp',
template: '<div class="red"></div>',
encapsulation: ViewEncapsulation.ShadowDom,
styles: [`:host { background: black; } .red { background: red; }`],
standalone: false,
})
class StyledShadowComponent {}
@Component({
selector: 'shadow-slot-comp',
template: '<slot></slot>',
encapsulation: ViewEncapsulation.ShadowDom,
standalone: false,
})
class ShadowSlotComponent {}
@Component({
selector: 'shadow-slots-comp',
template:
'<header><slot name="header"></slot></header><article><slot name="article"></slot></article>',
encapsulation: ViewEncapsulation.ShadowDom,
standalone: false,
})
class ShadowSlotsComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [ShadowComponent, ShadowSlotComponent, ShadowSlotsComponent, StyledShadowComponent],
})
class TestModule {
ngDoBootstrap() {}
}
| {
"end_byte": 4591,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/shadow_dom_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/hammer_gestures_spec.ts_0_6568 | /**
* @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, NgZone} from '@angular/core';
import {fakeAsync, inject, TestBed, tick} from '@angular/core/testing';
import {EventManager} from '@angular/platform-browser';
import {
HammerGestureConfig,
HammerGesturesPlugin,
} from '@angular/platform-browser/src/dom/events/hammer_gestures';
describe('HammerGesturesPlugin', () => {
let plugin: HammerGesturesPlugin;
let fakeConsole: any;
if (isNode) {
// Jasmine will throw if there are no tests.
it('should pass', () => {});
return;
}
beforeEach(() => {
fakeConsole = {warn: jasmine.createSpy('console.warn')};
});
describe('with no custom loader', () => {
beforeEach(() => {
plugin = new HammerGesturesPlugin(document, new HammerGestureConfig(), fakeConsole);
});
it('should warn user and do nothing when Hammer.js not loaded', () => {
expect(plugin.supports('swipe')).toBe(false);
expect(fakeConsole.warn).toHaveBeenCalledWith(
`The "swipe" event cannot be bound because Hammer.JS is not ` +
`loaded and no custom loader has been specified.`,
);
});
});
describe('with a custom loader', () => {
// Use a fake custom loader for tests, with helper functions to resolve or reject.
let loader: () => Promise<void>;
let resolveLoader: () => void;
let failLoader: () => void;
// Arbitrary element and listener for testing.
let someElement: HTMLDivElement;
let someListener: () => void;
// Keep track of whatever value is in `window.Hammer` before the test so it can be
// restored afterwards so that this test doesn't care whether Hammer is actually loaded.
let originalHammerGlobal: any;
// Fake Hammer instance ("mc") used to test the underlying event registration.
let fakeHammerInstance: {on: jasmine.Spy; off: jasmine.Spy};
// Inject the NgZone so that we can make it available to the plugin through a fake
// EventManager.
let ngZone: NgZone;
beforeEach(inject([NgZone], (z: NgZone) => {
ngZone = z;
}));
let loaderCalled = 0;
let loaderIsCalledInAngularZone: boolean | null = null;
beforeEach(() => {
originalHammerGlobal = (window as any).Hammer;
(window as any).Hammer = undefined;
fakeHammerInstance = {
on: jasmine.createSpy('mc.on'),
off: jasmine.createSpy('mc.off'),
};
loader = () => {
loaderCalled++;
loaderIsCalledInAngularZone = NgZone.isInAngularZone();
return new Promise((resolve, reject) => {
resolveLoader = resolve;
failLoader = reject;
});
};
// Make the hammer config return a fake hammer instance
const hammerConfig = new HammerGestureConfig();
spyOn(hammerConfig, 'buildHammer').and.returnValue(fakeHammerInstance);
plugin = new HammerGesturesPlugin(document, hammerConfig, fakeConsole, loader);
// Use a fake EventManager that has access to the NgZone.
plugin.manager = {getZone: () => ngZone} as EventManager;
someElement = document.createElement('div');
someListener = () => {};
});
afterEach(() => {
loaderCalled = 0;
(window as any).Hammer = originalHammerGlobal;
});
it('should call the loader provider only once', () => {
plugin.addEventListener(someElement, 'swipe', () => {});
plugin.addEventListener(someElement, 'panleft', () => {});
plugin.addEventListener(someElement, 'panright', () => {});
// Ensure that the loader is called only once, because previouly
// it was called the same number of times as `addEventListener` was called.
expect(loaderCalled).toEqual(1);
});
it('should not log a warning when HammerJS is not loaded', () => {
plugin.addEventListener(someElement, 'swipe', () => {});
expect(fakeConsole.warn).not.toHaveBeenCalled();
});
it('should defer registering an event until Hammer is loaded', fakeAsync(() => {
plugin.addEventListener(someElement, 'swipe', someListener);
expect(fakeHammerInstance.on).not.toHaveBeenCalled();
(window as any).Hammer = {};
resolveLoader();
tick();
expect(fakeHammerInstance.on).toHaveBeenCalledWith('swipe', jasmine.any(Function));
}));
it('should cancel registration if an event is removed before being added', fakeAsync(() => {
const deregister = plugin.addEventListener(someElement, 'swipe', someListener);
deregister();
(window as any).Hammer = {};
resolveLoader();
tick();
expect(fakeHammerInstance.on).not.toHaveBeenCalled();
}));
it('should remove a listener after Hammer is loaded', fakeAsync(() => {
const removeListener = plugin.addEventListener(someElement, 'swipe', someListener);
(window as any).Hammer = {};
resolveLoader();
tick();
removeListener();
expect(fakeHammerInstance.off).toHaveBeenCalledWith('swipe', jasmine.any(Function));
}));
it('should log a warning when the loader fails', fakeAsync(() => {
plugin.addEventListener(someElement, 'swipe', () => {});
failLoader();
tick();
expect(fakeConsole.warn).toHaveBeenCalledWith(
`The "swipe" event cannot be bound because the custom Hammer.JS loader failed.`,
);
}));
it('should load a warning if the loader resolves and Hammer is not present', fakeAsync(() => {
plugin.addEventListener(someElement, 'swipe', () => {});
resolveLoader();
tick();
expect(fakeConsole.warn).toHaveBeenCalledWith(
`The custom HAMMER_LOADER completed, but Hammer.JS is not present.`,
);
}));
it('should call the loader outside of the Angular zone', fakeAsync(() => {
const ngZone = TestBed.inject(NgZone);
// Unit tests are being run in a ProxyZone, thus `addEventListener` is called within the
// ProxyZone. In real apps, `addEventListener` is called within the Angular zone; we
// mimic that behaviour by entering the Angular zone.
ngZone.run(() => plugin.addEventListener(someElement, 'swipe', () => {}));
const appRef = TestBed.inject(ApplicationRef);
spyOn(appRef, 'tick');
resolveLoader();
tick();
expect(appRef.tick).not.toHaveBeenCalled();
expect(loaderIsCalledInAngularZone).toEqual(false);
}));
});
});
| {
"end_byte": 6568,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/hammer_gestures_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/key_events_spec.ts_0_7943 | /**
* @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 {KeyEventsPlugin} from '@angular/platform-browser/src/dom/events/key_events';
describe('KeyEventsPlugin', () => {
it('should ignore unrecognized events', () => {
expect(KeyEventsPlugin.parseEventName('keydown')).toEqual(null);
expect(KeyEventsPlugin.parseEventName('keyup')).toEqual(null);
expect(KeyEventsPlugin.parseEventName('keydown.unknownmodifier.enter')).toEqual(null);
expect(KeyEventsPlugin.parseEventName('keyup.unknownmodifier.enter')).toEqual(null);
expect(KeyEventsPlugin.parseEventName('unknownevent.control.shift.enter')).toEqual(null);
expect(KeyEventsPlugin.parseEventName('unknownevent.enter')).toEqual(null);
});
it('should correctly parse event names', () => {
// key with no modifier
expect(KeyEventsPlugin.parseEventName('keydown.enter')).toEqual({
'domEventName': 'keydown',
'fullKey': 'enter',
});
expect(KeyEventsPlugin.parseEventName('keyup.enter')).toEqual({
'domEventName': 'keyup',
'fullKey': 'enter',
});
// key with modifiers:
expect(KeyEventsPlugin.parseEventName('keydown.control.shift.enter')).toEqual({
'domEventName': 'keydown',
'fullKey': 'control.shift.enter',
});
expect(KeyEventsPlugin.parseEventName('keyup.control.shift.enter')).toEqual({
'domEventName': 'keyup',
'fullKey': 'control.shift.enter',
});
// key with modifiers in a different order:
expect(KeyEventsPlugin.parseEventName('keydown.shift.control.enter')).toEqual({
'domEventName': 'keydown',
'fullKey': 'control.shift.enter',
});
expect(KeyEventsPlugin.parseEventName('keyup.shift.control.enter')).toEqual({
'domEventName': 'keyup',
'fullKey': 'control.shift.enter',
});
// key that is also a modifier:
expect(KeyEventsPlugin.parseEventName('keydown.shift.control')).toEqual({
'domEventName': 'keydown',
'fullKey': 'shift.control',
});
expect(KeyEventsPlugin.parseEventName('keyup.shift.control')).toEqual({
'domEventName': 'keyup',
'fullKey': 'shift.control',
});
expect(KeyEventsPlugin.parseEventName('keydown.control.shift')).toEqual({
'domEventName': 'keydown',
'fullKey': 'control.shift',
});
expect(KeyEventsPlugin.parseEventName('keyup.control.shift')).toEqual({
'domEventName': 'keyup',
'fullKey': 'control.shift',
});
// key code ordering
expect(KeyEventsPlugin.parseEventName('keyup.code.control.shift')).toEqual({
'domEventName': 'keyup',
'fullKey': 'code.control.shift',
});
expect(KeyEventsPlugin.parseEventName('keyup.control.code.shift')).toEqual({
'domEventName': 'keyup',
'fullKey': 'code.control.shift',
});
// capitalization gets lowercased
expect(KeyEventsPlugin.parseEventName('keyup.control.code.shift.KeyS')).toEqual({
'domEventName': 'keyup',
'fullKey': 'code.control.shift.keys',
});
// user provided order of `code.` does not matter
expect(KeyEventsPlugin.parseEventName('keyup.control.shift.code.KeyS')).toEqual({
'domEventName': 'keyup',
'fullKey': 'code.control.shift.keys',
});
// except for putting `code` at the end
expect(KeyEventsPlugin.parseEventName('keyup.control.shift.KeyS.code')).toBeNull();
});
it('should alias esc to escape', () => {
expect(KeyEventsPlugin.parseEventName('keyup.control.esc')).toEqual(
KeyEventsPlugin.parseEventName('keyup.control.escape'),
);
expect(KeyEventsPlugin.parseEventName('keyup.control.Esc')).toEqual(
KeyEventsPlugin.parseEventName('keyup.control.escape'),
);
});
it('should match key field', () => {
const baseKeyboardEvent = {
isTrusted: true,
bubbles: true,
cancelBubble: false,
cancelable: true,
composed: true,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
type: 'keydown',
};
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ß', code: 'KeyS', altKey: true}),
'alt.ß',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'S', code: 'KeyS', altKey: true}),
'alt.s',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'F', code: 'KeyF', metaKey: true}),
'meta.f',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ArrowUp', code: 'ArrowUp'}),
'arrowup',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ArrowDown', code: 'ArrowDown'}),
'arrowdown',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'A', code: 'KeyA'}),
'a',
),
).toBeTruthy();
// special characters
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Esc', code: 'Escape'}),
'escape',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: '\x1B', code: 'Escape'}),
'escape',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: '\b', code: 'Backspace'}),
'backspace',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: '\t', code: 'Tab'}),
'tab',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Del', code: 'Delete'}),
'delete',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: '\x7F', code: 'Delete'}),
'delete',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Left', code: 'ArrowLeft'}),
'arrowleft',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Right', code: 'ArrowRight'}),
'arrowright',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Up', code: 'ArrowUp'}),
'arrowup',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Down', code: 'ArrowDown'}),
'arrowdown',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Menu', code: 'ContextMenu'}),
'contextmenu',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Scroll', code: 'ScrollLock'}),
'scrolllock',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Win', code: 'OS'}),
'os',
),
).toBeTruthy();
});
| {
"end_byte": 7943,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/key_events_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/key_events_spec.ts_7947_15401 | ('should match code field', () => {
const baseKeyboardEvent = {
isTrusted: true,
bubbles: true,
cancelBubble: false,
cancelable: true,
composed: true,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
type: 'keydown',
};
// Windows
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 's', code: 'KeyS', altKey: true}),
'code.alt.keys',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 's', code: 'KeyS', altKey: true}),
'alt.s',
),
).toBeTruthy();
// MacOS
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ß', code: 'KeyS', altKey: true}),
'code.alt.keys',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ß', code: 'KeyS', altKey: true}),
'alt.s',
),
).toBeFalsy();
// Arrow Keys
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ArrowUp', code: 'ArrowUp'}),
'code.arrowup',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'ArrowDown', code: 'ArrowDown'}),
'arrowdown',
),
).toBeTruthy();
// Basic key match
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'A', code: 'KeyA'}),
'a',
),
).toBeTruthy();
// Basic code match
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'A', code: 'KeyA'}),
'code.a',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'A', code: 'KeyA'}),
'code.keya',
),
).toBeTruthy();
// basic special key
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Shift', code: 'LeftShift'}),
'code.shift',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, key: 'Shift', code: 'LeftShift'}),
'code.leftshift',
),
).toBeTruthy();
// combination keys with code match
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'AltLeft',
shiftKey: true,
altKey: true,
}),
'code.alt.shift.altleft',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'AltLeft',
shiftKey: true,
altKey: true,
}),
'code.shift.altleft',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Meta',
code: 'MetaLeft',
shiftKey: true,
metaKey: true,
}),
'code.meta.shift.metaleft',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'MetaLeft',
shiftKey: true,
metaKey: true,
}),
'code.shift.meta',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'S',
code: 'KeyS',
shiftKey: true,
metaKey: true,
}),
'code.meta.shift.keys',
),
).toBeTruthy();
// combination keys without code match
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'AltLeft',
shiftKey: true,
altKey: true,
}),
'shift.alt',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Meta',
code: 'MetaLeft',
shiftKey: true,
metaKey: true,
}),
'shift.meta',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'S',
code: 'KeyS',
shiftKey: true,
metaKey: true,
}),
'meta.shift.s',
),
).toBeTruthy();
// OS mismatch
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Meta',
code: 'MetaLeft',
shiftKey: true,
metaKey: true,
}),
'shift.alt',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'AltLeft',
shiftKey: true,
altKey: true,
}),
'shift.meta',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Meta',
code: 'MetaLeft',
shiftKey: true,
metaKey: true,
}),
'code.shift.altleft',
),
).toBeFalsy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: 'Alt',
code: 'AltLeft',
shiftKey: true,
altKey: true,
}),
'code.shift.metaleft',
),
).toBeFalsy();
// special key character cases
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: ' ',
code: 'Space',
shiftKey: false,
altKey: false,
}),
'space',
),
).toBeTruthy();
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {
...baseKeyboardEvent,
key: '.',
code: 'Period',
shiftKey: false,
altKey: false,
}),
'dot',
),
).toBeTruthy();
});
// unidentified key
it('should return false when key is unidentified', () => {
const baseKeyboardEvent = {
isTrusted: true,
bubbles: true,
cancelBubble: false,
cancelable: true,
composed: true,
altKey: false,
ctrlKey: false,
metaKey: false,
shiftKey: false,
type: 'keydown',
};
expect(
KeyEventsPlugin.matchEventFullKeyCode(
new KeyboardEvent('keydown', {...baseKeyboardEvent, shiftKey: false, altKey: false}),
'',
),
).toBeFalsy();
});
});
| {
"end_byte": 15401,
"start_byte": 7947,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/key_events_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/event_manager_spec.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 {ɵgetDOM as getDOM} from '@angular/common';
import {NgZone} from '@angular/core/src/zone/ng_zone';
import {DomEventsPlugin} from '@angular/platform-browser/src/dom/events/dom_events';
import {
EventManager,
EventManagerPlugin,
} from '@angular/platform-browser/src/dom/events/event_manager';
import {createMouseEvent, el} from '../../../testing/src/browser_util';
import {TestBed} from '@angular/core/testing';
(function () {
if (isNode) return;
let domEventPlugin: DomEventsPlugin;
let doc: Document;
let zone: NgZone;
const {runInInjectionContext} = TestBed;
| {
"end_byte": 788,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/event_manager_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/event_manager_spec.ts_792_9815 | escribe('EventManager', () => {
beforeEach(() => {
doc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
zone = new NgZone({});
runInInjectionContext(() => {
domEventPlugin = new DomEventsPlugin(doc);
});
});
it('should delegate event bindings to plugins that are passed in from the most generic one to the most specific one', () => {
const element = el('<div></div>');
const handler = (e: Event) => e;
const plugin = new FakeEventManagerPlugin(doc, ['click']);
const manager = new EventManager([domEventPlugin, plugin], new FakeNgZone());
manager.addEventListener(element, 'click', handler);
expect(plugin.eventHandler['click']).toBe(handler);
});
it('should delegate event bindings to the first plugin supporting the event', () => {
const element = el('<div></div>');
const clickHandler = (e: Event) => e;
const dblClickHandler = (e: Event) => e;
const plugin1 = new FakeEventManagerPlugin(doc, ['dblclick']);
const plugin2 = new FakeEventManagerPlugin(doc, ['click', 'dblclick']);
const manager = new EventManager([plugin2, plugin1], new FakeNgZone());
manager.addEventListener(element, 'click', clickHandler);
manager.addEventListener(element, 'dblclick', dblClickHandler);
expect(plugin2.eventHandler['click']).toBe(clickHandler);
expect(plugin1.eventHandler['dblclick']).toBe(dblClickHandler);
});
it('should throw when no plugin can handle the event', () => {
const element = el('<div></div>');
const plugin = new FakeEventManagerPlugin(doc, ['dblclick']);
const manager = new EventManager([plugin], new FakeNgZone());
expect(() => manager.addEventListener(element, 'click', null!)).toThrowError(
'NG05101: No event manager plugin found for event click',
);
});
it('events are caught when fired from a child', () => {
const element = el('<div><div></div></div>');
// Workaround for https://bugs.webkit.org/show_bug.cgi?id=122755
doc.body.appendChild(element);
const child = element.firstChild as Element;
const dispatchedEvent = createMouseEvent('click');
let receivedEvent: MouseEvent | undefined;
const handler = (e: MouseEvent) => {
receivedEvent = e;
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
manager.addEventListener(element, 'click', handler);
getDOM().dispatchEvent(child, dispatchedEvent);
expect(receivedEvent).toBe(dispatchedEvent);
});
it('should keep zone when addEventListener', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvent: MouseEvent | undefined;
let receivedZone: Zone | undefined;
const handler = (e: MouseEvent) => {
receivedEvent = e;
receivedZone = Zone.current;
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
let remover: Function | undefined;
Zone.root.run(() => {
remover = manager.addEventListener(element, 'click', handler);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvent).toBe(dispatchedEvent);
expect(receivedZone?.name).toBe(Zone.root.name);
receivedEvent = undefined;
remover?.();
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvent).toBe(undefined);
});
it('should keep zone when addEventListener multiple times', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let receivedZones: Zone[] = [];
const handler1 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const handler2 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
let remover1: Function | undefined;
let remover2: Function | undefined;
Zone.root.run(() => {
remover1 = manager.addEventListener(element, 'click', handler1);
});
Zone.root.fork({name: 'test'}).run(() => {
remover2 = manager.addEventListener(element, 'click', handler2);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([dispatchedEvent, dispatchedEvent]);
expect(receivedZones).toEqual([Zone.root.name, 'test']);
receivedEvents = [];
remover1?.();
remover2?.();
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([]);
});
it('should support event.stopImmediatePropagation', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let receivedZones: Zone[] = [];
const handler1 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
e.stopImmediatePropagation();
};
const handler2 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
let remover1: Function | undefined;
let remover2: Function | undefined;
Zone.root.run(() => {
remover1 = manager.addEventListener(element, 'click', handler1);
});
Zone.root.fork({name: 'test'}).run(() => {
remover2 = manager.addEventListener(element, 'click', handler2);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([dispatchedEvent]);
expect(receivedZones).toEqual([Zone.root.name]);
receivedEvents = [];
remover1?.();
remover2?.();
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([]);
});
it('should handle event correctly when one handler remove itself ', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let receivedZones: Zone[] = [];
let remover1: Function | undefined;
let remover2: Function | undefined;
const handler1 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
remover1 && remover1();
};
const handler2 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
Zone.root.run(() => {
remover1 = manager.addEventListener(element, 'click', handler1);
});
Zone.root.fork({name: 'test'}).run(() => {
remover2 = manager.addEventListener(element, 'click', handler2);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([dispatchedEvent, dispatchedEvent]);
expect(receivedZones).toEqual([Zone.root.name, 'test']);
receivedEvents = [];
remover1?.();
remover2?.();
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([]);
});
it('should only add same callback once when addEventListener', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let receivedZones: Zone[] = [];
const handler = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
let remover1: Function | undefined;
let remover2: Function | undefined;
Zone.root.run(() => {
remover1 = manager.addEventListener(element, 'click', handler);
});
Zone.root.fork({name: 'test'}).run(() => {
remover2 = manager.addEventListener(element, 'click', handler);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([dispatchedEvent]);
expect(receivedZones).toEqual([Zone.root.name]);
receivedEvents = [];
remover1?.();
remover2?.();
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([]);
});
| {
"end_byte": 9815,
"start_byte": 792,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/event_manager_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/event_manager_spec.ts_9821_17606 | t('should be able to remove event listener which was added inside of ngZone', () => {
const Zone = (window as any)['Zone'];
const element = el('<div><div></div></div>');
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let receivedZones: Zone[] = [];
const handler1 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const handler2 = (e: MouseEvent) => {
receivedEvents.push(e);
receivedZones.push(Zone.current.name);
};
const manager = new EventManager([domEventPlugin], new FakeNgZone());
let remover1: Function | undefined;
let remover2: Function | undefined;
// handler1 is added in root zone
Zone.root.run(() => {
remover1 = manager.addEventListener(element, 'click', handler1);
});
// handler2 is added in 'angular' zone
Zone.root.fork({name: 'fakeAngularZone', properties: {isAngularZone: true}}).run(() => {
remover2 = manager.addEventListener(element, 'click', handler2);
});
getDOM().dispatchEvent(element, dispatchedEvent);
expect(receivedEvents).toEqual([dispatchedEvent, dispatchedEvent]);
expect(receivedZones).toEqual([Zone.root.name, 'fakeAngularZone']);
receivedEvents = [];
remover1?.();
remover2?.();
getDOM().dispatchEvent(element, dispatchedEvent);
// handler1 and handler2 are added in different zone
// one is angular zone, the other is not
// should still be able to remove them correctly
expect(receivedEvents).toEqual([]);
});
// This test is reliant on `zone_event_unpatched_init.js` and verifies
// that the Zone unpatched event setting applies to the event manager.
it('should run unpatchedEvents handler outside of ngZone', () => {
const element = el('<div><div></div></div>');
const zone = new NgZone({enableLongStackTrace: true});
const manager = new EventManager([domEventPlugin], zone);
let timeoutId: NodeJS.Timeout | null = null;
doc.body.appendChild(element);
// Register the event listener in the Angular zone. If the handler would be
// patched then, the Zone should propagate into the listener callback.
zone.run(() => {
manager.addEventListener(element, 'unpatchedEventManagerTest', () => {
// schedule some timer that would cause the zone to become unstable. if the event
// handler would be patched, `hasPendingMacrotasks` would be `true`.
timeoutId = setTimeout(() => {}, 9999999);
});
});
expect(zone.hasPendingMacrotasks).toBe(false);
getDOM().dispatchEvent(element, createMouseEvent('unpatchedEventManagerTest'));
expect(zone.hasPendingMacrotasks).toBe(false);
expect(timeoutId).not.toBe(null);
// cleanup the DOM by removing the test element we attached earlier.
element.remove();
timeoutId && clearTimeout(timeoutId);
});
it('should only trigger one Change detection when bubbling with shouldCoalesceEventChangeDetection = true', (done: DoneFn) => {
doc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
zone = new NgZone({shouldCoalesceEventChangeDetection: true});
runInInjectionContext(() => {
domEventPlugin = new DomEventsPlugin(doc);
});
const element = el('<div></div>');
const child = el('<div></div>');
element.appendChild(child);
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let stables: boolean[] = [];
const handler = (e: MouseEvent) => {
receivedEvents.push(e);
};
const manager = new EventManager([domEventPlugin], zone);
let removerChild: Function;
let removerParent: Function;
zone.run(() => {
removerChild = manager.addEventListener(child, 'click', handler);
removerParent = manager.addEventListener(element, 'click', handler);
});
zone.onStable.subscribe((isStable: boolean) => {
stables.push(isStable);
});
getDOM().dispatchEvent(child, dispatchedEvent);
requestAnimationFrame(() => {
expect(receivedEvents.length).toBe(2);
expect(stables.length).toBe(1);
removerChild && removerChild();
removerParent && removerParent();
done();
});
});
it('should only trigger one Change detection when bubbling with shouldCoalesceRunChangeDetection = true', (done: DoneFn) => {
doc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
zone = new NgZone({shouldCoalesceRunChangeDetection: true});
runInInjectionContext(() => {
domEventPlugin = new DomEventsPlugin(doc);
});
const element = el('<div></div>');
const child = el('<div></div>');
element.appendChild(child);
doc.body.appendChild(element);
const dispatchedEvent = createMouseEvent('click');
let receivedEvents: MouseEvent[] = [];
let stables: boolean[] = [];
const handler = (e: MouseEvent) => {
receivedEvents.push(e);
};
const manager = new EventManager([domEventPlugin], zone);
let removerChild: Function;
let removerParent: Function;
zone.run(() => {
removerChild = manager.addEventListener(child, 'click', handler);
removerParent = manager.addEventListener(element, 'click', handler);
});
zone.onStable.subscribe((isStable: boolean) => {
stables.push(isStable);
});
getDOM().dispatchEvent(child, dispatchedEvent);
requestAnimationFrame(() => {
expect(receivedEvents.length).toBe(2);
expect(stables.length).toBe(1);
removerChild && removerChild();
removerParent && removerParent();
done();
});
});
it('should not drain micro tasks queue too early with shouldCoalesceEventChangeDetection=true', (done: DoneFn) => {
doc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
zone = new NgZone({shouldCoalesceEventChangeDetection: true});
runInInjectionContext(() => {
domEventPlugin = new DomEventsPlugin(doc);
});
const element = el('<div></div>');
const child = el('<div></div>');
doc.body.appendChild(element);
const dispatchedClickEvent = createMouseEvent('click');
const dispatchedBlurEvent: FocusEvent = getDOM()
.getDefaultDocument()
.createEvent('FocusEvent');
dispatchedBlurEvent.initEvent('blur', true, true);
let logs: string[] = [];
const handler = () => {};
const blurHandler = (e: Event) => {
logs.push('blur');
};
const manager = new EventManager([domEventPlugin], zone);
let removerParent: Function;
let removerChildFocus: Function;
zone.run(() => {
removerParent = manager.addEventListener(element, 'click', handler);
removerChildFocus = manager.addEventListener(child, 'blur', blurHandler);
});
const sub = zone.onStable.subscribe(() => {
sub.unsubscribe();
logs.push('begin');
queueMicrotask(() => {
logs.push('promise resolved');
});
element.appendChild(child);
getDOM().dispatchEvent(child, dispatchedBlurEvent);
logs.push('end');
});
getDOM().dispatchEvent(element, dispatchedClickEvent);
requestAnimationFrame(() => {
expect(logs).toEqual(['begin', 'blur', 'end', 'promise resolved']);
removerParent();
removerChildFocus();
done();
});
});
| {
"end_byte": 17606,
"start_byte": 9821,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/event_manager_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/event_manager_spec.ts_17612_20294 | t('should not drain micro tasks queue too early with shouldCoalesceRunChangeDetection=true', (done: DoneFn) => {
doc = getDOM().supportsDOMEvents ? document : getDOM().createHtmlDocument();
zone = new NgZone({shouldCoalesceRunChangeDetection: true});
runInInjectionContext(() => {
domEventPlugin = new DomEventsPlugin(doc);
});
const element = el('<div></div>');
const child = el('<div></div>');
doc.body.appendChild(element);
const dispatchedClickEvent = createMouseEvent('click');
const dispatchedBlurEvent: FocusEvent = getDOM()
.getDefaultDocument()
.createEvent('FocusEvent');
dispatchedBlurEvent.initEvent('blur', true, true);
let logs: string[] = [];
const handler = () => {};
const blurHandler = (e: Event) => {
logs.push('blur');
};
const manager = new EventManager([domEventPlugin], zone);
let removerParent: Function;
let removerChildFocus: Function;
zone.run(() => {
removerParent = manager.addEventListener(element, 'click', handler);
removerChildFocus = manager.addEventListener(child, 'blur', blurHandler);
});
const sub = zone.onStable.subscribe(() => {
sub.unsubscribe();
logs.push('begin');
queueMicrotask(() => {
logs.push('promise resolved');
});
element.appendChild(child);
getDOM().dispatchEvent(child, dispatchedBlurEvent);
logs.push('end');
});
getDOM().dispatchEvent(element, dispatchedClickEvent);
requestAnimationFrame(() => {
expect(logs).toEqual(['begin', 'blur', 'end', 'promise resolved']);
removerParent && removerParent();
removerChildFocus && removerChildFocus();
done();
});
});
});
})();
/** @internal */
class FakeEventManagerPlugin extends EventManagerPlugin {
eventHandler: {[event: string]: Function} = {};
constructor(
doc: Document,
public supportedEvents: string[],
) {
super(doc);
}
override supports(eventName: string): boolean {
return this.supportedEvents.indexOf(eventName) > -1;
}
override addEventListener(element: Element, eventName: string, handler: Function) {
this.eventHandler[eventName] = handler;
return () => {
delete this.eventHandler[eventName];
};
}
}
class FakeNgZone extends NgZone {
constructor() {
super({enableLongStackTrace: false, shouldCoalesceEventChangeDetection: true});
}
override run<T>(fn: (...args: any[]) => T, applyThis?: any, applyArgs?: any[]): T {
return fn();
}
override runOutsideAngular(fn: Function) {
return fn();
}
}
| {
"end_byte": 20294,
"start_byte": 17612,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/event_manager_spec.ts"
} |
angular/packages/platform-browser/test/dom/events/zone_event_unpatched.init.mjs_0_1046 | /**
* @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
*/
// NOTE: This file affects most of tests in `platform-browser/test`. Make sure to
// not change semantics of Angular that would result in false-positives. If you need
// to change semantics of Angular, please create a separate test BUILD target.
// This file marks the `unpatchedEventManagerTest` event as unpatched. This is not
// strictly needed, but done for a specific test verifying that unpatched events are
// running outside the zone. See `event_manager_spec.ts` and the
// `unpatchedEvents handler outside of ngZone` spec.
export function configureZoneUnpatchedEvent() {
window.__zone_symbol__UNPATCHED_EVENTS = ['unpatchedEventManagerTest'];
}
// Invoke the function as a side-effect. We still expose the function so that it could be
// used e.g. in the Saucelabs legacy-job `test-init.ts` file.
configureZoneUnpatchedEvent();
| {
"end_byte": 1046,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/test/dom/events/zone_event_unpatched.init.mjs"
} |
angular/packages/platform-browser/testing/PACKAGE.md_0_69 | Supplies a testing module for the Angular platform-browser subsystem. | {
"end_byte": 69,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/PACKAGE.md"
} |
angular/packages/platform-browser/testing/BUILD.bazel_0_810 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "testing",
srcs = glob(["**/*.ts"]),
deps = [
"//packages/common/testing",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"@npm//@types/jasmine",
"@npm//rxjs",
],
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-browser_testing_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-browser/testing",
)
| {
"end_byte": 810,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/BUILD.bazel"
} |
angular/packages/platform-browser/testing/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-browser/testing/index.ts"
} |
angular/packages/platform-browser/testing/public_api.ts_0_357 | /**
* @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="jasmine" />
/**
* @module
* @description
* Entry point for all public APIs of this package.
*/
export * from './src/testing';
| {
"end_byte": 357,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/public_api.ts"
} |
angular/packages/platform-browser/testing/src/testing.ts_0_342 | /**
* @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 the platform-browser/testing package.
*/
export * from './browser';
| {
"end_byte": 342,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/src/testing.ts"
} |
angular/packages/platform-browser/testing/src/matchers.ts_0_6496 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {Type} from '@angular/core';
import {ComponentFixture} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {childNodesAsList, hasClass, hasStyle, isCommentNode} from './browser_util';
/**
* Jasmine matchers that check Angular specific conditions.
*
* Note: These matchers will only work in a browser environment.
*/
export interface NgMatchers<T = any> extends jasmine.Matchers<T> {
/**
* Expect the element to have exactly the given text.
*
* @usageNotes
* ### Example
*
* {@example testing/ts/matchers.ts region='toHaveText'}
*/
toHaveText(expected: string): boolean;
/**
* Expect the element to have the given CSS class.
*
* @usageNotes
* ### Example
*
* {@example testing/ts/matchers.ts region='toHaveCssClass'}
*/
toHaveCssClass(expected: string): boolean;
/**
* Expect the element to have the given CSS styles.
*
* @usageNotes
* ### Example
*
* {@example testing/ts/matchers.ts region='toHaveCssStyle'}
*/
toHaveCssStyle(expected: {[k: string]: string} | string): boolean;
/**
* Expect a class to implement the interface of the given class.
*
* @usageNotes
* ### Example
*
* {@example testing/ts/matchers.ts region='toImplement'}
*/
toImplement(expected: any): boolean;
/**
* Expect a component of the given type to show.
*/
toContainComponent(expectedComponentType: Type<any>, expectationFailOutput?: any): boolean;
/**
* Invert the matchers.
*/
not: NgMatchers<T>;
}
/**
* Jasmine matching function with Angular matchers mixed in.
*
* ## Example
*
* {@example testing/ts/matchers.ts region='toHaveText'}
*/
const _expect: <T = any>(actual: T) => NgMatchers<T> = expect as any;
export {_expect as expect};
beforeEach(function () {
jasmine.addMatchers({
toHaveText: function () {
return {
compare: function (actual: any, expectedText: string) {
const actualText = elementText(actual);
return {
pass: actualText == expectedText,
get message() {
return 'Expected ' + actualText + ' to be equal to ' + expectedText;
},
};
},
};
},
toHaveCssClass: function () {
return {compare: buildError(false), negativeCompare: buildError(true)};
function buildError(isNot: boolean) {
return function (actual: any, className: string) {
return {
pass: hasClass(actual, className) == !isNot,
get message() {
return `Expected ${actual.outerHTML} ${
isNot ? 'not ' : ''
}to contain the CSS class "${className}"`;
},
};
};
}
},
toHaveCssStyle: function () {
return {
compare: function (actual: any, styles: {[k: string]: string} | string) {
let allPassed: boolean;
if (typeof styles === 'string') {
allPassed = hasStyle(actual, styles);
} else {
allPassed = Object.keys(styles).length !== 0;
Object.keys(styles).forEach((prop) => {
allPassed = allPassed && hasStyle(actual, prop, styles[prop]);
});
}
return {
pass: allPassed,
get message() {
const expectedValueStr = typeof styles === 'string' ? styles : JSON.stringify(styles);
return `Expected ${actual.outerHTML} ${!allPassed ? ' ' : 'not '}to contain the
CSS ${
typeof styles === 'string' ? 'property' : 'styles'
} "${expectedValueStr}"`;
},
};
},
};
},
toImplement: function () {
return {
compare: function (actualObject: any, expectedInterface: any) {
const intProps = Object.keys(expectedInterface.prototype);
const missedMethods: any[] = [];
intProps.forEach((k) => {
if (!actualObject.constructor.prototype[k]) missedMethods.push(k);
});
return {
pass: missedMethods.length == 0,
get message() {
return (
'Expected ' +
actualObject +
' to have the following methods: ' +
missedMethods.join(', ')
);
},
};
},
};
},
toContainComponent: function () {
return {
compare: function (actualFixture: any, expectedComponentType: Type<any>) {
const failOutput = arguments[2];
const msgFn = (msg: string): string => [msg, failOutput].filter(Boolean).join(', ');
// verify correct actual type
if (!(actualFixture instanceof ComponentFixture)) {
return {
pass: false,
message: msgFn(
`Expected actual to be of type \'ComponentFixture\' [actual=${actualFixture.constructor.name}]`,
),
};
}
const found = !!actualFixture.debugElement.query(By.directive(expectedComponentType));
return found
? {pass: true}
: {pass: false, message: msgFn(`Expected ${expectedComponentType.name} to show`)};
},
};
},
});
});
function elementText(n: any): string {
const hasNodes = (n: any) => {
const children = n.childNodes;
return children && children.length > 0;
};
if (n instanceof Array) {
return n.map(elementText).join('');
}
if (isCommentNode(n)) {
return '';
}
if (getDOM().isElementNode(n)) {
const tagName = (n as Element).tagName;
if (tagName === 'CONTENT') {
return elementText(Array.prototype.slice.apply((<any>n).getDistributedNodes()));
} else if (tagName === 'SLOT') {
return elementText(Array.prototype.slice.apply((<any>n).assignedNodes()));
}
}
if (hasShadowRoot(n)) {
return elementText(childNodesAsList((<any>n).shadowRoot));
}
if (hasNodes(n)) {
return elementText(childNodesAsList(n));
}
return (n as any).textContent;
}
function hasShadowRoot(node: any): boolean {
return node.shadowRoot != null && node instanceof HTMLElement;
}
| {
"end_byte": 6496,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/src/matchers.ts"
} |
angular/packages/platform-browser/testing/src/browser.ts_0_1531 | /**
* @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 {PlatformLocation} from '@angular/common';
import {MockPlatformLocation} from '@angular/common/testing';
import {
APP_ID,
createPlatformFactory,
NgModule,
PLATFORM_INITIALIZER,
platformCore,
StaticProvider,
ɵinternalProvideZoneChangeDetection as internalProvideZoneChangeDetection,
ɵChangeDetectionScheduler as ChangeDetectionScheduler,
ɵChangeDetectionSchedulerImpl as ChangeDetectionSchedulerImpl,
} from '@angular/core';
import {BrowserModule, ɵBrowserDomAdapter as BrowserDomAdapter} from '@angular/platform-browser';
function initBrowserTests() {
BrowserDomAdapter.makeCurrent();
}
const _TEST_BROWSER_PLATFORM_PROVIDERS: StaticProvider[] = [
{provide: PLATFORM_INITIALIZER, useValue: initBrowserTests, multi: true},
];
/**
* Platform for testing
*
* @publicApi
*/
export const platformBrowserTesting = createPlatformFactory(
platformCore,
'browserTesting',
_TEST_BROWSER_PLATFORM_PROVIDERS,
);
/**
* NgModule for testing.
*
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
providers: [
{provide: APP_ID, useValue: 'a'},
internalProvideZoneChangeDetection({}),
{provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl},
{provide: PlatformLocation, useClass: MockPlatformLocation},
],
})
export class BrowserTestingModule {}
| {
"end_byte": 1531,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/src/browser.ts"
} |
angular/packages/platform-browser/testing/src/browser_util.ts_0_4345 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {NgZone} from '@angular/core';
export function dispatchEvent(element: any, eventType: any): Event {
const evt: Event = getDOM().getDefaultDocument().createEvent('Event');
evt.initEvent(eventType, true, true);
getDOM().dispatchEvent(element, evt);
return evt;
}
export function createMouseEvent(eventType: string): MouseEvent {
const evt: MouseEvent = getDOM().getDefaultDocument().createEvent('MouseEvent');
evt.initEvent(eventType, true, true);
return evt;
}
export function el(html: string): HTMLElement {
return <HTMLElement>getContent(createTemplate(html)).firstChild;
}
function getAttributeMap(element: any): Map<string, string> {
const res = new Map<string, string>();
const elAttrs = element.attributes;
for (let i = 0; i < elAttrs.length; i++) {
const attrib = elAttrs.item(i);
res.set(attrib.name, attrib.value);
}
return res;
}
const _selfClosingTags = ['br', 'hr', 'input'];
export function stringifyElement(el: Element): string {
let result = '';
if (getDOM().isElementNode(el)) {
const tagName = el.tagName.toLowerCase();
// Opening tag
result += `<${tagName}`;
// Attributes in an ordered way
const attributeMap = getAttributeMap(el);
const sortedKeys = Array.from(attributeMap.keys()).sort();
for (const key of sortedKeys) {
const lowerCaseKey = key.toLowerCase();
let attValue = attributeMap.get(key);
if (typeof attValue !== 'string') {
result += ` ${lowerCaseKey}`;
} else {
// Browsers order style rules differently. Order them alphabetically for consistency.
if (lowerCaseKey === 'style') {
attValue = attValue
.split(/; ?/)
.filter((s) => !!s)
.sort()
.map((s) => `${s};`)
.join(' ');
}
result += ` ${lowerCaseKey}="${attValue}"`;
}
}
result += '>';
// Children
const childrenRoot = templateAwareRoot(el);
const children = childrenRoot ? childrenRoot.childNodes : [];
for (let j = 0; j < children.length; j++) {
result += stringifyElement(children[j]);
}
// Closing tag
if (_selfClosingTags.indexOf(tagName) == -1) {
result += `</${tagName}>`;
}
} else if (isCommentNode(el)) {
result += `<!--${el.nodeValue}-->`;
} else {
result += el.textContent;
}
return result;
}
export function createNgZone(): NgZone {
return new NgZone({enableLongStackTrace: true, shouldCoalesceEventChangeDetection: false});
}
export function isCommentNode(node: Node): boolean {
return node.nodeType === Node.COMMENT_NODE;
}
export function isTextNode(node: Node): boolean {
return node.nodeType === Node.TEXT_NODE;
}
export function getContent(node: Node): Node {
if ('content' in node) {
return (<any>node).content;
} else {
return node;
}
}
export function templateAwareRoot(el: Node): any {
return getDOM().isElementNode(el) && el.nodeName === 'TEMPLATE' ? getContent(el) : el;
}
export function setCookie(name: string, value: string) {
// document.cookie is magical, assigning into it assigns/overrides one cookie value, but does
// not clear other cookies.
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
}
export function hasStyle(element: any, styleName: string, styleValue?: string | null): boolean {
const value = element.style[styleName] || '';
return styleValue ? value == styleValue : value.length > 0;
}
export function hasClass(element: any, className: string): boolean {
return element.classList.contains(className);
}
export function sortedClassList(element: any): any[] {
return Array.prototype.slice.call(element.classList, 0).sort();
}
export function createTemplate(html: any): HTMLElement {
const t = getDOM().getDefaultDocument().createElement('template');
t.innerHTML = html;
return t;
}
export function childNodesAsList(el: Node): any[] {
const childNodes = el.childNodes;
const res = [];
for (let i = 0; i < childNodes.length; i++) {
res[i] = childNodes[i];
}
return res;
}
| {
"end_byte": 4345,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/testing/src/browser_util.ts"
} |
angular/packages/platform-browser/animations/PACKAGE.md_0_78 | Provides infrastructure for the rendering of animations in supported browsers. | {
"end_byte": 78,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/PACKAGE.md"
} |
angular/packages/platform-browser/animations/BUILD.bazel_0_977 | load("//tools:defaults.bzl", "generate_api_docs", "ng_module", "tsec_test")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "animations",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/animations",
"//packages/animations/browser",
"//packages/common",
"//packages/core",
"//packages/platform-browser",
],
)
tsec_test(
name = "tsec_test",
target = "animations",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-browser_animations_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-browser/animations",
)
| {
"end_byte": 977,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/BUILD.bazel"
} |
angular/packages/platform-browser/animations/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-browser/animations/index.ts"
} |
angular/packages/platform-browser/animations/public_api.ts_0_325 | /**
* @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/animations';
| {
"end_byte": 325,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/public_api.ts"
} |
angular/packages/platform-browser/animations/test/animation_renderer_spec.ts_0_1269 | /**
* @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 {
animate,
AnimationPlayer,
AnimationTriggerMetadata,
style,
transition,
trigger,
} from '@angular/animations';
import {
ɵAnimationEngine as AnimationEngine,
ɵAnimationRendererFactory as AnimationRendererFactory,
} from '@angular/animations/browser';
import {
APP_INITIALIZER,
Component,
destroyPlatform,
importProvidersFrom,
Injectable,
NgModule,
NgZone,
RendererFactory2,
RendererType2,
ViewChild,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {bootstrapApplication} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {
BrowserAnimationsModule,
ɵInjectableAnimationEngine as InjectableAnimationEngine,
} from '@angular/platform-browser/animations';
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
import {DomRendererFactory2} from '@angular/platform-browser/src/dom/dom_renderer';
import {withBody} from '@angular/private/testing';
import {el} from '../../testing/src/browser_util';
( | {
"end_byte": 1269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/test/animation_renderer_spec.ts_1271_10377 | nction () {
if (isNode) return;
describe('AnimationRenderer', () => {
let element: any;
beforeEach(() => {
element = el('<div></div>');
TestBed.configureTestingModule({
providers: [{provide: AnimationEngine, useClass: MockAnimationEngine}],
imports: [BrowserAnimationsModule],
});
});
function makeRenderer(animationTriggers: any[] = []) {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': animationTriggers},
};
return (TestBed.inject(RendererFactory2) as AnimationRendererFactory).createRenderer(
element,
type,
);
}
it("should hook into the engine's insert operations when appending children", () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
const container = el('<div></div>');
renderer.appendChild(container, element);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when inserting a child before another", () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
const container = el('<div></div>');
const element2 = el('<div></div>');
container.appendChild(element2);
renderer.insertBefore(container, element, element2);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when removing children", () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
renderer.removeChild(null, element);
expect(engine.captures['onRemove'].pop()).toEqual([element]);
});
it("should hook into the engine's setProperty call if the property begins with `@`", () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
renderer.setProperty(element, 'prop', 'value');
expect(engine.captures['setProperty']).toBeFalsy();
renderer.setProperty(element, '@prop', 'value');
expect(engine.captures['setProperty'].pop()).toEqual([element, 'prop', 'value']);
});
// https://github.com/angular/angular/issues/32794
it('should support nested animation triggers', () => {
makeRenderer([[trigger('myAnimation', [])]]);
const {triggers} = TestBed.inject(AnimationEngine) as MockAnimationEngine;
expect(triggers.length).toEqual(1);
expect(triggers[0].name).toEqual('myAnimation');
});
describe('listen', () => {
it("should hook into the engine's listen call if the property begins with `@`", () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen(element, 'event', cb);
expect(engine.captures['listen']).toBeFalsy();
renderer.listen(element, '@event.phase', cb);
expect(engine.captures['listen'].pop()).toEqual([element, 'event', 'phase']);
});
it('should resolve the body|document|window nodes given their values as strings as input', () => {
const renderer = makeRenderer();
const engine = TestBed.inject(AnimationEngine) as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen('body', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document.body);
renderer.listen('document', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document);
renderer.listen('window', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(window);
});
});
describe('registering animations', () => {
it('should only create a trigger definition once even if the registered multiple times');
});
describe('flushing animations', () => {
// these tests are only meant to be run within the DOM
if (isNode) return;
it('should flush and fire callbacks when the zone becomes stable', (async) => {
@Component({
selector: 'my-cmp',
template: '<div [@myAnimation]="exp" (@myAnimation.start)="onStart($event)"></div>',
animations: [
trigger('myAnimation', [
transition('* => state', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
event: any;
onStart(event: any) {
this.event = event;
}
}
TestBed.configureTestingModule({
providers: [{provide: AnimationEngine, useClass: InjectableAnimationEngine}],
declarations: [Cmp],
});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'state';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(cmp.event.triggerName).toEqual('myAnimation');
expect(cmp.event.phaseName).toEqual('start');
cmp.event = null;
engine.flush();
expect(cmp.event).toBeFalsy();
async();
});
});
it('should properly insert/remove nodes through the animation renderer that do not contain animations', (async) => {
@Component({
selector: 'my-cmp',
template: '<div #elm *ngIf="exp"></div>',
animations: [
trigger('someAnimation', [
transition('* => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
@ViewChild('elm') public element: any;
}
TestBed.configureTestingModule({
providers: [{provide: AnimationEngine, useClass: InjectableAnimationEngine}],
declarations: [Cmp],
});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
cmp.exp = false;
const element = cmp.element;
expect(element.nativeElement.parentNode).toBeTruthy();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.nativeElement.parentNode).toBeFalsy();
async();
});
});
});
it('should only queue up dom removals if the element itself contains a valid leave animation', () => {
@Component({
selector: 'my-cmp',
template: `
<div #elm1 *ngIf="exp1"></div>
<div #elm2 @animation1 *ngIf="exp2"></div>
<div #elm3 @animation2 *ngIf="exp3"></div>
`,
animations: [
trigger('animation1', [transition('a => b', [])]),
trigger('animation2', [transition(':leave', [])]),
],
standalone: false,
})
class Cmp {
exp1: any = true;
exp2: any = true;
exp3: any = true;
@ViewChild('elm1') public elm1: any;
@ViewChild('elm2') public elm2: any;
@ViewChild('elm3') public elm3: any;
}
TestBed.configureTestingModule({
providers: [{provide: AnimationEngine, useClass: InjectableAnimationEngine}],
declarations: [Cmp],
});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const elm1 = cmp.elm1;
const elm2 = cmp.elm2;
const elm3 = cmp.elm3;
assertHasParent(elm1);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
finishPlayers(engine.players);
cmp.exp1 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp2 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp3 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(1);
});
});
});
| {
"end_byte": 10377,
"start_byte": 1271,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/test/animation_renderer_spec.ts_10381_19908 | cribe('AnimationRendererFactory', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useClass: ExtendedAnimationRendererFactory,
deps: [DomRendererFactory2, AnimationEngine, NgZone],
},
],
imports: [BrowserAnimationsModule],
});
});
it('should provide hooks at the start and end of change detection', () => {
@Component({
selector: 'my-cmp',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [trigger('myAnimation', [])],
standalone: false,
})
class Cmp {
public exp: any;
}
TestBed.configureTestingModule({
providers: [{provide: AnimationEngine, useClass: InjectableAnimationEngine}],
declarations: [Cmp],
});
const renderer = TestBed.inject(RendererFactory2) as ExtendedAnimationRendererFactory;
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
renderer.log = [];
fixture.changeDetectorRef.detectChanges();
expect(renderer.log).toEqual(['begin', 'end']);
renderer.log = [];
fixture.changeDetectorRef.detectChanges();
expect(renderer.log).toEqual(['begin', 'end']);
});
});
describe('destroy', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
// See https://github.com/angular/angular/issues/39955
it(
'should clear bootstrapped component contents when the `BrowserAnimationsModule` is imported',
withBody('<div>before</div><app-root></app-root><div>after</div>', async () => {
@Component({
selector: 'app-root',
template: 'app-root content',
standalone: false,
})
class AppComponent {}
@NgModule({
imports: [BrowserAnimationsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
class AppModule {}
const ngModuleRef = await platformBrowserDynamic().bootstrapModule(AppModule);
const root = document.body.querySelector('app-root')!;
expect(root.textContent).toEqual('app-root content');
expect(document.body.childNodes.length).toEqual(3);
ngModuleRef.destroy();
expect(document.body.querySelector('app-root')).toBeFalsy(); // host element is removed
expect(document.body.childNodes.length).toEqual(2); // other elements are preserved
}),
);
// See https://github.com/angular/angular/issues/45108
it(
'should clear bootstrapped component contents when the animation engine is requested during initialization',
withBody('<div>before</div><app-root></app-root><div>after</div>', async () => {
@Injectable({providedIn: 'root'})
class AppService {
// The `RendererFactory2` is injected here explicitly because we import the
// `BrowserAnimationsModule`. The `RendererFactory2` will be provided with
// `AnimationRendererFactory` which relies on the `AnimationEngine`. We want to ensure
// that `ApplicationRef` is created earlier before the `AnimationEngine`, because
// previously the `AnimationEngine` was created before the `ApplicationRef` (see the
// link above to the original issue). The `ApplicationRef` was created after
// `APP_INITIALIZER` has been run but before the root module is bootstrapped.
constructor(rendererFactory: RendererFactory2) {}
}
@Component({
selector: 'app-root',
template: 'app-root content',
standalone: false,
})
class AppComponent {}
@NgModule({
imports: [BrowserAnimationsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
// The `APP_INITIALIZER` token is requested before the root module is bootstrapped,
// the `useFactory` just injects the `AppService` that injects the
// `RendererFactory2`.
{
provide: APP_INITIALIZER,
useFactory: () => (appService: AppService) => appService,
deps: [AppService],
multi: true,
},
],
})
class AppModule {}
const ngModuleRef = await platformBrowserDynamic().bootstrapModule(AppModule);
const root = document.body.querySelector('app-root')!;
expect(root.textContent).toEqual('app-root content');
expect(document.body.childNodes.length).toEqual(3);
ngModuleRef.destroy();
expect(document.body.querySelector('app-root')).toBeFalsy(); // host element is removed
expect(document.body.childNodes.length).toEqual(2); // other elements are preserved
}),
);
// See https://github.com/angular/angular/issues/45108
it(
'should clear standalone bootstrapped component contents when the animation engine is requested during initialization',
withBody('<div>before</div><app-root></app-root><div>after</div>', async () => {
@Injectable({providedIn: 'root'})
class AppService {
// The `RendererFactory2` is injected here explicitly because we import the
// `BrowserAnimationsModule`. The `RendererFactory2` will be provided with
// `AnimationRendererFactory` which relies on the `AnimationEngine`. We want to ensure
// that `ApplicationRef` is created earlier before the `AnimationEngine`, because
// previously the `AnimationEngine` was created before the `ApplicationRef` (see the
// link above to the original issue). The `ApplicationRef` was created after
// `APP_INITIALIZER` has been run but before the root module is bootstrapped.
constructor(rendererFactory: RendererFactory2) {}
}
@Component({selector: 'app-root', template: 'app-root content', standalone: true})
class AppComponent {}
const appRef = await bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(BrowserAnimationsModule),
// The `APP_INITIALIZER` token is requested before the standalone component is
// bootstrapped, the `useFactory` just injects the `AppService` that injects the
// `RendererFactory2`.
{
provide: APP_INITIALIZER,
useFactory: () => (appService: AppService) => appService,
deps: [AppService],
multi: true,
},
],
});
const root = document.body.querySelector('app-root')!;
expect(root.textContent).toEqual('app-root content');
expect(document.body.childNodes.length).toEqual(3);
appRef.destroy();
expect(document.body.querySelector('app-root')).toBeFalsy(); // host element is removed
expect(document.body.childNodes.length).toEqual(2); // other elements are
}),
);
it(
'should clear bootstrapped component contents when async animations are used',
withBody('<div>before</div><app-root></app-root><div>after</div>', async () => {
@Component({selector: 'app-root', template: 'app-root content', standalone: true})
class AppComponent {}
const appRef = await bootstrapApplication(AppComponent, {
providers: [provideAnimationsAsync()],
});
const root = document.body.querySelector('app-root')!;
expect(root.textContent).toEqual('app-root content');
expect(document.body.childNodes.length).toEqual(3);
appRef.destroy();
expect(document.body.querySelector('app-root')).toBeFalsy(); // host element is removed
expect(document.body.childNodes.length).toEqual(2); // other elements are
}),
);
});
})();
@Injectable()
class MockAnimationEngine extends InjectableAnimationEngine {
captures: {[method: string]: any[]} = {};
triggers: AnimationTriggerMetadata[] = [];
private _capture(name: string, args: any[]) {
const data = (this.captures[name] = this.captures[name] || []);
data.push(args);
}
override registerTrigger(
componentId: string,
namespaceId: string,
hostElement: any,
name: string,
metadata: AnimationTriggerMetadata,
): void {
this.triggers.push(metadata);
}
override onInsert(namespaceId: string, element: any): void {
this._capture('onInsert', [element]);
}
override onRemove(namespaceId: string, element: any, domFn: () => any): void {
this._capture('onRemove', [element]);
}
override process(namespaceId: string, element: any, property: string, value: any): boolean {
this._capture('setProperty', [element, property, value]);
return true;
}
override listen(
namespaceId: string,
element: any,
eventName: string,
eventPhase: string,
callback: (event: any) => any,
): () => void {
// we don't capture the callback here since the renderer wraps it in a zone
this._capture('listen', [element, eventName, eventPhase]);
return () => {};
}
override flush() {}
override destroy(namespaceId: string) {}
}
@Injectable()
class ExtendedAnimationRendererFactory extends AnimationRendererFactory {
public log: string[] = [];
override begin() {
super.begin();
this.log.push('begin');
}
override end() {
super.end();
this.log.push('end');
}
}
f | {
"end_byte": 19908,
"start_byte": 10381,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/test/animation_renderer_spec.ts_19910_20221 | ction assertHasParent(element: any, yes: boolean = true) {
const parent = element.nativeElement.parentNode;
if (yes) {
expect(parent).toBeTruthy();
} else {
expect(parent).toBeFalsy();
}
}
function finishPlayers(players: AnimationPlayer[]) {
players.forEach((player) => player.finish());
}
| {
"end_byte": 20221,
"start_byte": 19910,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/test/BUILD.bazel_0_1254 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/platform-browser/animations/index.mjs",
deps = ["//packages/platform-browser/animations"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/platform-browser/animations",
"//packages/platform-browser/animations/async",
"//packages/platform-browser/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 1254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/BUILD.bazel"
} |
angular/packages/platform-browser/animations/test/noop_animations_module_spec.ts_0_4226 | /**
* @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 {animate, style, transition, trigger} from '@angular/animations';
import {ɵAnimationEngine} from '@angular/animations/browser';
import {Component} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {
BrowserAnimationsModule,
NoopAnimationsModule,
provideNoopAnimations,
} from '@angular/platform-browser/animations';
describe('NoopAnimationsModule', () => {
beforeEach(() => {
TestBed.configureTestingModule({imports: [NoopAnimationsModule]});
});
noopAnimationTests();
});
describe('BrowserAnimationsModule with disableAnimations = true', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [BrowserAnimationsModule.withConfig({disableAnimations: true})],
});
});
noopAnimationTests();
});
describe('provideNoopAnimations()', () => {
beforeEach(() => {
TestBed.configureTestingModule({providers: [provideNoopAnimations()]});
});
noopAnimationTests();
});
function noopAnimationTests() {
it('should flush and fire callbacks when the zone becomes stable', (done) => {
// This test is only meant to be run inside the browser.
if (isNode) {
done();
return;
}
@Component({
selector: 'my-cmp',
template:
'<div [@myAnimation]="exp" (@myAnimation.start)="onStart($event)" (@myAnimation.done)="onDone($event)"></div>',
animations: [
trigger('myAnimation', [
transition('* => state', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
startEvent: any;
doneEvent: any;
onStart(event: any) {
this.startEvent = event;
}
onDone(event: any) {
this.doneEvent = event;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'state';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(cmp.doneEvent.triggerName).toEqual('myAnimation');
expect(cmp.doneEvent.phaseName).toEqual('done');
done();
});
});
it('should handle leave animation callbacks even if the element is destroyed in the process', (async) => {
// This test is only meant to be run inside the browser.
if (isNode) {
async();
return;
}
@Component({
selector: 'my-cmp',
template:
'<div *ngIf="exp" @myAnimation (@myAnimation.start)="onStart($event)" (@myAnimation.done)="onDone($event)"></div>',
animations: [
trigger('myAnimation', [
transition(':leave', [style({'opacity': '0'}), animate(500, style({'opacity': '1'}))]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
startEvent: any;
doneEvent: any;
onStart(event: any) {
this.startEvent = event;
}
onDone(event: any) {
this.doneEvent = event;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(ɵAnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
cmp.startEvent = null;
cmp.doneEvent = null;
cmp.exp = false;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(cmp.startEvent.toState).toEqual('void');
expect(cmp.doneEvent.triggerName).toEqual('myAnimation');
expect(cmp.doneEvent.phaseName).toEqual('done');
expect(cmp.doneEvent.toState).toEqual('void');
async();
});
});
});
}
| {
"end_byte": 4226,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/test/noop_animations_module_spec.ts"
} |
angular/packages/platform-browser/animations/async/PACKAGE.md_0_92 | Provides a lazy loaded infrastructure for the rendering of animations in supported browsers. | {
"end_byte": 92,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/PACKAGE.md"
} |
angular/packages/platform-browser/animations/async/BUILD.bazel_0_1045 | load("//tools:defaults.bzl", "ng_module", "tsec_test")
load("//adev/shared-docs/pipeline/api-gen:generate_api_docs.bzl", "generate_api_docs")
package(default_visibility = ["//visibility:public"])
exports_files(["package.json"])
ng_module(
name = "async",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
deps = [
"//packages/animations",
"//packages/animations/browser",
"//packages/common",
"//packages/core",
"//packages/platform-browser",
],
)
tsec_test(
name = "tsec_test",
target = "async",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]) + ["PACKAGE.md"],
)
generate_api_docs(
name = "platform-browser_animations_async_docs",
srcs = [
":files_for_docgen",
"//packages:common_files_and_deps_for_docs",
],
entry_point = ":index.ts",
module_name = "@angular/platform-browser/animations/async",
)
| {
"end_byte": 1045,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/BUILD.bazel"
} |
angular/packages/platform-browser/animations/async/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-browser/animations/async/index.ts"
} |
angular/packages/platform-browser/animations/async/public_api.ts_0_331 | /**
* @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/async-animations';
| {
"end_byte": 331,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/public_api.ts"
} |
angular/packages/platform-browser/animations/async/test/animation_renderer_spec.ts_0_9386 | /**
* @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 {
animate,
AnimationPlayer,
AnimationTriggerMetadata,
style,
transition,
trigger,
} from '@angular/animations';
import {
ɵAnimationEngine as AnimationEngine,
ɵAnimationRenderer as AnimationRenderer,
ɵAnimationRendererFactory as AnimationRendererFactory,
ɵBaseAnimationRenderer as BaseAnimationRenderer,
} from '@angular/animations/browser';
import {DOCUMENT} from '@angular/common';
import {
afterNextRender,
ANIMATION_MODULE_TYPE,
Component,
inject,
Injectable,
Injector,
NgZone,
RendererFactory2,
RendererType2,
runInInjectionContext,
ViewChild,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {ɵDomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
import {InjectableAnimationEngine} from '@angular/platform-browser/animations/src/providers';
import {el} from '@angular/platform-browser/testing/src/browser_util';
import {
AsyncAnimationRendererFactory,
DynamicDelegationRenderer,
ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN,
} from '../src/async_animation_renderer';
import {provideAnimationsAsync} from '../public_api';
type AnimationBrowserModule = typeof import('@angular/animations/browser');
(function () {
if (isNode) {
it('empty test so jasmine doesnt complain', () => {});
return;
}
describe('AnimationRenderer', () => {
let element: any;
beforeEach(() => {
element = el('<div></div>');
TestBed.configureTestingModule({
providers: [
{
provide: RendererFactory2,
useFactory: (
doc: Document,
renderer: DomRendererFactory2,
zone: NgZone,
engine: MockAnimationEngine,
) => {
const animationModule = {
ɵcreateEngine: (_: 'animations' | 'noop', _2: Document): AnimationEngine => engine,
ɵAnimationEngine: MockAnimationEngine as any,
ɵAnimationRenderer: AnimationRenderer,
ɵBaseAnimationRenderer: BaseAnimationRenderer,
ɵAnimationRendererFactory: AnimationRendererFactory,
} satisfies Partial<AnimationBrowserModule> as AnimationBrowserModule;
return new AsyncAnimationRendererFactory(
doc,
renderer,
zone,
'animations',
Promise.resolve(animationModule),
);
},
deps: [DOCUMENT, DomRendererFactory2, NgZone, AnimationEngine],
},
{provide: ANIMATION_MODULE_TYPE, useValue: 'BrowserAnimations'},
{provide: AnimationEngine, useClass: MockAnimationEngine},
],
});
});
function makeRenderer(animationTriggers: any[] = []): Promise<DynamicDelegationRenderer> {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': animationTriggers},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type);
return (factory as any)._rendererFactoryPromise.then(() => renderer);
}
it("should hook into the engine's insert operations when appending children", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const container = el('<div></div>');
renderer.appendChild(container, element);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when inserting a child before another", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const container = el('<div></div>');
const element2 = el('<div></div>');
container.appendChild(element2);
renderer.insertBefore(container, element, element2);
expect(engine.captures['onInsert'].pop()).toEqual([element]);
});
it("should hook into the engine's insert operations when removing children", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
renderer.removeChild(null, element, false);
expect(engine.captures['onRemove'].pop()).toEqual([element]);
});
it("should hook into the engine's setProperty call if the property begins with `@`", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
renderer.setProperty(element, 'prop', 'value');
expect(engine.captures['setProperty']).toBeFalsy();
renderer.setProperty(element, '@prop', 'value');
expect(engine.captures['setProperty'].pop()).toEqual([element, 'prop', 'value']);
});
// https://github.com/angular/angular/issues/32794
it('should support nested animation triggers', async () => {
const renderer = await makeRenderer([[trigger('myAnimation', [])]]);
const {triggers} = (renderer as any).delegate.engine as MockAnimationEngine;
expect(triggers.length).toEqual(1);
expect(triggers[0].name).toEqual('myAnimation');
});
describe('listen', () => {
it("should hook into the engine's listen call if the property begins with `@`", async () => {
const renderer = await makeRenderer();
const engine = (renderer as any).delegate.engine as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen(element, 'event', cb);
expect(engine.captures['listen']).toBeFalsy();
renderer.listen(element, '@event.phase', cb);
expect(engine.captures['listen'].pop()).toEqual([element, 'event', 'phase']);
});
it('should resolve the body|document|window nodes given their values as strings as input', async () => {
const renderer = await makeRenderer();
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
const cb = (event: any): boolean => {
return true;
};
renderer.listen('body', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document.body);
renderer.listen('document', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(document);
renderer.listen('window', '@event', cb);
expect(engine.captures['listen'].pop()[0]).toBe(window);
});
it('should store animations events passed to the default renderer and register them against the animation renderer', async () => {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': []},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type) as DynamicDelegationRenderer;
const cb = (event: any): boolean => true;
renderer.listen('body', '@event', cb);
renderer.listen('document', '@event', cb);
renderer.listen('window', '@event', cb);
// The animation renderer is not loaded yet
expect((renderer['delegate'] as AnimationRenderer).engine).toBeUndefined();
// This will change the delegate renderer from the default one to the AnimationRenderer
await factory['_rendererFactoryPromise']!.then(() => renderer);
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
expect(engine.captures['listen'][0][0]).toBe(document.body);
expect(engine.captures['listen'][1][0]).toBe(document);
expect(engine.captures['listen'][2][0]).toBe(window);
});
});
it('should store animations properties set on the default renderer and set them also on the animation renderer', async () => {
const type = <RendererType2>{
id: 'id',
encapsulation: null!,
styles: [],
data: {'animation': []},
};
const factory = TestBed.inject(RendererFactory2) as AsyncAnimationRendererFactory;
const renderer = factory.createRenderer(element, type) as DynamicDelegationRenderer;
renderer.setProperty(element, '@openClose', 'closed');
renderer.setProperty(element, '@openClose', 'open');
// The animation renderer is not loaded yet
expect((renderer['delegate'] as AnimationRenderer).engine).toBeUndefined();
// This will change the delegate renderer from the default one to the AnimationRenderer
await factory['_rendererFactoryPromise']!.then(() => renderer);
const engine = (renderer['delegate'] as AnimationRenderer).engine as MockAnimationEngine;
expect(engine.captures['setProperty'][0][2]).toBe('closed');
expect(engine.captures['setProperty'][1][2]).toBe('open');
});
describe('registering animations', () => {
it('should only create a trigger definition once even if the registered multiple times');
});
descr | {
"end_byte": 9386,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/async/test/animation_renderer_spec.ts_9392_17260 | lushing animations', () => {
beforeEach(() => {
TestBed.resetTestingModule();
});
// these tests are only meant to be run within the DOM
if (isNode) return;
it('should flush and fire callbacks when the zone becomes stable', (async) => {
@Component({
selector: 'my-cmp',
template: '<div [@myAnimation]="exp" (@myAnimation.start)="onStart($event)"></div>',
animations: [
trigger('myAnimation', [
transition('* => state', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
event: any;
onStart(event: any) {
this.event = event;
}
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = 'state';
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(cmp.event.triggerName).toEqual('myAnimation');
expect(cmp.event.phaseName).toEqual('start');
cmp.event = null;
engine.flush();
expect(cmp.event).toBeFalsy();
async();
});
});
it('should properly insert/remove nodes through the animation renderer that do not contain animations', (async) => {
@Component({
selector: 'my-cmp',
template: '<div #elm *ngIf="exp"></div>',
animations: [
trigger('someAnimation', [
transition('* => *', [
style({'opacity': '0'}),
animate(500, style({'opacity': '1'})),
]),
]),
],
standalone: false,
})
class Cmp {
exp: any;
@ViewChild('elm') public element: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
cmp.exp = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
cmp.exp = false;
const element = cmp.element;
expect(element.nativeElement.parentNode).toBeTruthy();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.nativeElement.parentNode).toBeFalsy();
async();
});
});
});
it('should only queue up dom removals if the element itself contains a valid leave animation', () => {
@Component({
selector: 'my-cmp',
template: `
<div #elm1 *ngIf="exp1"></div>
<div #elm2 @animation1 *ngIf="exp2"></div>
<div #elm3 @animation2 *ngIf="exp3"></div>
`,
animations: [
trigger('animation1', [transition('a => b', [])]),
trigger('animation2', [transition(':leave', [])]),
],
standalone: false,
})
class Cmp {
exp1: any = true;
exp2: any = true;
exp3: any = true;
@ViewChild('elm1') public elm1: any;
@ViewChild('elm2') public elm2: any;
@ViewChild('elm3') public elm3: any;
}
TestBed.configureTestingModule({declarations: [Cmp]});
const engine = TestBed.inject(AnimationEngine);
const fixture = TestBed.createComponent(Cmp);
const cmp = fixture.componentInstance;
fixture.detectChanges();
const elm1 = cmp.elm1;
const elm2 = cmp.elm2;
const elm3 = cmp.elm3;
assertHasParent(elm1);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
finishPlayers(engine.players);
cmp.exp1 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp2 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(0);
cmp.exp3 = false;
fixture.detectChanges();
assertHasParent(elm1, false);
assertHasParent(elm2, false);
assertHasParent(elm3);
engine.flush();
expect(engine.players.length).toEqual(1);
});
});
describe('custom scheduling', () => {
it('should be able to use a custom loading scheduler', async () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
provideAnimationsAsync(),
{
provide: ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN,
useFactory: () => {
const injector = inject(Injector);
return <T>(loadFn: () => T) => {
return new Promise<T>((res) => {
runInInjectionContext(injector, () => afterNextRender(() => res(loadFn())));
});
};
},
},
],
});
const renderer = await makeRenderer();
expect(renderer).toBeInstanceOf(DynamicDelegationRenderer);
expect(renderer['delegate']).toBeInstanceOf(AnimationRenderer);
});
it('should handle scheduling error', async () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
providers: [
provideAnimationsAsync(),
{
provide: ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN,
useValue: () => {
throw new Error('SchedulingError');
},
},
],
});
try {
await makeRenderer();
} catch (err) {
expect((err as Error).message).toBe('SchedulingError');
}
});
});
});
})();
@Injectable()
class MockAnimationEngine extends InjectableAnimationEngine {
captures: {[method: string]: any[]} = {};
triggers: AnimationTriggerMetadata[] = [];
private _capture(name: string, args: any[]) {
const data = (this.captures[name] = this.captures[name] || []);
data.push(args);
}
override registerTrigger(
componentId: string,
namespaceId: string,
hostElement: any,
name: string,
metadata: AnimationTriggerMetadata,
): void {
this.triggers.push(metadata);
}
override onInsert(namespaceId: string, element: any): void {
this._capture('onInsert', [element]);
}
override onRemove(namespaceId: string, element: any, domFn: () => any): void {
this._capture('onRemove', [element]);
}
override process(namespaceId: string, element: any, property: string, value: any): boolean {
this._capture('setProperty', [element, property, value]);
return true;
}
override listen(
namespaceId: string,
element: any,
eventName: string,
eventPhase: string,
callback: (event: any) => any,
): () => void {
// we don't capture the callback here since the renderer wraps it in a zone
this._capture('listen', [element, eventName, eventPhase]);
return () => {};
}
override flush() {}
override destroy(namespaceId: string) {}
}
function assertHasParent(element: any, yes: boolean = true) {
const parent = element.nativeElement.parentNode;
if (yes) {
expect(parent).toBeTruthy();
} else {
expect(parent).toBeFalsy();
}
}
function finishPlayers(players: AnimationPlayer[]) {
players.forEach((player) => player.finish());
}
| {
"end_byte": 17260,
"start_byte": 9392,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/test/animation_renderer_spec.ts"
} |
angular/packages/platform-browser/animations/async/test/BUILD.bazel_0_1254 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test")
circular_dependency_test(
name = "circular_deps_test",
entry_point = "angular/packages/platform-browser/animations/index.mjs",
deps = ["//packages/platform-browser/animations"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/animations",
"//packages/animations/browser",
"//packages/animations/browser/testing",
"//packages/common",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/platform-browser",
"//packages/platform-browser-dynamic",
"//packages/platform-browser/animations",
"//packages/platform-browser/animations/async",
"//packages/platform-browser/testing",
"//packages/private/testing",
"@npm//rxjs",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
],
)
karma_web_test_suite(
name = "test_web",
deps = [
":test_lib",
],
)
| {
"end_byte": 1254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/test/BUILD.bazel"
} |
angular/packages/platform-browser/animations/async/src/async-animations.ts_0_397 | /**
* @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 animation APIs of the animation browser package.
*/
export {provideAnimationsAsync} from './providers';
export * from './private_export';
| {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/src/async-animations.ts"
} |
angular/packages/platform-browser/animations/async/src/private_export.ts_0_360 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
AsyncAnimationRendererFactory as ɵAsyncAnimationRendererFactory,
ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN,
} from './async_animation_renderer';
| {
"end_byte": 360,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/src/private_export.ts"
} |
angular/packages/platform-browser/animations/async/src/providers.ts_0_2105 | /**
* @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 {
ANIMATION_MODULE_TYPE,
EnvironmentProviders,
makeEnvironmentProviders,
NgZone,
RendererFactory2,
ɵperformanceMarkFeature as performanceMarkFeature,
InjectionToken,
} from '@angular/core';
import {ɵDomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
import {AsyncAnimationRendererFactory} from './async_animation_renderer';
/**
* Returns the set of dependency-injection providers
* to enable animations in an application. See [animations guide](guide/animations)
* to learn more about animations in Angular.
*
* When you use this function instead of the eager `provideAnimations()`, animations won't be
* rendered until the renderer is loaded.
*
* @usageNotes
*
* The function is useful when you want to enable animations in an application
* bootstrapped using the `bootstrapApplication` function. In this scenario there
* is no need to import the `BrowserAnimationsModule` NgModule at all, just add
* providers returned by this function to the `providers` list as show below.
*
* ```typescript
* bootstrapApplication(RootComponent, {
* providers: [
* provideAnimationsAsync()
* ]
* });
* ```
*
* @param type pass `'noop'` as argument to disable animations.
*
* @publicApi
*/
export function provideAnimationsAsync(
type: 'animations' | 'noop' = 'animations',
): EnvironmentProviders {
performanceMarkFeature('NgAsyncAnimations');
return makeEnvironmentProviders([
{
provide: RendererFactory2,
useFactory: (doc: Document, renderer: DomRendererFactory2, zone: NgZone) => {
return new AsyncAnimationRendererFactory(doc, renderer, zone, type);
},
deps: [DOCUMENT, DomRendererFactory2, NgZone],
},
{
provide: ANIMATION_MODULE_TYPE,
useValue: type === 'noop' ? 'NoopAnimations' : 'BrowserAnimations',
},
]);
}
| {
"end_byte": 2105,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/src/providers.ts"
} |
angular/packages/platform-browser/animations/async/src/async_animation_renderer.ts_0_6132 | /**
* @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 {
ɵAnimationEngine as AnimationEngine,
ɵAnimationRenderer as AnimationRenderer,
ɵAnimationRendererFactory as AnimationRendererFactory,
} from '@angular/animations/browser';
import {
inject,
Injectable,
NgZone,
OnDestroy,
Renderer2,
RendererFactory2,
RendererStyleFlags2,
RendererType2,
ɵAnimationRendererType as AnimationRendererType,
ɵChangeDetectionScheduler as ChangeDetectionScheduler,
ɵNotificationSource as NotificationSource,
ɵRuntimeError as RuntimeError,
Injector,
InjectionToken,
} from '@angular/core';
import {ɵRuntimeErrorCode as RuntimeErrorCode} from '@angular/platform-browser';
const ANIMATION_PREFIX = '@';
@Injectable()
export class AsyncAnimationRendererFactory implements OnDestroy, RendererFactory2 {
private _rendererFactoryPromise: Promise<AnimationRendererFactory> | null = null;
private readonly scheduler = inject(ChangeDetectionScheduler, {optional: true});
private readonly loadingSchedulerFn = inject(ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN, {
optional: true,
});
private _engine?: AnimationEngine;
/**
*
* @param moduleImpl allows to provide a mock implmentation (or will load the animation module)
*/
constructor(
private doc: Document,
private delegate: RendererFactory2,
private zone: NgZone,
private animationType: 'animations' | 'noop',
private moduleImpl?: Promise<{
ɵcreateEngine: (type: 'animations' | 'noop', doc: Document) => AnimationEngine;
ɵAnimationRendererFactory: typeof AnimationRendererFactory;
}>,
) {}
/** @nodoc */
ngOnDestroy(): void {
// When the root view is removed, the renderer defers the actual work to the
// `TransitionAnimationEngine` to do this, and the `TransitionAnimationEngine` doesn't actually
// remove the DOM node, but just calls `markElementAsRemoved()`. The actual DOM node is not
// removed until `TransitionAnimationEngine` "flushes".
// Note: we already flush on destroy within the `InjectableAnimationEngine`. The injectable
// engine is not provided when async animations are used.
this._engine?.flush();
}
/**
* @internal
*/
private loadImpl(): Promise<AnimationRendererFactory> {
// Note on the `.then(m => m)` part below: Closure compiler optimizations in g3 require
// `.then` to be present for a dynamic import (or an import should be `await`ed) to detect
// the set of imported symbols.
const loadFn = () => this.moduleImpl ?? import('@angular/animations/browser').then((m) => m);
let moduleImplPromise: typeof this.moduleImpl;
if (this.loadingSchedulerFn) {
moduleImplPromise = this.loadingSchedulerFn(loadFn);
} else {
moduleImplPromise = loadFn();
}
return moduleImplPromise
.catch((e) => {
throw new RuntimeError(
RuntimeErrorCode.ANIMATION_RENDERER_ASYNC_LOADING_FAILURE,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Async loading for animations package was ' +
'enabled, but loading failed. Angular falls back to using regular rendering. ' +
"No animations will be displayed and their styles won't be applied.",
);
})
.then(({ɵcreateEngine, ɵAnimationRendererFactory}) => {
// We can't create the renderer yet because we might need the hostElement and the type
// Both are provided in createRenderer().
this._engine = ɵcreateEngine(this.animationType, this.doc);
const rendererFactory = new ɵAnimationRendererFactory(
this.delegate,
this._engine,
this.zone,
);
this.delegate = rendererFactory;
return rendererFactory;
});
}
/**
* This method is delegating the renderer creation to the factories.
* It uses default factory while the animation factory isn't loaded
* and will rely on the animation factory once it is loaded.
*
* Calling this method will trigger as side effect the loading of the animation module
* if the renderered component uses animations.
*/
createRenderer(hostElement: any, rendererType: RendererType2): Renderer2 {
const renderer = this.delegate.createRenderer(hostElement, rendererType);
if ((renderer as AnimationRenderer).ɵtype === AnimationRendererType.Regular) {
// The factory is already loaded, this is an animation renderer
return renderer;
}
// We need to prevent the DomRenderer to throw an error because of synthetic properties
if (typeof (renderer as any).throwOnSyntheticProps === 'boolean') {
(renderer as any).throwOnSyntheticProps = false;
}
// Using a dynamic renderer to switch the renderer implementation once the module is loaded.
const dynamicRenderer = new DynamicDelegationRenderer(renderer);
// Kick off the module loading if the component uses animations but the module hasn't been
// loaded yet.
if (rendererType?.data?.['animation'] && !this._rendererFactoryPromise) {
this._rendererFactoryPromise = this.loadImpl();
}
this._rendererFactoryPromise
?.then((animationRendererFactory) => {
const animationRenderer = animationRendererFactory.createRenderer(
hostElement,
rendererType,
);
dynamicRenderer.use(animationRenderer);
this.scheduler?.notify(NotificationSource.AsyncAnimationsLoaded);
})
.catch((e) => {
// Permanently use regular renderer when loading fails.
dynamicRenderer.use(renderer);
});
return dynamicRenderer;
}
begin(): void {
this.delegate.begin?.();
}
end(): void {
this.delegate.end?.();
}
whenRenderingDone?(): Promise<any> {
return this.delegate.whenRenderingDone?.() ?? Promise.resolve();
}
}
/**
* The class allows to dynamicly switch between different renderer implementations
* by changing the delegate renderer.
*/
export class Dy | {
"end_byte": 6132,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/src/async_animation_renderer.ts"
} |
angular/packages/platform-browser/animations/async/src/async_animation_renderer.ts_6133_10452 | amicDelegationRenderer implements Renderer2 {
// List of callbacks that need to be replayed on the animation renderer once its loaded
private replay: ((renderer: Renderer2) => void)[] | null = [];
readonly ɵtype = AnimationRendererType.Delegated;
constructor(private delegate: Renderer2) {}
use(impl: Renderer2) {
this.delegate = impl;
if (this.replay !== null) {
// Replay queued actions using the animation renderer to apply
// all events and properties collected while loading was in progress.
for (const fn of this.replay) {
fn(impl);
}
// Set to `null` to indicate that the queue was processed
// and we no longer need to collect events and properties.
this.replay = null;
}
}
get data(): {[key: string]: any} {
return this.delegate.data;
}
destroy(): void {
this.replay = null;
this.delegate.destroy();
}
createElement(name: string, namespace?: string | null) {
return this.delegate.createElement(name, namespace);
}
createComment(value: string): void {
return this.delegate.createComment(value);
}
createText(value: string): any {
return this.delegate.createText(value);
}
get destroyNode(): ((node: any) => void) | null {
return this.delegate.destroyNode;
}
appendChild(parent: any, newChild: any): void {
this.delegate.appendChild(parent, newChild);
}
insertBefore(parent: any, newChild: any, refChild: any, isMove?: boolean | undefined): void {
this.delegate.insertBefore(parent, newChild, refChild, isMove);
}
removeChild(parent: any, oldChild: any, isHostElement?: boolean | undefined): void {
this.delegate.removeChild(parent, oldChild, isHostElement);
}
selectRootElement(selectorOrNode: any, preserveContent?: boolean | undefined): any {
return this.delegate.selectRootElement(selectorOrNode, preserveContent);
}
parentNode(node: any): any {
return this.delegate.parentNode(node);
}
nextSibling(node: any): any {
return this.delegate.nextSibling(node);
}
setAttribute(el: any, name: string, value: string, namespace?: string | null | undefined): void {
this.delegate.setAttribute(el, name, value, namespace);
}
removeAttribute(el: any, name: string, namespace?: string | null | undefined): void {
this.delegate.removeAttribute(el, name, namespace);
}
addClass(el: any, name: string): void {
this.delegate.addClass(el, name);
}
removeClass(el: any, name: string): void {
this.delegate.removeClass(el, name);
}
setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2 | undefined): void {
this.delegate.setStyle(el, style, value, flags);
}
removeStyle(el: any, style: string, flags?: RendererStyleFlags2 | undefined): void {
this.delegate.removeStyle(el, style, flags);
}
setProperty(el: any, name: string, value: any): void {
// We need to keep track of animation properties set on default renderer
// So we can also set them also on the animation renderer
if (this.shouldReplay(name)) {
this.replay!.push((renderer: Renderer2) => renderer.setProperty(el, name, value));
}
this.delegate.setProperty(el, name, value);
}
setValue(node: any, value: string): void {
this.delegate.setValue(node, value);
}
listen(target: any, eventName: string, callback: (event: any) => boolean | void): () => void {
// We need to keep track of animation events registred by the default renderer
// So we can also register them against the animation renderer
if (this.shouldReplay(eventName)) {
this.replay!.push((renderer: Renderer2) => renderer.listen(target, eventName, callback));
}
return this.delegate.listen(target, eventName, callback);
}
private shouldReplay(propOrEventName: string): boolean {
//`null` indicates that we no longer need to collect events and properties
return this.replay !== null && propOrEventName.startsWith(ANIMATION_PREFIX);
}
}
/**
* Provides a custom scheduler function for the async loading of the animation package.
*
* Private token for investigation purposes
*/
export const ɵASYNC_ANIMATION_LOADING_SCHEDULER_FN = new InjectionToken<<T>(loadFn: () => T) => T>(
ngDevMode ? 'async_animation_loading_scheduler_fn' : '',
);
| {
"end_byte": 10452,
"start_byte": 6133,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/async/src/async_animation_renderer.ts"
} |
angular/packages/platform-browser/animations/src/module.ts_0_3948 | /**
* @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 {
ModuleWithProviders,
NgModule,
Provider,
ɵperformanceMarkFeature as performanceMarkFeature,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {BROWSER_ANIMATIONS_PROVIDERS, BROWSER_NOOP_ANIMATIONS_PROVIDERS} from './providers';
/**
* Object used to configure the behavior of {@link BrowserAnimationsModule}
* @publicApi
*/
export interface BrowserAnimationsModuleConfig {
/**
* Whether animations should be disabled. Passing this is identical to providing the
* `NoopAnimationsModule`, but it can be controlled based on a runtime value.
*/
disableAnimations?: boolean;
}
/**
* Exports `BrowserModule` with additional dependency-injection providers
* for use with animations. See [Animations](guide/animations).
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
providers: BROWSER_ANIMATIONS_PROVIDERS,
})
export class BrowserAnimationsModule {
/**
* Configures the module based on the specified object.
*
* @param config Object used to configure the behavior of the `BrowserAnimationsModule`.
* @see {@link BrowserAnimationsModuleConfig}
*
* @usageNotes
* When registering the `BrowserAnimationsModule`, you can use the `withConfig`
* function as follows:
* ```
* @NgModule({
* imports: [BrowserAnimationsModule.withConfig(config)]
* })
* class MyNgModule {}
* ```
*/
static withConfig(
config: BrowserAnimationsModuleConfig,
): ModuleWithProviders<BrowserAnimationsModule> {
return {
ngModule: BrowserAnimationsModule,
providers: config.disableAnimations
? BROWSER_NOOP_ANIMATIONS_PROVIDERS
: BROWSER_ANIMATIONS_PROVIDERS,
};
}
}
/**
* Returns the set of dependency-injection providers
* to enable animations in an application. See [animations guide](guide/animations)
* to learn more about animations in Angular.
*
* @usageNotes
*
* The function is useful when you want to enable animations in an application
* bootstrapped using the `bootstrapApplication` function. In this scenario there
* is no need to import the `BrowserAnimationsModule` NgModule at all, just add
* providers returned by this function to the `providers` list as show below.
*
* ```typescript
* bootstrapApplication(RootComponent, {
* providers: [
* provideAnimations()
* ]
* });
* ```
*
* @publicApi
*/
export function provideAnimations(): Provider[] {
performanceMarkFeature('NgEagerAnimations');
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideAnimations` call results in app code.
return [...BROWSER_ANIMATIONS_PROVIDERS];
}
/**
* A null player that must be imported to allow disabling of animations.
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
providers: BROWSER_NOOP_ANIMATIONS_PROVIDERS,
})
export class NoopAnimationsModule {}
/**
* Returns the set of dependency-injection providers
* to disable animations in an application. See [animations guide](guide/animations)
* to learn more about animations in Angular.
*
* @usageNotes
*
* The function is useful when you want to bootstrap an application using
* the `bootstrapApplication` function, but you need to disable animations
* (for example, when running tests).
*
* ```typescript
* bootstrapApplication(RootComponent, {
* providers: [
* provideNoopAnimations()
* ]
* });
* ```
*
* @publicApi
*/
export function provideNoopAnimations(): Provider[] {
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideNoopAnimations` call results in app code.
return [...BROWSER_NOOP_ANIMATIONS_PROVIDERS];
}
| {
"end_byte": 3948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/src/module.ts"
} |
angular/packages/platform-browser/animations/src/private_export.ts_0_290 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {InjectableAnimationEngine as ɵInjectableAnimationEngine} from './providers';
| {
"end_byte": 290,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/src/private_export.ts"
} |
angular/packages/platform-browser/animations/src/providers.ts_0_2890 | /**
* @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 {
AnimationDriver,
NoopAnimationDriver,
ɵAnimationEngine as AnimationEngine,
ɵAnimationRendererFactory as AnimationRendererFactory,
ɵAnimationStyleNormalizer as AnimationStyleNormalizer,
ɵWebAnimationsDriver as WebAnimationsDriver,
ɵWebAnimationsStyleNormalizer as WebAnimationsStyleNormalizer,
} from '@angular/animations/browser';
import {DOCUMENT} from '@angular/common';
import {
ANIMATION_MODULE_TYPE,
inject,
Inject,
Injectable,
NgZone,
OnDestroy,
Provider,
RendererFactory2,
ɵChangeDetectionScheduler as ChangeDetectionScheduler,
} from '@angular/core';
import {ɵDomRendererFactory2 as DomRendererFactory2} from '@angular/platform-browser';
@Injectable()
export class InjectableAnimationEngine extends AnimationEngine implements OnDestroy {
// The `ApplicationRef` is injected here explicitly to force the dependency ordering.
// Since the `ApplicationRef` should be created earlier before the `AnimationEngine`, they
// both have `ngOnDestroy` hooks and `flush()` must be called after all views are destroyed.
constructor(
@Inject(DOCUMENT) doc: Document,
driver: AnimationDriver,
normalizer: AnimationStyleNormalizer,
) {
super(doc, driver, normalizer);
}
ngOnDestroy(): void {
this.flush();
}
}
export function instantiateDefaultStyleNormalizer() {
return new WebAnimationsStyleNormalizer();
}
export function instantiateRendererFactory(
renderer: DomRendererFactory2,
engine: AnimationEngine,
zone: NgZone,
) {
return new AnimationRendererFactory(renderer, engine, zone);
}
const SHARED_ANIMATION_PROVIDERS: Provider[] = [
{provide: AnimationStyleNormalizer, useFactory: instantiateDefaultStyleNormalizer},
{provide: AnimationEngine, useClass: InjectableAnimationEngine},
{
provide: RendererFactory2,
useFactory: instantiateRendererFactory,
deps: [DomRendererFactory2, AnimationEngine, NgZone],
},
];
/**
* Separate providers from the actual module so that we can do a local modification in Google3 to
* include them in the BrowserModule.
*/
export const BROWSER_ANIMATIONS_PROVIDERS: Provider[] = [
{provide: AnimationDriver, useFactory: () => new WebAnimationsDriver()},
{provide: ANIMATION_MODULE_TYPE, useValue: 'BrowserAnimations'},
...SHARED_ANIMATION_PROVIDERS,
];
/**
* Separate providers from the actual module so that we can do a local modification in Google3 to
* include them in the BrowserTestingModule.
*/
export const BROWSER_NOOP_ANIMATIONS_PROVIDERS: Provider[] = [
{provide: AnimationDriver, useClass: NoopAnimationDriver},
{provide: ANIMATION_MODULE_TYPE, useValue: 'NoopAnimations'},
...SHARED_ANIMATION_PROVIDERS,
];
| {
"end_byte": 2890,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/src/providers.ts"
} |
angular/packages/platform-browser/animations/src/animations.ts_0_557 | /**
* @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 animation APIs of the animation browser package.
*/
export {ANIMATION_MODULE_TYPE} from '@angular/core';
export {
BrowserAnimationsModule,
BrowserAnimationsModuleConfig,
NoopAnimationsModule,
provideAnimations,
provideNoopAnimations,
} from './module';
export * from './private_export';
| {
"end_byte": 557,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/animations/src/animations.ts"
} |
angular/packages/platform-browser/src/platform-browser.ts_0_1337 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {
ApplicationConfig,
bootstrapApplication,
BrowserModule,
createApplication,
platformBrowser,
provideProtractorTestingSupport,
} from './browser';
export {Meta, MetaDefinition} from './browser/meta';
export {Title} from './browser/title';
export {disableDebugTools, enableDebugTools} from './browser/tools/tools';
export {By} from './dom/debug/by';
export {REMOVE_STYLES_ON_COMPONENT_DESTROY} from './dom/dom_renderer';
export {EVENT_MANAGER_PLUGINS, EventManager, EventManagerPlugin} from './dom/events/event_manager';
export {
HAMMER_GESTURE_CONFIG,
HAMMER_LOADER,
HammerGestureConfig,
HammerLoader,
HammerModule,
} from './dom/events/hammer_gestures';
export {
DomSanitizer,
SafeHtml,
SafeResourceUrl,
SafeScript,
SafeStyle,
SafeUrl,
SafeValue,
} from './security/dom_sanitization_service';
export {
HydrationFeature,
HydrationFeatureKind,
provideClientHydration,
withEventReplay,
withHttpTransferCacheOptions,
withI18nSupport,
withNoHttpTransferCache,
withIncrementalHydration,
} from './hydration';
export * from './private_export';
export {VERSION} from './version';
| {
"end_byte": 1337,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/platform-browser.ts"
} |
angular/packages/platform-browser/src/errors.ts_0_950 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* The list of error codes used in runtime code of the `platform-browser` package.
* Reserved error code range: 5000-5500.
*/
export const enum RuntimeErrorCode {
// Hydration Errors
UNSUPPORTED_ZONEJS_INSTANCE = -5000,
// misc errors (5100-5200 range)
BROWSER_MODULE_ALREADY_LOADED = 5100,
NO_PLUGIN_FOR_EVENT = 5101,
UNSUPPORTED_EVENT_TARGET = 5102,
TESTABILITY_NOT_FOUND = 5103,
ROOT_NODE_NOT_FOUND = -5104,
UNEXPECTED_SYNTHETIC_PROPERTY = 5105,
// Sanitization-related errors (5200-5300 range)
SANITIZATION_UNSAFE_SCRIPT = 5200,
SANITIZATION_UNSAFE_RESOURCE_URL = 5201,
SANITIZATION_UNEXPECTED_CTX = 5202,
// Animations related errors (5300-5400 range)
ANIMATION_RENDERER_ASYNC_LOADING_FAILURE = 5300,
}
| {
"end_byte": 950,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/errors.ts"
} |
angular/packages/platform-browser/src/platform-browser.externs.js_0_467 | /**
* @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
*
* @externs
*/
/**
* @suppress {duplicate}
*/
var getAngularTestability;
/**
* @suppress {duplicate}
*/
var getAllAngularTestabilities;
/**
* @suppress {duplicate}
*/
var getAllAngularRootElements;
/**
* @suppress {duplicate}
*/
var frameworkStabilizers;
| {
"end_byte": 467,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/platform-browser.externs.js"
} |
angular/packages/platform-browser/src/hydration.ts_0_8524 | /**
* @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 {HttpTransferCacheOptions, ɵwithHttpTransferCache} from '@angular/common/http';
import {
ENVIRONMENT_INITIALIZER,
EnvironmentProviders,
inject,
makeEnvironmentProviders,
NgZone,
Provider,
ɵConsole as Console,
ɵformatRuntimeError as formatRuntimeError,
ɵwithDomHydration as withDomHydration,
ɵwithEventReplay,
ɵwithI18nSupport,
ɵZONELESS_ENABLED as ZONELESS_ENABLED,
ɵwithIncrementalHydration,
} from '@angular/core';
import {RuntimeErrorCode} from './errors';
/**
* The list of features as an enum to uniquely type each `HydrationFeature`.
* @see {@link HydrationFeature}
*
* @publicApi
*/
export enum HydrationFeatureKind {
NoHttpTransferCache,
HttpTransferCacheOptions,
I18nSupport,
EventReplay,
IncrementalHydration,
}
/**
* Helper type to represent a Hydration feature.
*
* @publicApi
*/
export interface HydrationFeature<FeatureKind extends HydrationFeatureKind> {
ɵkind: FeatureKind;
ɵproviders: Provider[];
}
/**
* Helper function to create an object that represents a Hydration feature.
*/
function hydrationFeature<FeatureKind extends HydrationFeatureKind>(
ɵkind: FeatureKind,
ɵproviders: Provider[] = [],
ɵoptions: unknown = {},
): HydrationFeature<FeatureKind> {
return {ɵkind, ɵproviders};
}
/**
* Disables HTTP transfer cache. Effectively causes HTTP requests to be performed twice: once on the
* server and other one on the browser.
*
* @publicApi
*/
export function withNoHttpTransferCache(): HydrationFeature<HydrationFeatureKind.NoHttpTransferCache> {
// This feature has no providers and acts as a flag that turns off
// HTTP transfer cache (which otherwise is turned on by default).
return hydrationFeature(HydrationFeatureKind.NoHttpTransferCache);
}
/**
* The function accepts an object, which allows to configure cache parameters,
* such as which headers should be included (no headers are included by default),
* whether POST requests should be cached or a callback function to determine if a
* particular request should be cached.
*
* @publicApi
*/
export function withHttpTransferCacheOptions(
options: HttpTransferCacheOptions,
): HydrationFeature<HydrationFeatureKind.HttpTransferCacheOptions> {
// This feature has no providers and acts as a flag to pass options to the HTTP transfer cache.
return hydrationFeature(
HydrationFeatureKind.HttpTransferCacheOptions,
ɵwithHttpTransferCache(options),
);
}
/**
* Enables support for hydrating i18n blocks.
*
* @developerPreview
* @publicApi
*/
export function withI18nSupport(): HydrationFeature<HydrationFeatureKind.I18nSupport> {
return hydrationFeature(HydrationFeatureKind.I18nSupport, ɵwithI18nSupport());
}
/**
* Enables support for replaying user events (e.g. `click`s) that happened on a page
* before hydration logic has completed. Once an application is hydrated, all captured
* events are replayed and relevant event listeners are executed.
*
* @usageNotes
*
* Basic example of how you can enable event replay in your application when
* `bootstrapApplication` function is used:
* ```
* bootstrapApplication(AppComponent, {
* providers: [provideClientHydration(withEventReplay())]
* });
* ```
* @publicApi
* @see {@link provideClientHydration}
*/
export function withEventReplay(): HydrationFeature<HydrationFeatureKind.EventReplay> {
return hydrationFeature(HydrationFeatureKind.EventReplay, ɵwithEventReplay());
}
/**
* Enables support for incremental hydration using the `hydrate` trigger syntax.
*
* @usageNotes
*
* Basic example of how you can enable incremental hydration in your application when
* the `bootstrapApplication` function is used:
* ```
* bootstrapApplication(AppComponent, {
* providers: [provideClientHydration(withIncrementalHydration())]
* });
* ```
* @experimental
* @publicApi
* @see {@link provideClientHydration}
*/
export function withIncrementalHydration(): HydrationFeature<HydrationFeatureKind.IncrementalHydration> {
return hydrationFeature(HydrationFeatureKind.IncrementalHydration, ɵwithIncrementalHydration());
}
/**
* Returns an `ENVIRONMENT_INITIALIZER` token setup with a function
* that verifies whether compatible ZoneJS was used in an application
* and logs a warning in a console if it's not the case.
*/
function provideZoneJsCompatibilityDetector(): Provider[] {
return [
{
provide: ENVIRONMENT_INITIALIZER,
useValue: () => {
const ngZone = inject(NgZone);
const isZoneless = inject(ZONELESS_ENABLED);
// Checking `ngZone instanceof NgZone` would be insufficient here,
// because custom implementations might use NgZone as a base class.
if (!isZoneless && ngZone.constructor !== NgZone) {
const console = inject(Console);
const message = formatRuntimeError(
RuntimeErrorCode.UNSUPPORTED_ZONEJS_INSTANCE,
'Angular detected that hydration was enabled for an application ' +
'that uses a custom or a noop Zone.js implementation. ' +
'This is not yet a fully supported configuration.',
);
// tslint:disable-next-line:no-console
console.warn(message);
}
},
multi: true,
},
];
}
/**
* Sets up providers necessary to enable hydration functionality for the application.
*
* By default, the function enables the recommended set of features for the optimal
* performance for most of the applications. It includes the following features:
*
* * Reconciling DOM hydration. Learn more about it [here](guide/hydration).
* * [`HttpClient`](api/common/http/HttpClient) response caching while running on the server and
* transferring this cache to the client to avoid extra HTTP requests. Learn more about data caching
* [here](guide/ssr#caching-data-when-using-httpclient).
*
* These functions allow you to disable some of the default features or enable new ones:
*
* * {@link withNoHttpTransferCache} to disable HTTP transfer cache
* * {@link withHttpTransferCacheOptions} to configure some HTTP transfer cache options
* * {@link withI18nSupport} to enable hydration support for i18n blocks
* * {@link withEventReplay} to enable support for replaying user events
*
* @usageNotes
*
* Basic example of how you can enable hydration in your application when
* `bootstrapApplication` function is used:
* ```
* bootstrapApplication(AppComponent, {
* providers: [provideClientHydration()]
* });
* ```
*
* Alternatively if you are using NgModules, you would add `provideClientHydration`
* to your root app module's provider list.
* ```
* @NgModule({
* declarations: [RootCmp],
* bootstrap: [RootCmp],
* providers: [provideClientHydration()],
* })
* export class AppModule {}
* ```
*
* @see {@link withNoHttpTransferCache}
* @see {@link withHttpTransferCacheOptions}
* @see {@link withI18nSupport}
* @see {@link withEventReplay}
*
* @param features Optional features to configure additional router behaviors.
* @returns A set of providers to enable hydration.
*
* @publicApi
*/
export function provideClientHydration(
...features: HydrationFeature<HydrationFeatureKind>[]
): EnvironmentProviders {
const providers: Provider[] = [];
const featuresKind = new Set<HydrationFeatureKind>();
const hasHttpTransferCacheOptions = featuresKind.has(
HydrationFeatureKind.HttpTransferCacheOptions,
);
for (const {ɵproviders, ɵkind} of features) {
featuresKind.add(ɵkind);
if (ɵproviders.length) {
providers.push(ɵproviders);
}
}
if (
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
featuresKind.has(HydrationFeatureKind.NoHttpTransferCache) &&
hasHttpTransferCacheOptions
) {
// TODO: Make this a runtime error
throw new Error(
'Configuration error: found both withHttpTransferCacheOptions() and withNoHttpTransferCache() in the same call to provideClientHydration(), which is a contradiction.',
);
}
return makeEnvironmentProviders([
typeof ngDevMode !== 'undefined' && ngDevMode ? provideZoneJsCompatibilityDetector() : [],
withDomHydration(),
featuresKind.has(HydrationFeatureKind.NoHttpTransferCache) || hasHttpTransferCacheOptions
? []
: ɵwithHttpTransferCache({}),
providers,
]);
}
| {
"end_byte": 8524,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/hydration.ts"
} |
angular/packages/platform-browser/src/private_export.ts_0_1133 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {ɵgetDOM} from '@angular/common';
export {
initDomAdapter as ɵinitDomAdapter,
INTERNAL_BROWSER_PLATFORM_PROVIDERS as ɵINTERNAL_BROWSER_PLATFORM_PROVIDERS,
} from './browser';
export {BrowserDomAdapter as ɵBrowserDomAdapter} from './browser/browser_adapter';
export {BrowserGetTestability as ɵBrowserGetTestability} from './browser/testability';
export {DomRendererFactory2 as ɵDomRendererFactory2} from './dom/dom_renderer';
export {DomEventsPlugin as ɵDomEventsPlugin} from './dom/events/dom_events';
export {HammerGesturesPlugin as ɵHammerGesturesPlugin} from './dom/events/hammer_gestures';
export {KeyEventsPlugin as ɵKeyEventsPlugin} from './dom/events/key_events';
export {SharedStylesHost as ɵSharedStylesHost} from './dom/shared_styles_host';
export {RuntimeErrorCode as ɵRuntimeErrorCode} from './errors';
export {DomSanitizerImpl as ɵDomSanitizerImpl} from './security/dom_sanitization_service';
| {
"end_byte": 1133,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/private_export.ts"
} |
angular/packages/platform-browser/src/browser.ts_0_8654 | /**
* @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 {
CommonModule,
DOCUMENT,
XhrFactory,
ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID,
} from '@angular/common';
import {
APP_ID,
ApplicationConfig as ApplicationConfigFromCore,
ApplicationModule,
ApplicationRef,
createPlatformFactory,
ErrorHandler,
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
NgZone,
Optional,
PLATFORM_ID,
PLATFORM_INITIALIZER,
platformCore,
PlatformRef,
Provider,
RendererFactory2,
SkipSelf,
StaticProvider,
Testability,
TestabilityRegistry,
Type,
ɵINJECTOR_SCOPE as INJECTOR_SCOPE,
ɵinternalCreateApplication as internalCreateApplication,
ɵRuntimeError as RuntimeError,
ɵsetDocument,
ɵTESTABILITY as TESTABILITY,
ɵTESTABILITY_GETTER as TESTABILITY_GETTER,
} from '@angular/core';
import {BrowserDomAdapter} from './browser/browser_adapter';
import {BrowserGetTestability} from './browser/testability';
import {BrowserXhr} from './browser/xhr';
import {DomRendererFactory2} from './dom/dom_renderer';
import {DomEventsPlugin} from './dom/events/dom_events';
import {EVENT_MANAGER_PLUGINS, EventManager} from './dom/events/event_manager';
import {KeyEventsPlugin} from './dom/events/key_events';
import {SharedStylesHost} from './dom/shared_styles_host';
import {RuntimeErrorCode} from './errors';
/**
* Set of config options available during the application bootstrap operation.
*
* @publicApi
*
* @deprecated
* `ApplicationConfig` has moved, please import `ApplicationConfig` from `@angular/core` instead.
*/
// The below is a workaround to add a deprecated message.
type ApplicationConfig = ApplicationConfigFromCore;
export {ApplicationConfig};
/**
* Bootstraps an instance of an Angular application and renders a standalone component as the
* application's root component. More information about standalone components can be found in [this
* guide](guide/components/importing).
*
* @usageNotes
* The root component passed into this function *must* be a standalone one (should have the
* `standalone: true` flag in the `@Component` decorator config).
*
* ```typescript
* @Component({
* standalone: true,
* template: 'Hello world!'
* })
* class RootComponent {}
*
* const appRef: ApplicationRef = await bootstrapApplication(RootComponent);
* ```
*
* You can add the list of providers that should be available in the application injector by
* specifying the `providers` field in an object passed as the second argument:
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* {provide: BACKEND_URL, useValue: 'https://yourdomain.com/api'}
* ]
* });
* ```
*
* The `importProvidersFrom` helper method can be used to collect all providers from any
* existing NgModule (and transitively from all NgModules that it imports):
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* importProvidersFrom(SomeNgModule)
* ]
* });
* ```
*
* Note: the `bootstrapApplication` method doesn't include [Testability](api/core/Testability) by
* default. You can add [Testability](api/core/Testability) by getting the list of necessary
* providers using `provideProtractorTestingSupport()` function and adding them into the `providers`
* array, for example:
*
* ```typescript
* import {provideProtractorTestingSupport} from '@angular/platform-browser';
*
* await bootstrapApplication(RootComponent, {providers: [provideProtractorTestingSupport()]});
* ```
*
* @param rootComponent A reference to a standalone component that should be rendered.
* @param options Extra configuration for the bootstrap operation, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
export function bootstrapApplication(
rootComponent: Type<unknown>,
options?: ApplicationConfig,
): Promise<ApplicationRef> {
return internalCreateApplication({rootComponent, ...createProvidersConfig(options)});
}
/**
* Create an instance of an Angular application without bootstrapping any components. This is useful
* for the situation where one wants to decouple application environment creation (a platform and
* associated injectors) from rendering components on a screen. Components can be subsequently
* bootstrapped on the returned `ApplicationRef`.
*
* @param options Extra configuration for the application environment, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
export function createApplication(options?: ApplicationConfig) {
return internalCreateApplication(createProvidersConfig(options));
}
function createProvidersConfig(options?: ApplicationConfig) {
return {
appProviders: [...BROWSER_MODULE_PROVIDERS, ...(options?.providers ?? [])],
platformProviders: INTERNAL_BROWSER_PLATFORM_PROVIDERS,
};
}
/**
* Returns a set of providers required to setup [Testability](api/core/Testability) for an
* application bootstrapped using the `bootstrapApplication` function. The set of providers is
* needed to support testing an application with Protractor (which relies on the Testability APIs
* to be present).
*
* @returns An array of providers required to setup Testability for an application and make it
* available for testing using Protractor.
*
* @publicApi
*/
export function provideProtractorTestingSupport(): Provider[] {
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideProtractorTestingSupport` call results in app
// code.
return [...TESTABILITY_PROVIDERS];
}
export function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
}
export function errorHandler(): ErrorHandler {
return new ErrorHandler();
}
export function _document(): any {
// Tell ivy about the global document
ɵsetDocument(document);
return document;
}
export const INTERNAL_BROWSER_PLATFORM_PROVIDERS: StaticProvider[] = [
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
{provide: PLATFORM_INITIALIZER, useValue: initDomAdapter, multi: true},
{provide: DOCUMENT, useFactory: _document, deps: []},
];
/**
* A factory function that returns a `PlatformRef` instance associated with browser service
* providers.
*
* @publicApi
*/
export const platformBrowser: (extraProviders?: StaticProvider[]) => PlatformRef =
createPlatformFactory(platformCore, 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
/**
* Internal marker to signal whether providers from the `BrowserModule` are already present in DI.
* This is needed to avoid loading `BrowserModule` providers twice. We can't rely on the
* `BrowserModule` presence itself, since the standalone-based bootstrap just imports
* `BrowserModule` providers without referencing the module itself.
*/
const BROWSER_MODULE_PROVIDERS_MARKER = new InjectionToken(
typeof ngDevMode === 'undefined' || ngDevMode ? 'BrowserModule Providers Marker' : '',
);
const TESTABILITY_PROVIDERS = [
{
provide: TESTABILITY_GETTER,
useClass: BrowserGetTestability,
deps: [],
},
{
provide: TESTABILITY,
useClass: Testability,
deps: [NgZone, TestabilityRegistry, TESTABILITY_GETTER],
},
{
provide: Testability, // Also provide as `Testability` for backwards-compatibility.
useClass: Testability,
deps: [NgZone, TestabilityRegistry, TESTABILITY_GETTER],
},
];
const BROWSER_MODULE_PROVIDERS: Provider[] = [
{provide: INJECTOR_SCOPE, useValue: 'root'},
{provide: ErrorHandler, useFactory: errorHandler, deps: []},
{
provide: EVENT_MANAGER_PLUGINS,
useClass: DomEventsPlugin,
multi: true,
deps: [DOCUMENT, NgZone, PLATFORM_ID],
},
{provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true, deps: [DOCUMENT]},
DomRendererFactory2,
SharedStylesHost,
EventManager,
{provide: RendererFactory2, useExisting: DomRendererFactory2},
{provide: XhrFactory, useClass: BrowserXhr, deps: []},
typeof ngDevMode === 'undefined' || ngDevMode
? {provide: BROWSER_MODULE_PROVIDERS_MARKER, useValue: true}
: [],
];
/**
* Exports required infrastructure for all Angular apps.
* Included by default in all Angular apps created with the CLI
* `new` command.
* Re-exports `CommonModule` and `ApplicationModule`, making their
* exports and providers available to all apps.
*
* @publicApi
*/
@NgModu | {
"end_byte": 8654,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser.ts"
} |
angular/packages/platform-browser/src/browser.ts_8655_9340 | e({
providers: [...BROWSER_MODULE_PROVIDERS, ...TESTABILITY_PROVIDERS],
exports: [CommonModule, ApplicationModule],
})
export class BrowserModule {
constructor(
@Optional()
@SkipSelf()
@Inject(BROWSER_MODULE_PROVIDERS_MARKER)
providersAlreadyPresent: boolean | null,
) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && providersAlreadyPresent) {
throw new RuntimeError(
RuntimeErrorCode.BROWSER_MODULE_ALREADY_LOADED,
`Providers from the \`BrowserModule\` have already been loaded. If you need access ` +
`to common directives such as NgIf and NgFor, import the \`CommonModule\` instead.`,
);
}
}
}
| {
"end_byte": 9340,
"start_byte": 8655,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser.ts"
} |
angular/packages/platform-browser/src/version.ts_0_427 | /**
* @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 the platform-browser package.
*/
import {Version} from '@angular/core';
/**
* @publicApi
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');
| {
"end_byte": 427,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/version.ts"
} |
angular/packages/platform-browser/src/security/dom_sanitization_service.ts_0_8678 | /**
* @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 {
forwardRef,
Inject,
Injectable,
Sanitizer,
SecurityContext,
ɵ_sanitizeHtml as _sanitizeHtml,
ɵ_sanitizeUrl as _sanitizeUrl,
ɵallowSanitizationBypassAndThrow as allowSanitizationBypassOrThrow,
ɵbypassSanitizationTrustHtml as bypassSanitizationTrustHtml,
ɵbypassSanitizationTrustResourceUrl as bypassSanitizationTrustResourceUrl,
ɵbypassSanitizationTrustScript as bypassSanitizationTrustScript,
ɵbypassSanitizationTrustStyle as bypassSanitizationTrustStyle,
ɵbypassSanitizationTrustUrl as bypassSanitizationTrustUrl,
ɵBypassType as BypassType,
ɵRuntimeError as RuntimeError,
ɵunwrapSafeValue as unwrapSafeValue,
ɵXSS_SECURITY_URL as XSS_SECURITY_URL,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
export {SecurityContext};
/**
* Marker interface for a value that's safe to use in a particular context.
*
* @publicApi
*/
export interface SafeValue {}
/**
* Marker interface for a value that's safe to use as HTML.
*
* @publicApi
*/
export interface SafeHtml extends SafeValue {}
/**
* Marker interface for a value that's safe to use as style (CSS).
*
* @publicApi
*/
export interface SafeStyle extends SafeValue {}
/**
* Marker interface for a value that's safe to use as JavaScript.
*
* @publicApi
*/
export interface SafeScript extends SafeValue {}
/**
* Marker interface for a value that's safe to use as a URL linking to a document.
*
* @publicApi
*/
export interface SafeUrl extends SafeValue {}
/**
* Marker interface for a value that's safe to use as a URL to load executable code from.
*
* @publicApi
*/
export interface SafeResourceUrl extends SafeValue {}
/**
* DomSanitizer helps preventing Cross Site Scripting Security bugs (XSS) by sanitizing
* values to be safe to use in the different DOM contexts.
*
* For example, when binding a URL in an `<a [href]="someValue">` hyperlink, `someValue` will be
* sanitized so that an attacker cannot inject e.g. a `javascript:` URL that would execute code on
* the website.
*
* In specific situations, it might be necessary to disable sanitization, for example if the
* application genuinely needs to produce a `javascript:` style link with a dynamic value in it.
* Users can bypass security by constructing a value with one of the `bypassSecurityTrust...`
* methods, and then binding to that value from the template.
*
* These situations should be very rare, and extraordinary care must be taken to avoid creating a
* Cross Site Scripting (XSS) security bug!
*
* When using `bypassSecurityTrust...`, make sure to call the method as early as possible and as
* close as possible to the source of the value, to make it easy to verify no security bug is
* created by its use.
*
* It is not required (and not recommended) to bypass security if the value is safe, e.g. a URL that
* does not start with a suspicious protocol, or an HTML snippet that does not contain dangerous
* code. The sanitizer leaves safe values intact.
*
* @security Calling any of the `bypassSecurityTrust...` APIs disables Angular's built-in
* sanitization for the value passed in. Carefully check and audit all values and code paths going
* into this call. Make sure any user data is appropriately escaped for this security context.
* For more detail, see the [Security Guide](https://g.co/ng/security).
*
* @publicApi
*/
@Injectable({providedIn: 'root', useExisting: forwardRef(() => DomSanitizerImpl)})
export abstract class DomSanitizer implements Sanitizer {
/**
* Gets a safe value from either a known safe value or a value with unknown safety.
*
* If the given value is already a `SafeValue`, this method returns the unwrapped value.
* If the security context is HTML and the given value is a plain string, this method
* sanitizes the string, removing any potentially unsafe content.
* For any other security context, this method throws an error if provided
* with a plain string.
*/
abstract sanitize(context: SecurityContext, value: SafeValue | string | null): string | null;
/**
* Bypass security and trust the given value to be safe HTML. Only use this when the bound HTML
* is unsafe (e.g. contains `<script>` tags) and the code should be executed. The sanitizer will
* leave safe HTML intact, so in most situations this method should not be used.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
*/
abstract bypassSecurityTrustHtml(value: string): SafeHtml;
/**
* Bypass security and trust the given value to be safe style value (CSS).
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
*/
abstract bypassSecurityTrustStyle(value: string): SafeStyle;
/**
* Bypass security and trust the given value to be safe JavaScript.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
*/
abstract bypassSecurityTrustScript(value: string): SafeScript;
/**
* Bypass security and trust the given value to be a safe style URL, i.e. a value that can be used
* in hyperlinks or `<img src>`.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
*/
abstract bypassSecurityTrustUrl(value: string): SafeUrl;
/**
* Bypass security and trust the given value to be a safe resource URL, i.e. a location that may
* be used to load executable code from, like `<script src>`, or `<iframe src>`.
*
* **WARNING:** calling this method with untrusted user data exposes your application to XSS
* security risks!
*/
abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl;
}
@Injectable({providedIn: 'root'})
export class DomSanitizerImpl extends DomSanitizer {
constructor(@Inject(DOCUMENT) private _doc: any) {
super();
}
override sanitize(ctx: SecurityContext, value: SafeValue | string | null): string | null {
if (value == null) return null;
switch (ctx) {
case SecurityContext.NONE:
return value as string;
case SecurityContext.HTML:
if (allowSanitizationBypassOrThrow(value, BypassType.Html)) {
return unwrapSafeValue(value);
}
return _sanitizeHtml(this._doc, String(value)).toString();
case SecurityContext.STYLE:
if (allowSanitizationBypassOrThrow(value, BypassType.Style)) {
return unwrapSafeValue(value);
}
return value as string;
case SecurityContext.SCRIPT:
if (allowSanitizationBypassOrThrow(value, BypassType.Script)) {
return unwrapSafeValue(value);
}
throw new RuntimeError(
RuntimeErrorCode.SANITIZATION_UNSAFE_SCRIPT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'unsafe value used in a script context',
);
case SecurityContext.URL:
if (allowSanitizationBypassOrThrow(value, BypassType.Url)) {
return unwrapSafeValue(value);
}
return _sanitizeUrl(String(value));
case SecurityContext.RESOURCE_URL:
if (allowSanitizationBypassOrThrow(value, BypassType.ResourceUrl)) {
return unwrapSafeValue(value);
}
throw new RuntimeError(
RuntimeErrorCode.SANITIZATION_UNSAFE_RESOURCE_URL,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`unsafe value used in a resource URL context (see ${XSS_SECURITY_URL})`,
);
default:
throw new RuntimeError(
RuntimeErrorCode.SANITIZATION_UNEXPECTED_CTX,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Unexpected SecurityContext ${ctx} (see ${XSS_SECURITY_URL})`,
);
}
}
override bypassSecurityTrustHtml(value: string): SafeHtml {
return bypassSanitizationTrustHtml(value);
}
override bypassSecurityTrustStyle(value: string): SafeStyle {
return bypassSanitizationTrustStyle(value);
}
override bypassSecurityTrustScript(value: string): SafeScript {
return bypassSanitizationTrustScript(value);
}
override bypassSecurityTrustUrl(value: string): SafeUrl {
return bypassSanitizationTrustUrl(value);
}
override bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl {
return bypassSanitizationTrustResourceUrl(value);
}
}
| {
"end_byte": 8678,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/security/dom_sanitization_service.ts"
} |
angular/packages/platform-browser/src/browser/title.ts_0_1090 | /**
* @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 {Inject, Injectable} from '@angular/core';
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class Title {
constructor(@Inject(DOCUMENT) private _doc: any) {}
/**
* Get the title of the current HTML document.
*/
getTitle(): string {
return this._doc.title;
}
/**
* Set the title of the current HTML document.
* @param newTitle
*/
setTitle(newTitle: string) {
this._doc.title = newTitle || '';
}
}
| {
"end_byte": 1090,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/title.ts"
} |
angular/packages/platform-browser/src/browser/meta.ts_0_7878 | /**
* @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, ɵDomAdapter as DomAdapter, ɵgetDOM as getDOM} from '@angular/common';
import {Inject, Injectable} from '@angular/core';
/**
* Represents the attributes of an HTML `<meta>` element. The element itself is
* represented by the internal `HTMLMetaElement`.
*
* @see [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta)
* @see {@link Meta}
*
* @publicApi
*/
export type MetaDefinition = {
charset?: string;
content?: string;
httpEquiv?: string;
id?: string;
itemprop?: string;
name?: string;
property?: string;
scheme?: string;
url?: string;
} & {
// TODO(IgorMinar): this type looks wrong
[prop: string]: string;
};
/**
* A service for managing HTML `<meta>` tags.
*
* Properties of the `MetaDefinition` object match the attributes of the
* HTML `<meta>` tag. These tags define document metadata that is important for
* things like configuring a Content Security Policy, defining browser compatibility
* and security settings, setting HTTP Headers, defining rich content for social sharing,
* and Search Engine Optimization (SEO).
*
* To identify specific `<meta>` tags in a document, use an attribute selection
* string in the format `"tag_attribute='value string'"`.
* For example, an `attrSelector` value of `"name='description'"` matches a tag
* whose `name` attribute has the value `"description"`.
* Selectors are used with the `querySelector()` Document method,
* in the format `meta[{attrSelector}]`.
*
* @see [HTML meta tag](https://developer.mozilla.org/docs/Web/HTML/Element/meta)
* @see [Document.querySelector()](https://developer.mozilla.org/docs/Web/API/Document/querySelector)
*
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class Meta {
private _dom: DomAdapter;
constructor(@Inject(DOCUMENT) private _doc: any) {
this._dom = getDOM();
}
/**
* Retrieves or creates a specific `<meta>` tag element in the current HTML document.
* In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
* values in the provided tag definition, and verifies that all other attribute values are equal.
* If an existing element is found, it is returned and is not modified in any way.
* @param tag The definition of a `<meta>` element to match or create.
* @param forceCreation True to create a new element without checking whether one already exists.
* @returns The existing element with the same attributes and values if found,
* the new element if no match is found, or `null` if the tag parameter is not defined.
*/
addTag(tag: MetaDefinition, forceCreation: boolean = false): HTMLMetaElement | null {
if (!tag) return null;
return this._getOrCreateElement(tag, forceCreation);
}
/**
* Retrieves or creates a set of `<meta>` tag elements in the current HTML document.
* In searching for an existing tag, Angular attempts to match the `name` or `property` attribute
* values in the provided tag definition, and verifies that all other attribute values are equal.
* @param tags An array of tag definitions to match or create.
* @param forceCreation True to create new elements without checking whether they already exist.
* @returns The matching elements if found, or the new elements.
*/
addTags(tags: MetaDefinition[], forceCreation: boolean = false): HTMLMetaElement[] {
if (!tags) return [];
return tags.reduce((result: HTMLMetaElement[], tag: MetaDefinition) => {
if (tag) {
result.push(this._getOrCreateElement(tag, forceCreation));
}
return result;
}, []);
}
/**
* Retrieves a `<meta>` tag element in the current HTML document.
* @param attrSelector The tag attribute and value to match against, in the format
* `"tag_attribute='value string'"`.
* @returns The matching element, if any.
*/
getTag(attrSelector: string): HTMLMetaElement | null {
if (!attrSelector) return null;
return this._doc.querySelector(`meta[${attrSelector}]`) || null;
}
/**
* Retrieves a set of `<meta>` tag elements in the current HTML document.
* @param attrSelector The tag attribute and value to match against, in the format
* `"tag_attribute='value string'"`.
* @returns The matching elements, if any.
*/
getTags(attrSelector: string): HTMLMetaElement[] {
if (!attrSelector) return [];
const list /*NodeList*/ = this._doc.querySelectorAll(`meta[${attrSelector}]`);
return list ? [].slice.call(list) : [];
}
/**
* Modifies an existing `<meta>` tag element in the current HTML document.
* @param tag The tag description with which to replace the existing tag content.
* @param selector A tag attribute and value to match against, to identify
* an existing tag. A string in the format `"tag_attribute=`value string`"`.
* If not supplied, matches a tag with the same `name` or `property` attribute value as the
* replacement tag.
* @return The modified element.
*/
updateTag(tag: MetaDefinition, selector?: string): HTMLMetaElement | null {
if (!tag) return null;
selector = selector || this._parseSelector(tag);
const meta: HTMLMetaElement = this.getTag(selector)!;
if (meta) {
return this._setMetaElementAttributes(tag, meta);
}
return this._getOrCreateElement(tag, true);
}
/**
* Removes an existing `<meta>` tag element from the current HTML document.
* @param attrSelector A tag attribute and value to match against, to identify
* an existing tag. A string in the format `"tag_attribute=`value string`"`.
*/
removeTag(attrSelector: string): void {
this.removeTagElement(this.getTag(attrSelector)!);
}
/**
* Removes an existing `<meta>` tag element from the current HTML document.
* @param meta The tag definition to match against to identify an existing tag.
*/
removeTagElement(meta: HTMLMetaElement): void {
if (meta) {
this._dom.remove(meta);
}
}
private _getOrCreateElement(
meta: MetaDefinition,
forceCreation: boolean = false,
): HTMLMetaElement {
if (!forceCreation) {
const selector: string = this._parseSelector(meta);
// It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to
// check if element has tag attributes
const elem = this.getTags(selector).filter((elem) => this._containsAttributes(meta, elem))[0];
if (elem !== undefined) return elem;
}
const element: HTMLMetaElement = this._dom.createElement('meta') as HTMLMetaElement;
this._setMetaElementAttributes(meta, element);
const head = this._doc.getElementsByTagName('head')[0];
head.appendChild(element);
return element;
}
private _setMetaElementAttributes(tag: MetaDefinition, el: HTMLMetaElement): HTMLMetaElement {
Object.keys(tag).forEach((prop: string) =>
el.setAttribute(this._getMetaKeyMap(prop), tag[prop]),
);
return el;
}
private _parseSelector(tag: MetaDefinition): string {
const attr: string = tag.name ? 'name' : 'property';
return `${attr}="${tag[attr]}"`;
}
private _containsAttributes(tag: MetaDefinition, elem: HTMLMetaElement): boolean {
return Object.keys(tag).every(
(key: string) => elem.getAttribute(this._getMetaKeyMap(key)) === tag[key],
);
}
private _getMetaKeyMap(prop: string): string {
return META_KEYS_MAP[prop] || prop;
}
}
/**
* Mapping for MetaDefinition properties with their correct meta attribute names
*/
const META_KEYS_MAP: {[prop: string]: string} = {
httpEquiv: 'http-equiv',
};
| {
"end_byte": 7878,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/meta.ts"
} |
angular/packages/platform-browser/src/browser/generic_browser_adapter.ts_0_565 | /**
* @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 {ɵDomAdapter as DomAdapter} from '@angular/common';
/**
* Provides DOM operations in any browser environment.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
export abstract class GenericBrowserDomAdapter extends DomAdapter {
override readonly supportsDOMEvents: boolean = true;
}
| {
"end_byte": 565,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/generic_browser_adapter.ts"
} |
angular/packages/platform-browser/src/browser/xhr.ts_0_506 | /**
* @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 {XhrFactory} from '@angular/common';
import {Injectable} from '@angular/core';
/**
* A factory for `HttpXhrBackend` that uses the `XMLHttpRequest` browser API.
*/
@Injectable()
export class BrowserXhr implements XhrFactory {
build(): XMLHttpRequest {
return new XMLHttpRequest();
}
}
| {
"end_byte": 506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/xhr.ts"
} |
angular/packages/platform-browser/src/browser/browser_adapter.ts_0_2922 | /**
* @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 {
ɵparseCookieValue as parseCookieValue,
ɵsetRootDomAdapter as setRootDomAdapter,
} from '@angular/common';
import {GenericBrowserDomAdapter} from './generic_browser_adapter';
/**
* A `DomAdapter` powered by full browser DOM APIs.
*
* @security Tread carefully! Interacting with the DOM directly is dangerous and
* can introduce XSS risks.
*/
/* tslint:disable:requireParameterType no-console */
export class BrowserDomAdapter extends GenericBrowserDomAdapter {
static makeCurrent() {
setRootDomAdapter(new BrowserDomAdapter());
}
override onAndCancel(el: Node, evt: any, listener: any): Function {
el.addEventListener(evt, listener);
return () => {
el.removeEventListener(evt, listener);
};
}
override dispatchEvent(el: Node, evt: any) {
el.dispatchEvent(evt);
}
override remove(node: Node): void {
(node as Element | Text | Comment).remove();
}
override createElement(tagName: string, doc?: Document): HTMLElement {
doc = doc || this.getDefaultDocument();
return doc.createElement(tagName);
}
override createHtmlDocument(): Document {
return document.implementation.createHTMLDocument('fakeTitle');
}
override getDefaultDocument(): Document {
return document;
}
override isElementNode(node: Node): boolean {
return node.nodeType === Node.ELEMENT_NODE;
}
override isShadowRoot(node: any): boolean {
return node instanceof DocumentFragment;
}
/** @deprecated No longer being used in Ivy code. To be removed in version 14. */
override getGlobalEventTarget(doc: Document, target: string): EventTarget | null {
if (target === 'window') {
return window;
}
if (target === 'document') {
return doc;
}
if (target === 'body') {
return doc.body;
}
return null;
}
override getBaseHref(doc: Document): string | null {
const href = getBaseElementHref();
return href == null ? null : relativePath(href);
}
override resetBaseElement(): void {
baseElement = null;
}
override getUserAgent(): string {
return window.navigator.userAgent;
}
override getCookie(name: string): string | null {
return parseCookieValue(document.cookie, name);
}
}
let baseElement: HTMLElement | null = null;
function getBaseElementHref(): string | null {
baseElement = baseElement || document.querySelector('base');
return baseElement ? baseElement.getAttribute('href') : null;
}
function relativePath(url: string): string {
// The base URL doesn't really matter, we just need it so relative paths have something
// to resolve against. In the browser `HTMLBaseElement.href` is always absolute.
return new URL(url, document.baseURI).pathname;
}
| {
"end_byte": 2922,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/browser_adapter.ts"
} |
angular/packages/platform-browser/src/browser/testability.ts_0_2263 | /**
* @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 {ɵgetDOM as getDOM} from '@angular/common';
import {
GetTestability,
Testability,
TestabilityRegistry,
ɵglobal as global,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
export class BrowserGetTestability implements GetTestability {
addToWindow(registry: TestabilityRegistry): void {
global['getAngularTestability'] = (elem: any, findInAncestors: boolean = true) => {
const testability = registry.findTestabilityInTree(elem, findInAncestors);
if (testability == null) {
throw new RuntimeError(
RuntimeErrorCode.TESTABILITY_NOT_FOUND,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
'Could not find testability for element.',
);
}
return testability;
};
global['getAllAngularTestabilities'] = () => registry.getAllTestabilities();
global['getAllAngularRootElements'] = () => registry.getAllRootElements();
const whenAllStable = (callback: () => void) => {
const testabilities = global['getAllAngularTestabilities']() as Testability[];
let count = testabilities.length;
const decrement = function () {
count--;
if (count == 0) {
callback();
}
};
testabilities.forEach((testability) => {
testability.whenStable(decrement);
});
};
if (!global['frameworkStabilizers']) {
global['frameworkStabilizers'] = [];
}
global['frameworkStabilizers'].push(whenAllStable);
}
findTestabilityInTree(
registry: TestabilityRegistry,
elem: any,
findInAncestors: boolean,
): Testability | null {
if (elem == null) {
return null;
}
const t = registry.getTestability(elem);
if (t != null) {
return t;
} else if (!findInAncestors) {
return null;
}
if (getDOM().isShadowRoot(elem)) {
return this.findTestabilityInTree(registry, (<any>elem).host, true);
}
return this.findTestabilityInTree(registry, elem.parentElement, true);
}
}
| {
"end_byte": 2263,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/testability.ts"
} |
angular/packages/platform-browser/src/browser/tools/tools.ts_0_1051 | /**
* @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 {ComponentRef} from '@angular/core';
import {exportNgVar} from '../../dom/util';
import {AngularProfiler} from './common_tools';
const PROFILER_GLOBAL_NAME = 'profiler';
/**
* Enabled Angular debug tools that are accessible via your browser's
* developer console.
*
* Usage:
*
* 1. Open developer console (e.g. in Chrome Ctrl + Shift + j)
* 1. Type `ng.` (usually the console will show auto-complete suggestion)
* 1. Try the change detection profiler `ng.profiler.timeChangeDetection()`
* then hit Enter.
*
* @publicApi
*/
export function enableDebugTools<T>(ref: ComponentRef<T>): ComponentRef<T> {
exportNgVar(PROFILER_GLOBAL_NAME, new AngularProfiler(ref));
return ref;
}
/**
* Disables Angular tools.
*
* @publicApi
*/
export function disableDebugTools(): void {
exportNgVar(PROFILER_GLOBAL_NAME, null);
}
| {
"end_byte": 1051,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/tools/tools.ts"
} |
angular/packages/platform-browser/src/browser/tools/common_tools.ts_0_2244 | /**
* @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, ComponentRef} from '@angular/core';
export class ChangeDetectionPerfRecord {
constructor(
public msPerTick: number,
public numTicks: number,
) {}
}
/**
* Entry point for all Angular profiling-related debug tools. This object
* corresponds to the `ng.profiler` in the dev console.
*/
export class AngularProfiler {
appRef: ApplicationRef;
constructor(ref: ComponentRef<any>) {
this.appRef = ref.injector.get(ApplicationRef);
}
// tslint:disable:no-console
/**
* Exercises change detection in a loop and then prints the average amount of
* time in milliseconds how long a single round of change detection takes for
* the current state of the UI. It runs a minimum of 5 rounds for a minimum
* of 500 milliseconds.
*
* Optionally, a user may pass a `config` parameter containing a map of
* options. Supported options are:
*
* `record` (boolean) - causes the profiler to record a CPU profile while
* it exercises the change detector. Example:
*
* ```
* ng.profiler.timeChangeDetection({record: true})
* ```
*/
timeChangeDetection(config: any): ChangeDetectionPerfRecord {
const record = config && config['record'];
const profileName = 'Change Detection';
// Profiler is not available in Android browsers without dev tools opened
if (record && 'profile' in console && typeof console.profile === 'function') {
console.profile(profileName);
}
const start = performance.now();
let numTicks = 0;
while (numTicks < 5 || performance.now() - start < 500) {
this.appRef.tick();
numTicks++;
}
const end = performance.now();
if (record && 'profileEnd' in console && typeof console.profileEnd === 'function') {
console.profileEnd(profileName);
}
const msPerTick = (end - start) / numTicks;
console.log(`ran ${numTicks} change detection cycles`);
console.log(`${msPerTick.toFixed(2)} ms per check`);
return new ChangeDetectionPerfRecord(msPerTick, numTicks);
}
}
| {
"end_byte": 2244,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/browser/tools/common_tools.ts"
} |
angular/packages/platform-browser/src/dom/dom_renderer.ts_0_5542 | /**
* @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, isPlatformServer, ɵgetDOM as getDOM} from '@angular/common';
import {
APP_ID,
CSP_NONCE,
Inject,
Injectable,
InjectionToken,
NgZone,
OnDestroy,
PLATFORM_ID,
Renderer2,
RendererFactory2,
RendererStyleFlags2,
RendererType2,
ViewEncapsulation,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
import {EventManager} from './events/event_manager';
import {SharedStylesHost} from './shared_styles_host';
export const NAMESPACE_URIS: {[ns: string]: string} = {
'svg': 'http://www.w3.org/2000/svg',
'xhtml': 'http://www.w3.org/1999/xhtml',
'xlink': 'http://www.w3.org/1999/xlink',
'xml': 'http://www.w3.org/XML/1998/namespace',
'xmlns': 'http://www.w3.org/2000/xmlns/',
'math': 'http://www.w3.org/1998/Math/MathML',
};
const COMPONENT_REGEX = /%COMP%/g;
export const COMPONENT_VARIABLE = '%COMP%';
export const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
export const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
/**
* The default value for the `REMOVE_STYLES_ON_COMPONENT_DESTROY` DI token.
*/
const REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT = true;
/**
* A DI token that indicates whether styles
* of destroyed components should be removed from DOM.
*
* By default, the value is set to `true`.
* @publicApi
*/
export const REMOVE_STYLES_ON_COMPONENT_DESTROY = new InjectionToken<boolean>(
ngDevMode ? 'RemoveStylesOnCompDestroy' : '',
{
providedIn: 'root',
factory: () => REMOVE_STYLES_ON_COMPONENT_DESTROY_DEFAULT,
},
);
export function shimContentAttribute(componentShortId: string): string {
return CONTENT_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
export function shimHostAttribute(componentShortId: string): string {
return HOST_ATTR.replace(COMPONENT_REGEX, componentShortId);
}
export function shimStylesContent(compId: string, styles: string[]): string[] {
return styles.map((s) => s.replace(COMPONENT_REGEX, compId));
}
@Injectable()
export class DomRendererFactory2 implements RendererFactory2, OnDestroy {
private readonly rendererByCompId = new Map<
string,
EmulatedEncapsulationDomRenderer2 | NoneEncapsulationDomRenderer
>();
private readonly defaultRenderer: Renderer2;
private readonly platformIsServer: boolean;
constructor(
private readonly eventManager: EventManager,
private readonly sharedStylesHost: SharedStylesHost,
@Inject(APP_ID) private readonly appId: string,
@Inject(REMOVE_STYLES_ON_COMPONENT_DESTROY) private removeStylesOnCompDestroy: boolean,
@Inject(DOCUMENT) private readonly doc: Document,
@Inject(PLATFORM_ID) readonly platformId: Object,
readonly ngZone: NgZone,
@Inject(CSP_NONCE) private readonly nonce: string | null = null,
) {
this.platformIsServer = isPlatformServer(platformId);
this.defaultRenderer = new DefaultDomRenderer2(
eventManager,
doc,
ngZone,
this.platformIsServer,
);
}
createRenderer(element: any, type: RendererType2 | null): Renderer2 {
if (!element || !type) {
return this.defaultRenderer;
}
if (this.platformIsServer && type.encapsulation === ViewEncapsulation.ShadowDom) {
// Domino does not support shadow DOM.
type = {...type, encapsulation: ViewEncapsulation.Emulated};
}
const renderer = this.getOrCreateRenderer(element, type);
// Renderers have different logic due to different encapsulation behaviours.
// Ex: for emulated, an attribute is added to the element.
if (renderer instanceof EmulatedEncapsulationDomRenderer2) {
renderer.applyToHost(element);
} else if (renderer instanceof NoneEncapsulationDomRenderer) {
renderer.applyStyles();
}
return renderer;
}
private getOrCreateRenderer(element: any, type: RendererType2): Renderer2 {
const rendererByCompId = this.rendererByCompId;
let renderer = rendererByCompId.get(type.id);
if (!renderer) {
const doc = this.doc;
const ngZone = this.ngZone;
const eventManager = this.eventManager;
const sharedStylesHost = this.sharedStylesHost;
const removeStylesOnCompDestroy = this.removeStylesOnCompDestroy;
const platformIsServer = this.platformIsServer;
switch (type.encapsulation) {
case ViewEncapsulation.Emulated:
renderer = new EmulatedEncapsulationDomRenderer2(
eventManager,
sharedStylesHost,
type,
this.appId,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
);
break;
case ViewEncapsulation.ShadowDom:
return new ShadowDomRenderer(
eventManager,
sharedStylesHost,
element,
type,
doc,
ngZone,
this.nonce,
platformIsServer,
);
default:
renderer = new NoneEncapsulationDomRenderer(
eventManager,
sharedStylesHost,
type,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
);
break;
}
rendererByCompId.set(type.id, renderer);
}
return renderer;
}
ngOnDestroy() {
this.rendererByCompId.clear();
}
}
| {
"end_byte": 5542,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/dom_renderer.ts"
} |
angular/packages/platform-browser/src/dom/dom_renderer.ts_5544_12787 | ass DefaultDomRenderer2 implements Renderer2 {
data: {[key: string]: any} = Object.create(null);
/**
* By default this renderer throws when encountering synthetic properties
* This can be disabled for example by the AsyncAnimationRendererFactory
*/
throwOnSyntheticProps = true;
constructor(
private readonly eventManager: EventManager,
private readonly doc: Document,
private readonly ngZone: NgZone,
private readonly platformIsServer: boolean,
) {}
destroy(): void {}
destroyNode = null;
createElement(name: string, namespace?: string): any {
if (namespace) {
// TODO: `|| namespace` was added in
// https://github.com/angular/angular/commit/2b9cc8503d48173492c29f5a271b61126104fbdb to
// support how Ivy passed around the namespace URI rather than short name at the time. It did
// not, however extend the support to other parts of the system (setAttribute, setAttribute,
// and the ServerRenderer). We should decide what exactly the semantics for dealing with
// namespaces should be and make it consistent.
// Related issues:
// https://github.com/angular/angular/issues/44028
// https://github.com/angular/angular/issues/44883
return this.doc.createElementNS(NAMESPACE_URIS[namespace] || namespace, name);
}
return this.doc.createElement(name);
}
createComment(value: string): any {
return this.doc.createComment(value);
}
createText(value: string): any {
return this.doc.createTextNode(value);
}
appendChild(parent: any, newChild: any): void {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.appendChild(newChild);
}
insertBefore(parent: any, newChild: any, refChild: any): void {
if (parent) {
const targetParent = isTemplateNode(parent) ? parent.content : parent;
targetParent.insertBefore(newChild, refChild);
}
}
removeChild(_parent: any, oldChild: any): void {
oldChild.remove();
}
selectRootElement(selectorOrNode: string | any, preserveContent?: boolean): any {
let el: any =
typeof selectorOrNode === 'string' ? this.doc.querySelector(selectorOrNode) : selectorOrNode;
if (!el) {
throw new RuntimeError(
RuntimeErrorCode.ROOT_NODE_NOT_FOUND,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`The selector "${selectorOrNode}" did not match any elements`,
);
}
if (!preserveContent) {
el.textContent = '';
}
return el;
}
parentNode(node: any): any {
return node.parentNode;
}
nextSibling(node: any): any {
return node.nextSibling;
}
setAttribute(el: any, name: string, value: string, namespace?: string): void {
if (namespace) {
name = namespace + ':' + name;
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.setAttributeNS(namespaceUri, name, value);
} else {
el.setAttribute(name, value);
}
} else {
el.setAttribute(name, value);
}
}
removeAttribute(el: any, name: string, namespace?: string): void {
if (namespace) {
const namespaceUri = NAMESPACE_URIS[namespace];
if (namespaceUri) {
el.removeAttributeNS(namespaceUri, name);
} else {
el.removeAttribute(`${namespace}:${name}`);
}
} else {
el.removeAttribute(name);
}
}
addClass(el: any, name: string): void {
el.classList.add(name);
}
removeClass(el: any, name: string): void {
el.classList.remove(name);
}
setStyle(el: any, style: string, value: any, flags: RendererStyleFlags2): void {
if (flags & (RendererStyleFlags2.DashCase | RendererStyleFlags2.Important)) {
el.style.setProperty(style, value, flags & RendererStyleFlags2.Important ? 'important' : '');
} else {
el.style[style] = value;
}
}
removeStyle(el: any, style: string, flags: RendererStyleFlags2): void {
if (flags & RendererStyleFlags2.DashCase) {
// removeProperty has no effect when used on camelCased properties.
el.style.removeProperty(style);
} else {
el.style[style] = '';
}
}
setProperty(el: any, name: string, value: any): void {
if (el == null) {
return;
}
(typeof ngDevMode === 'undefined' || ngDevMode) &&
this.throwOnSyntheticProps &&
checkNoSyntheticProp(name, 'property');
el[name] = value;
}
setValue(node: any, value: string): void {
node.nodeValue = value;
}
listen(
target: 'window' | 'document' | 'body' | any,
event: string,
callback: (event: any) => boolean,
): () => void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
this.throwOnSyntheticProps &&
checkNoSyntheticProp(event, 'listener');
if (typeof target === 'string') {
target = getDOM().getGlobalEventTarget(this.doc, target);
if (!target) {
throw new Error(`Unsupported event target ${target} for event ${event}`);
}
}
return this.eventManager.addEventListener(
target,
event,
this.decoratePreventDefault(callback),
) as VoidFunction;
}
private decoratePreventDefault(eventHandler: Function): Function {
// `DebugNode.triggerEventHandler` needs to know if the listener was created with
// decoratePreventDefault or is a listener added outside the Angular context so it can handle
// the two differently. In the first case, the special '__ngUnwrap__' token is passed to the
// unwrap the listener (see below).
return (event: any) => {
// Ivy uses '__ngUnwrap__' as a special token that allows us to unwrap the function
// so that it can be invoked programmatically by `DebugNode.triggerEventHandler`. The
// debug_node can inspect the listener toString contents for the existence of this special
// token. Because the token is a string literal, it is ensured to not be modified by compiled
// code.
if (event === '__ngUnwrap__') {
return eventHandler;
}
// Run the event handler inside the ngZone because event handlers are not patched
// by Zone on the server. This is required only for tests.
const allowDefaultBehavior = this.platformIsServer
? this.ngZone.runGuarded(() => eventHandler(event))
: eventHandler(event);
if (allowDefaultBehavior === false) {
event.preventDefault();
}
return undefined;
};
}
}
const AT_CHARCODE = (() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name: string, nameKind: string) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new RuntimeError(
RuntimeErrorCode.UNEXPECTED_SYNTHETIC_PROPERTY,
`Unexpected synthetic ${nameKind} ${name} found. Please make sure that:
- Either \`BrowserAnimationsModule\` or \`NoopAnimationsModule\` are imported in your application.
- There is corresponding configuration for the animation named \`${name}\` defined in the \`animations\` field of the \`@Component\` decorator (see https://angular.io/api/core/Component#animations).`,
);
}
}
function isTemplateNode(node: any): node is HTMLTemplateElement {
return node.tagName === 'TEMPLATE' && node.content !== undefined;
}
| {
"end_byte": 12787,
"start_byte": 5544,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/dom_renderer.ts"
} |
angular/packages/platform-browser/src/dom/dom_renderer.ts_12789_16265 | ass ShadowDomRenderer extends DefaultDomRenderer2 {
private shadowRoot: any;
constructor(
eventManager: EventManager,
private sharedStylesHost: SharedStylesHost,
private hostEl: any,
component: RendererType2,
doc: Document,
ngZone: NgZone,
nonce: string | null,
platformIsServer: boolean,
) {
super(eventManager, doc, ngZone, platformIsServer);
this.shadowRoot = (hostEl as any).attachShadow({mode: 'open'});
this.sharedStylesHost.addHost(this.shadowRoot);
const styles = shimStylesContent(component.id, component.styles);
for (const style of styles) {
const styleEl = document.createElement('style');
if (nonce) {
styleEl.setAttribute('nonce', nonce);
}
styleEl.textContent = style;
this.shadowRoot.appendChild(styleEl);
}
}
private nodeOrShadowRoot(node: any): any {
return node === this.hostEl ? this.shadowRoot : node;
}
override appendChild(parent: any, newChild: any): void {
return super.appendChild(this.nodeOrShadowRoot(parent), newChild);
}
override insertBefore(parent: any, newChild: any, refChild: any): void {
return super.insertBefore(this.nodeOrShadowRoot(parent), newChild, refChild);
}
override removeChild(_parent: any, oldChild: any): void {
return super.removeChild(null, oldChild);
}
override parentNode(node: any): any {
return this.nodeOrShadowRoot(super.parentNode(this.nodeOrShadowRoot(node)));
}
override destroy() {
this.sharedStylesHost.removeHost(this.shadowRoot);
}
}
class NoneEncapsulationDomRenderer extends DefaultDomRenderer2 {
private readonly styles: string[];
private readonly styleUrls?: string[];
constructor(
eventManager: EventManager,
private readonly sharedStylesHost: SharedStylesHost,
component: RendererType2,
private removeStylesOnCompDestroy: boolean,
doc: Document,
ngZone: NgZone,
platformIsServer: boolean,
compId?: string,
) {
super(eventManager, doc, ngZone, platformIsServer);
this.styles = compId ? shimStylesContent(compId, component.styles) : component.styles;
this.styleUrls = component.getExternalStyles?.(compId);
}
applyStyles(): void {
this.sharedStylesHost.addStyles(this.styles, this.styleUrls);
}
override destroy(): void {
if (!this.removeStylesOnCompDestroy) {
return;
}
this.sharedStylesHost.removeStyles(this.styles, this.styleUrls);
}
}
class EmulatedEncapsulationDomRenderer2 extends NoneEncapsulationDomRenderer {
private contentAttr: string;
private hostAttr: string;
constructor(
eventManager: EventManager,
sharedStylesHost: SharedStylesHost,
component: RendererType2,
appId: string,
removeStylesOnCompDestroy: boolean,
doc: Document,
ngZone: NgZone,
platformIsServer: boolean,
) {
const compId = appId + '-' + component.id;
super(
eventManager,
sharedStylesHost,
component,
removeStylesOnCompDestroy,
doc,
ngZone,
platformIsServer,
compId,
);
this.contentAttr = shimContentAttribute(compId);
this.hostAttr = shimHostAttribute(compId);
}
applyToHost(element: any): void {
this.applyStyles();
this.setAttribute(element, this.hostAttr, '');
}
override createElement(parent: any, name: string): Element {
const el = super.createElement(parent, name);
super.setAttribute(el, this.contentAttr, '');
return el;
}
}
| {
"end_byte": 16265,
"start_byte": 12789,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/dom_renderer.ts"
} |
angular/packages/platform-browser/src/dom/shared_styles_host.ts_0_7512 | /**
* @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, isPlatformServer} from '@angular/common';
import {
APP_ID,
CSP_NONCE,
Inject,
Injectable,
OnDestroy,
Optional,
PLATFORM_ID,
} from '@angular/core';
/** The style elements attribute name used to set value of `APP_ID` token. */
const APP_ID_ATTRIBUTE_NAME = 'ng-app-id';
/**
* A record of usage for a specific style including all elements added to the DOM
* that contain a given style.
*/
interface UsageRecord<T> {
elements: T[];
usage: number;
}
/**
* Removes all provided elements from the document.
* @param elements An array of HTML Elements.
*/
function removeElements(elements: Iterable<HTMLElement>): void {
for (const element of elements) {
element.remove();
}
}
/**
* Creates a `style` element with the provided inline style content.
* @param style A string of the inline style content.
* @param doc A DOM Document to use to create the element.
* @returns An HTMLStyleElement instance.
*/
function createStyleElement(style: string, doc: Document): HTMLStyleElement {
const styleElement = doc.createElement('style');
styleElement.textContent = style;
return styleElement;
}
/**
* Searches a DOM document's head element for style elements with a matching application
* identifier attribute (`ng-app-id`) to the provide identifier and adds usage records for each.
* @param doc An HTML DOM document instance.
* @param appId A string containing an Angular application identifer.
* @param usages A Map object for tracking style usage.
*/
function addServerStyles(
doc: Document,
appId: string,
usages: Map<string, UsageRecord<HTMLStyleElement>>,
): void {
const styleElements = doc.head?.querySelectorAll<HTMLStyleElement>(
`style[${APP_ID_ATTRIBUTE_NAME}="${appId}"]`,
);
if (styleElements) {
for (const styleElement of styleElements) {
if (styleElement.textContent) {
styleElement.removeAttribute(APP_ID_ATTRIBUTE_NAME);
usages.set(styleElement.textContent, {usage: 0, elements: [styleElement]});
}
}
}
}
/**
* Creates a `link` element for the provided external style URL.
* @param url A string of the URL for the stylesheet.
* @param doc A DOM Document to use to create the element.
* @returns An HTMLLinkElement instance.
*/
function createLinkElement(url: string, doc: Document): HTMLLinkElement {
const linkElement = doc.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('href', url);
return linkElement;
}
@Injectable()
export class SharedStylesHost implements OnDestroy {
/**
* Provides usage information for active inline style content and associated HTML <style> elements.
* Embedded styles typically originate from the `styles` metadata of a rendered component.
*/
private readonly inline = new Map<string /** content */, UsageRecord<HTMLStyleElement>>();
/**
* Provides usage information for active external style URLs and the associated HTML <link> elements.
* External styles typically originate from the `ɵɵExternalStylesFeature` of a rendered component.
*/
private readonly external = new Map<string /** URL */, UsageRecord<HTMLLinkElement>>();
/**
* Set of host DOM nodes that will have styles attached.
*/
private readonly hosts = new Set<Node>();
/**
* Whether the application code is currently executing on a server.
*/
private readonly isServer: boolean;
constructor(
@Inject(DOCUMENT) private readonly doc: Document,
@Inject(APP_ID) private readonly appId: string,
@Inject(CSP_NONCE) @Optional() private readonly nonce?: string | null,
@Inject(PLATFORM_ID) platformId: object = {},
) {
this.isServer = isPlatformServer(platformId);
addServerStyles(doc, appId, this.inline);
this.hosts.add(doc.head);
}
/**
* Adds embedded styles to the DOM via HTML `style` elements.
* @param styles An array of style content strings.
*/
addStyles(styles: string[], urls?: string[]): void {
for (const value of styles) {
this.addUsage(value, this.inline, createStyleElement);
}
urls?.forEach((value) => this.addUsage(value, this.external, createLinkElement));
}
/**
* Removes embedded styles from the DOM that were added as HTML `style` elements.
* @param styles An array of style content strings.
*/
removeStyles(styles: string[], urls?: string[]): void {
for (const value of styles) {
this.removeUsage(value, this.inline);
}
urls?.forEach((value) => this.removeUsage(value, this.external));
}
protected addUsage<T extends HTMLElement>(
value: string,
usages: Map<string, UsageRecord<T>>,
creator: (value: string, doc: Document) => T,
): void {
// Attempt to get any current usage of the value
const record = usages.get(value);
// If existing, just increment the usage count
if (record) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && record.usage === 0) {
// A usage count of zero indicates a preexisting server generated style.
// This attribute is solely used for debugging purposes of SSR style reuse.
record.elements.forEach((element) => element.setAttribute('ng-style-reused', ''));
}
record.usage++;
} else {
// Otherwise, create an entry to track the elements and add element for each host
usages.set(value, {
usage: 1,
elements: [...this.hosts].map((host) => this.addElement(host, creator(value, this.doc))),
});
}
}
protected removeUsage<T extends HTMLElement>(
value: string,
usages: Map<string, UsageRecord<T>>,
): void {
// Attempt to get any current usage of the value
const record = usages.get(value);
// If there is a record, reduce the usage count and if no longer used,
// remove from DOM and delete usage record.
if (record) {
record.usage--;
if (record.usage <= 0) {
removeElements(record.elements);
usages.delete(value);
}
}
}
ngOnDestroy(): void {
for (const [, {elements}] of [...this.inline, ...this.external]) {
removeElements(elements);
}
this.hosts.clear();
}
/**
* Adds a host node to the set of style hosts and adds all existing style usage to
* the newly added host node.
*
* This is currently only used for Shadow DOM encapsulation mode.
*/
addHost(hostNode: Node): void {
this.hosts.add(hostNode);
// Add existing styles to new host
for (const [style, {elements}] of this.inline) {
elements.push(this.addElement(hostNode, createStyleElement(style, this.doc)));
}
for (const [url, {elements}] of this.external) {
elements.push(this.addElement(hostNode, createLinkElement(url, this.doc)));
}
}
removeHost(hostNode: Node): void {
this.hosts.delete(hostNode);
}
private addElement<T extends HTMLElement>(host: Node, element: T): T {
// Add a nonce if present
if (this.nonce) {
element.setAttribute('nonce', this.nonce);
}
// Add application identifier when on the server to support client-side reuse
if (this.isServer) {
element.setAttribute(APP_ID_ATTRIBUTE_NAME, this.appId);
}
// Insert the element into the DOM with the host node as parent
return host.appendChild(element);
}
}
| {
"end_byte": 7512,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/shared_styles_host.ts"
} |
angular/packages/platform-browser/src/dom/util.ts_0_1117 | /**
* @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 as global} from '@angular/core';
/**
* Exports the value under a given `name` in the global property `ng`. For example `ng.probe` if
* `name` is `'probe'`.
* @param name Name under which it will be exported. Keep in mind this will be a property of the
* global `ng` object.
* @param value The value to export.
*/
export function exportNgVar(name: string, value: any): void {
if (typeof COMPILED === 'undefined' || !COMPILED) {
// Note: we can't export `ng` when using closure enhanced optimization as:
// - closure declares globals itself for minified names, which sometimes clobber our `ng` global
// - we can't declare a closure extern as the namespace `ng` is already used within Google
// for typings for angularJS (via `goog.provide('ng....')`).
const ng = (global['ng'] = (global['ng'] as {[key: string]: any} | undefined) || {});
ng[name] = value;
}
}
| {
"end_byte": 1117,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/util.ts"
} |
angular/packages/platform-browser/src/dom/events/dom_events.ts_0_1086 | /**
* @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 {Inject, Injectable} from '@angular/core';
import {EventManagerPlugin} from './event_manager';
@Injectable()
export class DomEventsPlugin extends EventManagerPlugin {
constructor(@Inject(DOCUMENT) doc: any) {
super(doc);
}
// This plugin should come last in the list of plugins, because it accepts all
// events.
override supports(eventName: string): boolean {
return true;
}
override addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
element.addEventListener(eventName, handler as EventListener, false);
return () => this.removeEventListener(element, eventName, handler as EventListener);
}
removeEventListener(target: any, eventName: string, callback: Function): void {
return target.removeEventListener(eventName, callback as EventListener);
}
}
| {
"end_byte": 1086,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/events/dom_events.ts"
} |
angular/packages/platform-browser/src/dom/events/event_manager.ts_0_3288 | /**
* @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 {
Inject,
Injectable,
InjectionToken,
NgZone,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../../errors';
/**
* The injection token for plugins of the `EventManager` service.
*
* @publicApi
*/
export const EVENT_MANAGER_PLUGINS = new InjectionToken<EventManagerPlugin[]>(
ngDevMode ? 'EventManagerPlugins' : '',
);
/**
* An injectable service that provides event management for Angular
* through a browser plug-in.
*
* @publicApi
*/
@Injectable()
export class EventManager {
private _plugins: EventManagerPlugin[];
private _eventNameToPlugin = new Map<string, EventManagerPlugin>();
/**
* Initializes an instance of the event-manager service.
*/
constructor(
@Inject(EVENT_MANAGER_PLUGINS) plugins: EventManagerPlugin[],
private _zone: NgZone,
) {
plugins.forEach((plugin) => {
plugin.manager = this;
});
this._plugins = plugins.slice().reverse();
}
/**
* Registers a handler for a specific element and event.
*
* @param element The HTML element to receive event notifications.
* @param eventName The name of the event to listen for.
* @param handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @returns A callback function that can be used to remove the handler.
*/
addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
const plugin = this._findPluginFor(eventName);
return plugin.addEventListener(element, eventName, handler);
}
/**
* Retrieves the compilation zone in which event listeners are registered.
*/
getZone(): NgZone {
return this._zone;
}
/** @internal */
_findPluginFor(eventName: string): EventManagerPlugin {
let plugin = this._eventNameToPlugin.get(eventName);
if (plugin) {
return plugin;
}
const plugins = this._plugins;
plugin = plugins.find((plugin) => plugin.supports(eventName));
if (!plugin) {
throw new RuntimeError(
RuntimeErrorCode.NO_PLUGIN_FOR_EVENT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`No event manager plugin found for event ${eventName}`,
);
}
this._eventNameToPlugin.set(eventName, plugin);
return plugin;
}
}
/**
* The plugin definition for the `EventManager` class
*
* It can be used as a base class to create custom manager plugins, i.e. you can create your own
* class that extends the `EventManagerPlugin` one.
*
* @publicApi
*/
export abstract class EventManagerPlugin {
// TODO: remove (has some usage in G3)
constructor(private _doc: any) {}
// Using non-null assertion because it's set by EventManager's constructor
manager!: EventManager;
/**
* Should return `true` for every event name that should be supported by this plugin
*/
abstract supports(eventName: string): boolean;
/**
* Implement the behaviour for the supported events
*/
abstract addEventListener(element: HTMLElement, eventName: string, handler: Function): Function;
}
| {
"end_byte": 3288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/events/event_manager.ts"
} |
angular/packages/platform-browser/src/dom/events/key_events.ts_0_6633 | /**
* @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, ɵgetDOM as getDOM} from '@angular/common';
import {Inject, Injectable, NgZone} from '@angular/core';
import {EventManagerPlugin} from './event_manager';
/**
* Defines supported modifiers for key events.
*/
const MODIFIER_KEYS = ['alt', 'control', 'meta', 'shift'];
// The following values are here for cross-browser compatibility and to match the W3C standard
// cf https://www.w3.org/TR/DOM-Level-3-Events-key/
const _keyMap: {[k: string]: string} = {
'\b': 'Backspace',
'\t': 'Tab',
'\x7F': 'Delete',
'\x1B': 'Escape',
'Del': 'Delete',
'Esc': 'Escape',
'Left': 'ArrowLeft',
'Right': 'ArrowRight',
'Up': 'ArrowUp',
'Down': 'ArrowDown',
'Menu': 'ContextMenu',
'Scroll': 'ScrollLock',
'Win': 'OS',
};
/**
* Retrieves modifiers from key-event objects.
*/
const MODIFIER_KEY_GETTERS: {[key: string]: (event: KeyboardEvent) => boolean} = {
'alt': (event: KeyboardEvent) => event.altKey,
'control': (event: KeyboardEvent) => event.ctrlKey,
'meta': (event: KeyboardEvent) => event.metaKey,
'shift': (event: KeyboardEvent) => event.shiftKey,
};
/**
* A browser plug-in that provides support for handling of key events in Angular.
*/
@Injectable()
export class KeyEventsPlugin extends EventManagerPlugin {
/**
* Initializes an instance of the browser plug-in.
* @param doc The document in which key events will be detected.
*/
constructor(@Inject(DOCUMENT) doc: any) {
super(doc);
}
/**
* Reports whether a named key event is supported.
* @param eventName The event name to query.
* @return True if the named key event is supported.
*/
override supports(eventName: string): boolean {
return KeyEventsPlugin.parseEventName(eventName) != null;
}
/**
* Registers a handler for a specific element and key event.
* @param element The HTML element to receive event notifications.
* @param eventName The name of the key event to listen for.
* @param handler A function to call when the notification occurs. Receives the
* event object as an argument.
* @returns The key event that was registered.
*/
override addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
const parsedEvent = KeyEventsPlugin.parseEventName(eventName)!;
const outsideHandler = KeyEventsPlugin.eventCallback(
parsedEvent['fullKey'],
handler,
this.manager.getZone(),
);
return this.manager.getZone().runOutsideAngular(() => {
return getDOM().onAndCancel(element, parsedEvent['domEventName'], outsideHandler);
});
}
/**
* Parses the user provided full keyboard event definition and normalizes it for
* later internal use. It ensures the string is all lowercase, converts special
* characters to a standard spelling, and orders all the values consistently.
*
* @param eventName The name of the key event to listen for.
* @returns an object with the full, normalized string, and the dom event name
* or null in the case when the event doesn't match a keyboard event.
*/
static parseEventName(eventName: string): {fullKey: string; domEventName: string} | null {
const parts: string[] = eventName.toLowerCase().split('.');
const domEventName = parts.shift();
if (parts.length === 0 || !(domEventName === 'keydown' || domEventName === 'keyup')) {
return null;
}
const key = KeyEventsPlugin._normalizeKey(parts.pop()!);
let fullKey = '';
let codeIX = parts.indexOf('code');
if (codeIX > -1) {
parts.splice(codeIX, 1);
fullKey = 'code.';
}
MODIFIER_KEYS.forEach((modifierName) => {
const index: number = parts.indexOf(modifierName);
if (index > -1) {
parts.splice(index, 1);
fullKey += modifierName + '.';
}
});
fullKey += key;
if (parts.length != 0 || key.length === 0) {
// returning null instead of throwing to let another plugin process the event
return null;
}
// NOTE: Please don't rewrite this as so, as it will break JSCompiler property renaming.
// The code must remain in the `result['domEventName']` form.
// return {domEventName, fullKey};
const result: {fullKey: string; domEventName: string} = {} as any;
result['domEventName'] = domEventName;
result['fullKey'] = fullKey;
return result;
}
/**
* Determines whether the actual keys pressed match the configured key code string.
* The `fullKeyCode` event is normalized in the `parseEventName` method when the
* event is attached to the DOM during the `addEventListener` call. This is unseen
* by the end user and is normalized for internal consistency and parsing.
*
* @param event The keyboard event.
* @param fullKeyCode The normalized user defined expected key event string
* @returns boolean.
*/
static matchEventFullKeyCode(event: KeyboardEvent, fullKeyCode: string): boolean {
let keycode = _keyMap[event.key] || event.key;
let key = '';
if (fullKeyCode.indexOf('code.') > -1) {
keycode = event.code;
key = 'code.';
}
// the keycode could be unidentified so we have to check here
if (keycode == null || !keycode) return false;
keycode = keycode.toLowerCase();
if (keycode === ' ') {
keycode = 'space'; // for readability
} else if (keycode === '.') {
keycode = 'dot'; // because '.' is used as a separator in event names
}
MODIFIER_KEYS.forEach((modifierName) => {
if (modifierName !== keycode) {
const modifierGetter = MODIFIER_KEY_GETTERS[modifierName];
if (modifierGetter(event)) {
key += modifierName + '.';
}
}
});
key += keycode;
return key === fullKeyCode;
}
/**
* Configures a handler callback for a key event.
* @param fullKey The event name that combines all simultaneous keystrokes.
* @param handler The function that responds to the key event.
* @param zone The zone in which the event occurred.
* @returns A callback function.
*/
static eventCallback(fullKey: string, handler: Function, zone: NgZone): Function {
return (event: KeyboardEvent) => {
if (KeyEventsPlugin.matchEventFullKeyCode(event, fullKey)) {
zone.runGuarded(() => handler(event));
}
};
}
/** @internal */
static _normalizeKey(keyName: string): string {
return keyName === 'esc' ? 'escape' : keyName;
}
}
| {
"end_byte": 6633,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/events/key_events.ts"
} |
angular/packages/platform-browser/src/dom/events/hammer_gestures.ts_0_8288 | /**
* @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 {
Inject,
Injectable,
InjectionToken,
NgModule,
Optional,
Provider,
ɵConsole as Console,
} from '@angular/core';
import {EVENT_MANAGER_PLUGINS, EventManagerPlugin} from './event_manager';
/**
* Supported HammerJS recognizer event names.
*/
const EVENT_NAMES = {
// pan
'pan': true,
'panstart': true,
'panmove': true,
'panend': true,
'pancancel': true,
'panleft': true,
'panright': true,
'panup': true,
'pandown': true,
// pinch
'pinch': true,
'pinchstart': true,
'pinchmove': true,
'pinchend': true,
'pinchcancel': true,
'pinchin': true,
'pinchout': true,
// press
'press': true,
'pressup': true,
// rotate
'rotate': true,
'rotatestart': true,
'rotatemove': true,
'rotateend': true,
'rotatecancel': true,
// swipe
'swipe': true,
'swipeleft': true,
'swiperight': true,
'swipeup': true,
'swipedown': true,
// tap
'tap': true,
'doubletap': true,
};
/**
* DI token for providing [HammerJS](https://hammerjs.github.io/) support to Angular.
* @see {@link HammerGestureConfig}
*
* @ngModule HammerModule
* @publicApi
*/
export const HAMMER_GESTURE_CONFIG = new InjectionToken<HammerGestureConfig>('HammerGestureConfig');
/**
* Function that loads HammerJS, returning a promise that is resolved once HammerJs is loaded.
*
* @publicApi
*/
export type HammerLoader = () => Promise<void>;
/**
* Injection token used to provide a HammerLoader to Angular.
*
* @see {@link HammerLoader}
*
* @publicApi
*/
export const HAMMER_LOADER = new InjectionToken<HammerLoader>('HammerLoader');
export interface HammerInstance {
on(eventName: string, callback?: Function): void;
off(eventName: string, callback?: Function): void;
destroy?(): void;
}
/**
* An injectable [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager)
* for gesture recognition. Configures specific event recognition.
* @publicApi
*/
@Injectable()
export class HammerGestureConfig {
/**
* A set of supported event names for gestures to be used in Angular.
* Angular supports all built-in recognizers, as listed in
* [HammerJS documentation](https://hammerjs.github.io/).
*/
events: string[] = [];
/**
* Maps gesture event names to a set of configuration options
* that specify overrides to the default values for specific properties.
*
* The key is a supported event name to be configured,
* and the options object contains a set of properties, with override values
* to be applied to the named recognizer event.
* For example, to disable recognition of the rotate event, specify
* `{"rotate": {"enable": false}}`.
*
* Properties that are not present take the HammerJS default values.
* For information about which properties are supported for which events,
* and their allowed and default values, see
* [HammerJS documentation](https://hammerjs.github.io/).
*
*/
overrides: {[key: string]: Object} = {};
/**
* Properties whose default values can be overridden for a given event.
* Different sets of properties apply to different events.
* For information about which properties are supported for which events,
* and their allowed and default values, see
* [HammerJS documentation](https://hammerjs.github.io/).
*/
options?: {
cssProps?: any;
domEvents?: boolean;
enable?: boolean | ((manager: any) => boolean);
preset?: any[];
touchAction?: string;
recognizers?: any[];
inputClass?: any;
inputTarget?: EventTarget;
};
/**
* Creates a [HammerJS Manager](https://hammerjs.github.io/api/#hammermanager)
* and attaches it to a given HTML element.
* @param element The element that will recognize gestures.
* @returns A HammerJS event-manager object.
*/
buildHammer(element: HTMLElement): HammerInstance {
const mc = new Hammer!(element, this.options);
mc.get('pinch').set({enable: true});
mc.get('rotate').set({enable: true});
for (const eventName in this.overrides) {
mc.get(eventName).set(this.overrides[eventName]);
}
return mc;
}
}
/**
* Event plugin that adds Hammer support to an application.
*
* @ngModule HammerModule
*/
@Injectable()
export class HammerGesturesPlugin extends EventManagerPlugin {
private _loaderPromise: Promise<void> | null = null;
constructor(
@Inject(DOCUMENT) doc: any,
@Inject(HAMMER_GESTURE_CONFIG) private _config: HammerGestureConfig,
private console: Console,
@Optional() @Inject(HAMMER_LOADER) private loader?: HammerLoader | null,
) {
super(doc);
}
override supports(eventName: string): boolean {
if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) {
return false;
}
if (!(window as any).Hammer && !this.loader) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
this.console.warn(
`The "${eventName}" event cannot be bound because Hammer.JS is not ` +
`loaded and no custom loader has been specified.`,
);
}
return false;
}
return true;
}
override addEventListener(element: HTMLElement, eventName: string, handler: Function): Function {
const zone = this.manager.getZone();
eventName = eventName.toLowerCase();
// If Hammer is not present but a loader is specified, we defer adding the event listener
// until Hammer is loaded.
if (!(window as any).Hammer && this.loader) {
this._loaderPromise = this._loaderPromise || zone.runOutsideAngular(() => this.loader!());
// This `addEventListener` method returns a function to remove the added listener.
// Until Hammer is loaded, the returned function needs to *cancel* the registration rather
// than remove anything.
let cancelRegistration = false;
let deregister: Function = () => {
cancelRegistration = true;
};
zone.runOutsideAngular(() =>
this._loaderPromise!.then(() => {
// If Hammer isn't actually loaded when the custom loader resolves, give up.
if (!(window as any).Hammer) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
this.console.warn(
`The custom HAMMER_LOADER completed, but Hammer.JS is not present.`,
);
}
deregister = () => {};
return;
}
if (!cancelRegistration) {
// Now that Hammer is loaded and the listener is being loaded for real,
// the deregistration function changes from canceling registration to
// removal.
deregister = this.addEventListener(element, eventName, handler);
}
}).catch(() => {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
this.console.warn(
`The "${eventName}" event cannot be bound because the custom ` +
`Hammer.JS loader failed.`,
);
}
deregister = () => {};
}),
);
// Return a function that *executes* `deregister` (and not `deregister` itself) so that we
// can change the behavior of `deregister` once the listener is added. Using a closure in
// this way allows us to avoid any additional data structures to track listener removal.
return () => {
deregister();
};
}
return zone.runOutsideAngular(() => {
// Creating the manager bind events, must be done outside of angular
const mc = this._config.buildHammer(element);
const callback = function (eventObj: HammerInput) {
zone.runGuarded(function () {
handler(eventObj);
});
};
mc.on(eventName, callback);
return () => {
mc.off(eventName, callback);
// destroy mc to prevent memory leak
if (typeof mc.destroy === 'function') {
mc.destroy();
}
};
});
}
isCustomEvent(eventName: string): boolean {
return this._config.events.indexOf(eventName) > -1;
}
}
| {
"end_byte": 8288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/platform-browser/src/dom/events/hammer_gestures.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.