_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/core/test/bundling/animations-standalone/BUILD.bazel_0_1393 | load("//tools:defaults.bzl", "app_bundle", "jasmine_node_test", "ng_module", "ts_library")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("@npm//http-server:index.bzl", "http_server")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "animations_standalone",
srcs = ["index.ts"],
deps = [
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser/animations",
],
)
app_bundle(
name = "bundle",
entry_point = ":index.ts",
deps = [
":animations_standalone",
"@npm//rxjs",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["*_spec.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/private/testing",
"@npm//@bazel/runfiles",
],
)
jasmine_node_test(
name = "test",
data = [
":bundle.debug.min.js",
":bundle.js",
":bundle.min.js",
":bundle.min.js.br",
],
deps = [":test_lib"],
)
js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.debug.min.js",
golden = ":bundle.golden_symbols.json",
)
http_server(
name = "prodserver",
data = [
"index.html",
":bundle.debug.min.js",
":bundle.min.js",
],
)
| {
"end_byte": 1393,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations-standalone/BUILD.bazel"
} |
angular/packages/core/test/bundling/animations-standalone/index.ts_0_1123 | /**
* @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 {Component, NgModule, ɵNgModuleFactory as NgModuleFactory} from '@angular/core';
import {bootstrapApplication, BrowserModule, platformBrowser} from '@angular/platform-browser';
import {BrowserAnimationsModule, provideAnimations} from '@angular/platform-browser/animations';
@Component({
selector: 'app-animations',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]),
],
standalone: true,
})
class AnimationsComponent {
exp: any = false;
}
@Component({
selector: 'app-root',
template: `
<app-animations></app-animations>
`,
standalone: true,
imports: [AnimationsComponent],
})
class RootComponent {}
(window as any).waitForApp = bootstrapApplication(RootComponent, {providers: provideAnimations()});
| {
"end_byte": 1123,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations-standalone/index.ts"
} |
angular/packages/core/test/bundling/animations/index.html_0_1220 | <!DOCTYPE html>
<html>
<head>
<title>Angular Animations Example</title>
</head>
<body>
<!-- The Angular application will be bootstrapped into this element. -->
<app-root></app-root>
<!--
Script tag which bootstraps the application. Use `?debug` in URL to select
the debug version of the script.
There are two scripts sources: `bundle.min.js` and `bundle.debug.min.js` You can
switch between which bundle the browser loads to experiment with the application.
- `bundle.min.js`: Is what the site would serve to their users. It has gone
through rollup, build-optimizer, and uglify with tree shaking.
- `bundle.debug.min.js`: Is what the developer would like to see when debugging
the application. It has also gone through full pipeline of esbuild, babel optimization,
plugins from the devkit and terser, however mangling is disabled and the minified
file is formatted using prettier (to ease debugging).
-->
<script>
document.write('<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.debug.min.js' : '/bundle.min.js') +
'"></' + 'script>');
</script>
</body>
</html> | {
"end_byte": 1220,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations/index.html"
} |
angular/packages/core/test/bundling/animations/treeshaking_spec.ts_0_1058 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import '@angular/compiler';
import {runfiles} from '@bazel/runfiles';
import * as fs from 'fs';
import * as path from 'path';
const PACKAGE = 'angular/packages/core/test/bundling/animations';
describe('treeshaking with uglify', () => {
let content: string;
// We use the debug version as otherwise symbols/identifiers would be mangled (and the test would
// always pass)
const contentPath = runfiles.resolve(path.join(PACKAGE, 'bundle.debug.min.js'));
beforeAll(() => {
content = fs.readFileSync(contentPath, {encoding: 'utf-8'});
});
it('should drop unused TypeScript helpers', () => {
expect(content).not.toContain('__asyncGenerator');
});
it('should not contain rxjs from commonjs distro', () => {
expect(content).not.toContain('commonjsGlobal');
expect(content).not.toContain('createCommonjsModule');
});
});
| {
"end_byte": 1058,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations/treeshaking_spec.ts"
} |
angular/packages/core/test/bundling/animations/BUILD.bazel_0_1404 | load("//tools:defaults.bzl", "app_bundle", "jasmine_node_test", "ng_module", "ts_library")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("@npm//http-server:index.bzl", "http_server")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "animations",
srcs = ["index.ts"],
deps = [
"//packages/animations",
"//packages/core",
"//packages/platform-browser",
"//packages/platform-browser/animations",
],
)
app_bundle(
name = "bundle",
entry_point = ":index.ts",
deps = [
":animations",
"@npm//rxjs",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["*_spec.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/private/testing",
"@npm//@bazel/runfiles",
],
)
jasmine_node_test(
name = "test",
data = [
":bundle.debug.min.js",
":bundle.js",
":bundle.min.js",
":bundle.min.js.br",
],
deps = [":test_lib"],
)
js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.debug.min.js",
golden = ":bundle.golden_symbols.json",
)
http_server(
name = "prodserver",
data = [
"index.html",
":bundle.debug.min.js",
":bundle.min.js",
],
)
| {
"end_byte": 1404,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations/BUILD.bazel"
} |
angular/packages/core/test/bundling/animations/index.ts_0_1285 | /**
* @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 {Component, NgModule, ɵNgModuleFactory as NgModuleFactory} from '@angular/core';
import {BrowserModule, platformBrowser} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@Component({
selector: 'app-animations',
template: `
<div [@myAnimation]="exp"></div>
`,
animations: [
trigger('myAnimation', [transition('* => on', [animate(1000, style({opacity: 1}))])]),
],
standalone: false,
})
class AnimationsComponent {
exp: any = false;
}
@Component({
selector: 'app-root',
template: `
<app-animations></app-animations>
`,
standalone: false,
})
class RootComponent {}
@NgModule({
declarations: [RootComponent, AnimationsComponent],
imports: [BrowserModule, BrowserAnimationsModule],
})
class AnimationsExampleModule {
ngDoBootstrap(app: any) {
app.bootstrap(RootComponent);
}
}
(window as any).waitForApp = platformBrowser().bootstrapModule(AnimationsExampleModule, {
ngZone: 'noop',
});
| {
"end_byte": 1285,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/animations/index.ts"
} |
angular/packages/core/test/bundling/router/index.html_0_1317 | <!DOCTYPE html>
<html>
<head>
<title>Angular Routing Example</title>
</head>
<body>
<!-- The Angular application will be bootstrapped into this element. -->
<app-root></app-root>
<script src="/angular/packages/zone.js/bundles/zone.umd.js"></script>
<!--
Script tag which bootstraps the application. Use `?debug` in URL to select
the debug version of the script.
There are two scripts sources: `bundle.min.js` and `bundle.debug.min.js` You can
switch between which bundle the browser loads to experiment with the application.
- `bundle.min.js`: Is what the site would serve to their users. It has gone
through rollup, build-optimizer, and uglify with tree shaking.
- `bundle.debug.min.js`: Is what the developer would like to see when debugging
the application. It has also gone through full pipeline of esbuild, babel optimization,
plugins from the devkit and terser, however mangling is disabled and the minified
file is formatted using prettier (to ease debugging).
-->
<script>
document.write(
'<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.debug.min.js' : '/bundle.min.js') +
'"></' +
'script>'
);
</script>
</body>
</html>
| {
"end_byte": 1317,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/router/index.html"
} |
angular/packages/core/test/bundling/router/treeshaking_spec.ts_0_1054 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import '@angular/compiler';
import {runfiles} from '@bazel/runfiles';
import * as fs from 'fs';
import * as path from 'path';
const PACKAGE = 'angular/packages/core/test/bundling/router';
describe('treeshaking with uglify', () => {
let content: string;
// We use the debug version as otherwise symbols/identifiers would be mangled (and the test would
// always pass)
const contentPath = runfiles.resolve(path.join(PACKAGE, 'bundle.debug.min.js'));
beforeAll(() => {
content = fs.readFileSync(contentPath, {encoding: 'utf-8'});
});
it('should drop unused TypeScript helpers', () => {
expect(content).not.toContain('__asyncGenerator');
});
it('should not contain rxjs from commonjs distro', () => {
expect(content).not.toContain('commonjsGlobal');
expect(content).not.toContain('createCommonjsModule');
});
});
| {
"end_byte": 1054,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/router/treeshaking_spec.ts"
} |
angular/packages/core/test/bundling/router/BUILD.bazel_0_1472 | load("//tools:defaults.bzl", "app_bundle", "http_server", "jasmine_node_test", "ng_module", "ts_library")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "router",
srcs = [
"index.ts",
],
deps = [
"//packages/core",
"//packages/platform-browser",
"//packages/router",
],
)
app_bundle(
name = "bundle",
entry_point = ":index.ts",
deps = [
":router",
"//packages/core",
"//packages/platform-browser",
"//packages/router",
"@npm//rxjs",
],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["*_spec.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/core",
"//packages/core/testing",
"//packages/private/testing",
"@npm//@bazel/runfiles",
],
)
jasmine_node_test(
name = "test",
data = [
":bundle",
":bundle.debug.min.js",
":bundle.js",
":bundle.min.js",
],
deps = [":test_lib"],
)
js_expected_symbol_test(
name = "symbol_test",
src = ":bundle.debug.min.js",
golden = ":bundle.golden_symbols.json",
)
http_server(
name = "server",
srcs = [
"index.html",
],
deps = [
":bundle.debug.min.js",
":bundle.min.js",
"//packages/zone.js/bundles:zone.umd.js",
],
)
| {
"end_byte": 1472,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/router/BUILD.bazel"
} |
angular/packages/core/test/bundling/router/index.ts_0_1867 | /**
* @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 {APP_BASE_HREF} from '@angular/common';
import {Component, OnInit} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';
import {
ActivatedRoute,
provideRouter,
Router,
RouterLink,
RouterLinkActive,
RouterOutlet,
Routes,
} from '@angular/router';
@Component({
selector: 'app-list',
template: `
<ul>
<li><a routerLink="/item/1" routerLinkActive="active">List Item 1</a></li>
<li><a routerLink="/item/2" routerLinkActive="active">List Item 2</a></li>
<li><a routerLink="/item/3" routerLinkActive="active">List Item 3</a></li>
</ul>
`,
standalone: true,
imports: [RouterLink, RouterLinkActive],
})
class ListComponent {}
@Component({
selector: 'app-item',
template: `
Item {{id}}
<p><button (click)="viewList()">Back to List</button></p>`,
standalone: true,
})
class ItemComponent implements OnInit {
id = -1;
constructor(
private activatedRoute: ActivatedRoute,
private router: Router,
) {}
ngOnInit() {
this.activatedRoute.paramMap.subscribe((paramsMap) => {
this.id = +paramsMap.get('id')!;
});
}
viewList() {
this.router.navigate(['/list']);
}
}
@Component({
selector: 'app-root',
template: `<router-outlet></router-outlet>`,
standalone: true,
imports: [RouterOutlet],
})
class RootComponent {}
const ROUTES: Routes = [
{path: '', redirectTo: '/list', pathMatch: 'full'},
{path: 'list', component: ListComponent},
{path: 'item/:id', component: ItemComponent},
];
(window as any).waitForApp = bootstrapApplication(RootComponent, {
providers: [provideRouter(ROUTES), {provide: APP_BASE_HREF, useValue: ''}],
});
| {
"end_byte": 1867,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/bundling/router/index.ts"
} |
angular/packages/core/test/resource/resource_spec.ts_0_1666 | /**
* @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 {
createEnvironmentInjector,
EnvironmentInjector,
Injector,
resource,
ResourceStatus,
signal,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
abstract class MockBackend<T, R> {
protected pending = new Map<
T,
{resolve: (r: R) => void; reject: (reason: any) => void; promise: Promise<R>}
>();
fetch(request: T): Promise<R> {
const p = new Promise<R>((resolve, reject) => {
this.pending.set(request, {resolve, reject, promise: undefined!});
});
this.pending.get(request)!.promise = p;
return p;
}
abort(req: T) {
this.reject(req, 'aborted');
}
reject(req: T, reason: any) {
const entry = this.pending.get(req);
if (entry) {
this.pending.delete(req);
entry.reject(reason);
}
return Promise.resolve();
}
async flush() {
const allPending = Array.from(this.pending.values()).map((pending) => pending.promise);
for (const [req, {resolve}] of this.pending) {
resolve(this.prepareResponse(req));
}
this.pending.clear();
return Promise.all(allPending);
}
protected abstract prepareResponse(request: T): R;
}
class MockEchoBackend<T> extends MockBackend<T, T> {
override prepareResponse(request: T) {
return request;
}
}
class MockResponseCountingBackend extends MockBackend<number, string> {
counter = 0;
override prepareResponse(request: number) {
return request + ':' + this.counter++;
}
} | {
"end_byte": 1666,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/resource/resource_spec.ts"
} |
angular/packages/core/test/resource/resource_spec.ts_1668_10415 | describe('resource', () => {
it('should expose data and status based on reactive request', async () => {
const counter = signal(0);
const backend = new MockEchoBackend();
const echoResource = resource({
request: () => ({counter: counter()}),
loader: (params) => backend.fetch(params.request),
injector: TestBed.inject(Injector),
});
// a freshly created resource is in the idle state
expect(echoResource.status()).toBe(ResourceStatus.Idle);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.hasValue()).toBeFalse();
expect(echoResource.value()).toBeUndefined();
expect(echoResource.error()).toBe(undefined);
// flush effect to kick off a request
// THINK: testing patterns around a resource?
TestBed.flushEffects();
expect(echoResource.status()).toBe(ResourceStatus.Loading);
expect(echoResource.isLoading()).toBeTrue();
expect(echoResource.hasValue()).toBeFalse();
expect(echoResource.value()).toBeUndefined();
expect(echoResource.error()).toBe(undefined);
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.hasValue()).toBeTrue();
expect(echoResource.value()).toEqual({counter: 0});
expect(echoResource.error()).toBe(undefined);
counter.update((c) => c + 1);
TestBed.flushEffects();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.hasValue()).toBeTrue();
expect(echoResource.value()).toEqual({counter: 1});
expect(echoResource.error()).toBe(undefined);
});
it('should expose errors thrown during resource loading', async () => {
const backend = new MockEchoBackend();
const requestParam = {};
const echoResource = resource({
request: () => requestParam,
loader: (params) => backend.fetch(params.request),
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
await backend.reject(requestParam, 'Something went wrong....');
expect(echoResource.status()).toBe(ResourceStatus.Error);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.value()).toEqual(undefined);
expect(echoResource.error()).toBe('Something went wrong....');
});
it('should _not_ load if the request resolves to undefined', () => {
const counter = signal(0);
const backend = new MockEchoBackend();
const echoResource = resource({
request: () => (counter() > 5 ? {counter: counter()} : undefined),
loader: (params) => backend.fetch(params.request),
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
expect(echoResource.status()).toBe(ResourceStatus.Idle);
expect(echoResource.isLoading()).toBeFalse();
counter.set(10);
TestBed.flushEffects();
expect(echoResource.isLoading()).toBeTrue();
});
it('should cancel pending requests before starting a new one', async () => {
const counter = signal(0);
const backend = new MockEchoBackend<{counter: number}>();
const aborted: {counter: number}[] = [];
const echoResource = resource<{counter: number}, {counter: number}>({
request: () => ({counter: counter()}),
loader: ({request, abortSignal}) => {
abortSignal.addEventListener('abort', () => backend.abort(request));
return backend.fetch(request).catch((reason) => {
if (reason === 'aborted') {
aborted.push(request);
}
throw new Error(reason);
});
},
injector: TestBed.inject(Injector),
});
// start a request without resolving the previous one
TestBed.flushEffects();
await Promise.resolve();
// start a new request and resolve all
counter.update((c) => c + 1);
TestBed.flushEffects();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
expect(echoResource.value()).toEqual({counter: 1});
expect(echoResource.error()).toBe(undefined);
expect(aborted).toEqual([{counter: 0}]);
});
it('should cancel pending requests when the resource is destroyed via injector', async () => {
const counter = signal(0);
const backend = new MockEchoBackend<{counter: number}>();
const aborted: {counter: number}[] = [];
const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector));
const echoResource = resource<{counter: number}, {counter: number}>({
request: () => ({counter: counter()}),
loader: ({request, abortSignal}) => {
abortSignal.addEventListener('abort', () => backend.abort(request));
return backend.fetch(request).catch((reason) => {
if (reason === 'aborted') {
aborted.push(request);
}
throw new Error(reason);
});
},
injector,
});
// start a request without resolving the previous one
TestBed.flushEffects();
await Promise.resolve();
injector.destroy();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Idle);
expect(echoResource.value()).toBe(undefined);
expect(echoResource.error()).toBe(undefined);
expect(aborted).toEqual([{counter: 0}]);
});
it('should cancel pending requests when the resource is manually destroyed', async () => {
const counter = signal(0);
const backend = new MockEchoBackend<{counter: number}>();
const aborted: {counter: number}[] = [];
const injector = createEnvironmentInjector([], TestBed.inject(EnvironmentInjector));
const echoResource = resource<{counter: number}, {counter: number}>({
request: () => ({counter: counter()}),
loader: ({request, abortSignal}) => {
abortSignal.addEventListener('abort', () => backend.abort(request));
return backend.fetch(request).catch((reason) => {
if (reason === 'aborted') {
aborted.push(request);
}
throw new Error(reason);
});
},
injector,
});
// start a request without resolving the previous one
TestBed.flushEffects();
await Promise.resolve();
echoResource.destroy();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Idle);
expect(echoResource.value()).toBe(undefined);
expect(echoResource.error()).toBe(undefined);
expect(aborted).toEqual([{counter: 0}]);
});
it('should not respond to reactive state changes in a loader', async () => {
const unrelated = signal('a');
const backend = new MockResponseCountingBackend();
const res = resource<string, number>({
request: () => 0,
loader: (params) => {
// read reactive state and assure it is _not_ tracked
unrelated();
return backend.fetch(params.request);
},
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
await backend.flush();
expect(res.value()).toBe('0:0');
unrelated.set('b');
TestBed.flushEffects();
// there is no chang in the status
expect(res.status()).toBe(ResourceStatus.Resolved);
await backend.flush();
// there is no chang in the value
expect(res.value()).toBe('0:0');
});
it('should allow setting local state', async () => {
const counter = signal(0);
const backend = new MockEchoBackend();
const echoResource = resource({
request: () => ({counter: counter()}),
loader: (params) => backend.fetch(params.request),
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.value()).toEqual({counter: 0});
expect(echoResource.error()).toBe(undefined);
echoResource.value.set({counter: 100});
expect(echoResource.status()).toBe(ResourceStatus.Local);
expect(echoResource.isLoading()).toBeFalse();
expect(echoResource.hasValue()).toBeTrue();
expect(echoResource.value()).toEqual({counter: 100});
expect(echoResource.error()).toBe(undefined);
counter.set(1);
TestBed.flushEffects();
await backend.flush();
expect(echoResource.status()).toBe(ResourceStatus.Resolved);
expect(echoResource.value()).toEqual({counter: 1});
expect(echoResource.error()).toBe(undefined);
// state setter is also exposed on the resource directly
echoResource.set({counter: 200});
expect(echoResource.status()).toBe(ResourceStatus.Local);
expect(echoResource.hasValue()).toBeTrue();
expect(echoResource.value()).toEqual({counter: 200});
}); | {
"end_byte": 10415,
"start_byte": 1668,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/resource/resource_spec.ts"
} |
angular/packages/core/test/resource/resource_spec.ts_10419_12303 | it('should allow re-fetching data', async () => {
const backend = new MockResponseCountingBackend();
const res = resource<string, number>({
request: () => 0,
loader: (params) => backend.fetch(params.request),
injector: TestBed.inject(Injector),
});
TestBed.flushEffects();
await backend.flush();
expect(res.status()).toBe(ResourceStatus.Resolved);
expect(res.value()).toBe('0:0');
expect(res.error()).toBe(undefined);
res.reload();
TestBed.flushEffects();
await backend.flush();
expect(res.status()).toBe(ResourceStatus.Resolved);
expect(res.isLoading()).toBeFalse();
expect(res.value()).toBe('0:1');
expect(res.error()).toBe(undefined);
// calling refresh multiple times should _not_ result in multiple requests
res.reload();
TestBed.flushEffects();
res.reload();
TestBed.flushEffects();
await backend.flush();
expect(res.value()).toBe('0:2');
});
it('should respect provided equality function for the results signal', async () => {
const res = resource({
loader: async () => 0,
equal: (a, b) => true,
injector: TestBed.inject(Injector),
});
res.value.set(5);
expect(res.status()).toBe(ResourceStatus.Local);
expect(res.value()).toBe(5);
expect(res.error()).toBe(undefined);
res.value.set(10);
expect(res.status()).toBe(ResourceStatus.Local);
expect(res.value()).toBe(5); // equality blocked writes
expect(res.error()).toBe(undefined);
});
it('should convert writable resource to its read-only version', () => {
const res = resource({
loader: async () => 0,
equal: (a, b) => true,
injector: TestBed.inject(Injector),
});
const readonlyRes = res.asReadonly();
// @ts-expect-error
readonlyRes.asReadonly;
// @ts-expect-error
readonlyRes.value.set;
});
}); | {
"end_byte": 12303,
"start_byte": 10419,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/resource/resource_spec.ts"
} |
angular/packages/core/test/resource/BUILD.bazel_0_561 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ng_module")
package(default_visibility = ["//visibility:private"])
ng_module(
name = "resource_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/core",
"//packages/core/testing",
],
)
jasmine_node_test(
name = "resource",
bootstrap = ["//tools/testing:node"],
deps = [
":resource_lib",
],
)
karma_web_test_suite(
name = "resource_web",
deps = [
":resource_lib",
],
)
| {
"end_byte": 561,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/resource/BUILD.bazel"
} |
angular/packages/core/test/i18n/locale_data_api_spec.ts_0_3862 | /**
* @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 {
findLocaleData,
getLocaleCurrencyCode,
LocaleDataIndex,
registerLocaleData,
unregisterAllLocaleData,
} from '../../src/i18n/locale_data_api';
import {global} from '../../src/util/global';
describe('locale data api', () => {
const localeCaESVALENCIA: any[] = ['ca-ES-VALENCIA'];
const localeDe: any[] = ['de'];
const localeDeCH: any[] = ['de-CH'];
const localeEn: any[] = ['en'];
const localeFr: any[] = ['fr'];
localeFr[LocaleDataIndex.CurrencyCode] = 'EUR';
const localeFrCA: any[] = ['fr-CA'];
const localeZh: any[] = ['zh'];
const localeEnAU: any[] = ['en-AU'];
const fakeGlobalFr: any[] = ['fr'];
beforeAll(() => {
// Sumulate manually registering some locale data
registerLocaleData(localeCaESVALENCIA);
registerLocaleData(localeEn);
registerLocaleData(localeFr);
registerLocaleData(localeFrCA);
registerLocaleData(localeFr, 'fake-id');
registerLocaleData(localeFrCA, 'fake_Id2');
registerLocaleData(localeZh);
registerLocaleData(localeEnAU);
// Simulate some locale data existing on the global already
global.ng = global.ng || {};
global.ng.common = global.ng.common || {locales: {}};
global.ng.common.locales = global.ng.common.locales || {};
global.ng.common.locales['fr'] = fakeGlobalFr;
global.ng.common.locales['de'] = localeDe;
global.ng.common.locales['de-ch'] = localeDeCH;
});
afterAll(() => {
unregisterAllLocaleData();
global.ng.common.locales = undefined;
});
describe('findLocaleData', () => {
it('should throw if the LOCALE_DATA for the chosen locale or its parent locale is not available', () => {
expect(() => findLocaleData('pt-AO')).toThrowError(
/Missing locale data for the locale "pt-AO"/,
);
});
it('should return english data if the locale is en-US', () => {
expect(findLocaleData('en-US')).toEqual(localeEn);
});
it('should return the exact LOCALE_DATA if it is available', () => {
expect(findLocaleData('fr-CA')).toEqual(localeFrCA);
});
it('should return the parent LOCALE_DATA if it exists and exact locale is not available', () => {
expect(findLocaleData('fr-BE')).toEqual(localeFr);
});
it(`should find the LOCALE_DATA even if the locale id is badly formatted`, () => {
expect(findLocaleData('ca-ES-VALENCIA')).toEqual(localeCaESVALENCIA);
expect(findLocaleData('CA_es_Valencia')).toEqual(localeCaESVALENCIA);
});
it(`should find the LOCALE_DATA if the locale id was registered`, () => {
expect(findLocaleData('fake-id')).toEqual(localeFr);
expect(findLocaleData('fake_iD')).toEqual(localeFr);
expect(findLocaleData('fake-id2')).toEqual(localeFrCA);
});
it('should find the exact LOCALE_DATA if the locale is on the global object', () => {
expect(findLocaleData('de-CH')).toEqual(localeDeCH);
});
it('should find the parent LOCALE_DATA if the exact locale is not available and the parent locale is on the global object', () => {
expect(findLocaleData('de-BE')).toEqual(localeDe);
});
it('should find the registered LOCALE_DATA even if the same locale is on the global object', () => {
expect(findLocaleData('fr')).not.toBe(fakeGlobalFr);
});
});
describe('getLocaleCurrencyCode()', () => {
it('should return `null` if the given locale does not provide a currency code', () => {
expect(getLocaleCurrencyCode('de')).toBe(null);
});
it('should return the code at the `LocaleDataIndex.CurrencyCode` of the given locale`s data', () => {
expect(getLocaleCurrencyCode('fr')).toEqual('EUR');
});
});
});
| {
"end_byte": 3862,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/i18n/locale_data_api_spec.ts"
} |
angular/packages/core/test/sanitization/html_sanitizer_spec.ts_0_485 | /**
* @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 {_sanitizeHtml} from '../../src/sanitization/html_sanitizer';
import {isDOMParserAvailable} from '../../src/sanitization/inert_body';
function sanitizeHtml(defaultDoc: any, unsafeHtmlInput: string): string {
return _sanitizeHtml(defaultDoc, unsafeHtmlInput).toString();
} | {
"end_byte": 485,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/sanitization/html_sanitizer_spec.ts"
} |
angular/packages/core/test/sanitization/html_sanitizer_spec.ts_487_7606 | describe('HTML sanitizer', () => {
let defaultDoc: any;
let originalLog: (msg: any) => any = null!;
let logMsgs: string[];
beforeEach(() => {
defaultDoc = document;
logMsgs = [];
originalLog = console.warn; // Monkey patch DOM.log.
console.warn = (msg: any) => logMsgs.push(msg);
});
afterEach(() => {
console.warn = originalLog;
});
it('serializes nested structures', () => {
expect(
sanitizeHtml(defaultDoc, '<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'),
).toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>');
expect(logMsgs).toEqual([]);
});
it('serializes self closing elements', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hello <br> World</p>')).toEqual('<p>Hello <br> World</p>');
});
it('supports namespaced elements', () => {
expect(sanitizeHtml(defaultDoc, 'a<my:hr/><my:div>b</my:div>c')).toEqual('abc');
});
it('supports namespaced attributes', () => {
expect(sanitizeHtml(defaultDoc, '<a xlink:href="something">t</a>')).toEqual(
'<a xlink:href="something">t</a>',
);
expect(sanitizeHtml(defaultDoc, '<a xlink:evil="something">t</a>')).toEqual('<a>t</a>');
expect(sanitizeHtml(defaultDoc, '<a xlink:href="javascript:foo()">t</a>')).toEqual(
'<a xlink:href="unsafe:javascript:foo()">t</a>',
);
});
it('supports HTML5 elements', () => {
expect(sanitizeHtml(defaultDoc, '<main><summary>Works</summary></main>')).toEqual(
'<main><summary>Works</summary></main>',
);
});
it('supports ARIA attributes', () => {
expect(
sanitizeHtml(defaultDoc, '<h1 role="presentation" aria-haspopup="true">Test</h1>'),
).toEqual('<h1 role="presentation" aria-haspopup="true">Test</h1>');
expect(sanitizeHtml(defaultDoc, '<i aria-label="Info">Info</i>')).toEqual(
'<i aria-label="Info">Info</i>',
);
expect(sanitizeHtml(defaultDoc, '<img src="pteranodon.jpg" aria-details="details">')).toEqual(
'<img src="pteranodon.jpg" aria-details="details">',
);
});
it('ignores srcset attributes', () => {
// Modern browsers can handle `srcset` safely without any additional sanitization.
expect(
sanitizeHtml(defaultDoc, '<img srcset="/foo.png 400px, javascript:evil() 23px">'),
).toEqual('<img srcset="/foo.png 400px, javascript:evil() 23px">');
// Verify that complex `srcset` with URLs that contain commas are retained as is.
const content =
'<img src="https://localhost/h_450,w_450/logo.jpg" ' +
'srcset="https://localhost/h_450,w_450/logo.jpg 450w, https://localhost/h_300,w_300/logo.jpg 300w">';
expect(sanitizeHtml(defaultDoc, content)).toEqual(content);
});
it('supports sanitizing plain text', () => {
expect(sanitizeHtml(defaultDoc, 'Hello, World')).toEqual('Hello, World');
});
it('ignores non-element, non-attribute nodes', () => {
expect(sanitizeHtml(defaultDoc, '<!-- comments? -->no.')).toEqual('no.');
expect(sanitizeHtml(defaultDoc, '<?pi nodes?>no.')).toEqual('no.');
expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/);
});
it('supports sanitizing escaped entities', () => {
expect(sanitizeHtml(defaultDoc, '🚀')).toEqual('🚀');
expect(logMsgs).toEqual([]);
});
it('does not warn when just re-encoding text', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hellö Wörld</p>')).toEqual('<p>Hellö Wörld</p>');
expect(logMsgs).toEqual([]);
});
it('escapes entities', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hello < World</p>')).toEqual('<p>Hello < World</p>');
expect(sanitizeHtml(defaultDoc, '<p>Hello < World</p>')).toEqual('<p>Hello < World</p>');
expect(sanitizeHtml(defaultDoc, '<p alt="% & " !">Hello</p>')).toEqual(
'<p alt="% & " !">Hello</p>',
); // NB: quote encoded as ASCII ".
});
describe('should strip dangerous elements (but potentially traverse their content)', () => {
const dangerousTags = ['form', 'object', 'textarea', 'button', 'option', 'select'];
for (const tag of dangerousTags) {
it(tag, () => {
expect(sanitizeHtml(defaultDoc, `<${tag}>evil!</${tag}>`)).toEqual('evil!');
});
}
const dangerousSelfClosingTags = [
'base',
'basefont',
'embed',
'frameset',
'input',
'link',
'param',
];
for (const tag of dangerousSelfClosingTags) {
it(tag, () => {
expect(sanitizeHtml(defaultDoc, `before<${tag}>After`)).toEqual('beforeAfter');
});
}
const dangerousSkipContentTags = ['script', 'style', 'template'];
for (const tag of dangerousSkipContentTags) {
it(tag, () => {
expect(sanitizeHtml(defaultDoc, `<${tag}>evil!</${tag}>`)).toEqual('');
});
}
it(`frame`, () => {
// `<frame>` is special, because different browsers treat it differently (e.g. remove it
// altogether). // We just verify that (one way or another), there is no `<frame>` element
// after sanitization.
expect(sanitizeHtml(defaultDoc, `<frame>evil!</frame>`)).not.toContain('<frame>');
});
});
describe('should strip dangerous attributes', () => {
const dangerousAttrs = ['id', 'name', 'style'];
for (const attr of dangerousAttrs) {
it(`${attr}`, () => {
expect(sanitizeHtml(defaultDoc, `<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>');
});
}
});
it('ignores content of script elements', () => {
expect(sanitizeHtml(defaultDoc, '<script>var foo="<p>bar</p>"</script>')).toEqual('');
expect(sanitizeHtml(defaultDoc, '<script>var foo="<p>bar</p>"</script><div>hi</div>')).toEqual(
'<div>hi</div>',
);
expect(sanitizeHtml(defaultDoc, '<style><!-- something-->hi</style>')).toEqual('');
});
it('ignores content of style elements', () => {
expect(sanitizeHtml(defaultDoc, '<style><!-- foobar --></style><div>hi</div>')).toEqual(
'<div>hi</div>',
);
expect(sanitizeHtml(defaultDoc, '<style><!-- foobar --></style>')).toEqual('');
expect(sanitizeHtml(defaultDoc, '<style><!-- something-->hi</style>')).toEqual('');
expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/);
});
it('should strip unclosed iframe tag', () => {
expect(sanitizeHtml(defaultDoc, '<iframe>')).toEqual('');
expect([
'<iframe>',
// Double-escaped on IE
'&lt;iframe&gt;',
]).toContain(sanitizeHtml(defaultDoc, '<iframe><iframe>'));
expect([
'<script>evil();</script>',
// Double-escaped on IE
'&lt;script&gt;evil();&lt;/script&gt;',
]).toContain(sanitizeHtml(defaultDoc, '<iframe><script>evil();</script>'));
});
it('should ignore extraneous body tags', () => {
expect(sanitizeHtml(defaultDoc, '</body>')).toEqual('');
expect(sanitizeHtml(defaultDoc, 'foo</body>bar')).toEqual('foobar');
expect(sanitizeHtml(defaultDoc, 'foo<body>bar')).toEqual('foobar');
expect(sanitizeHtml(defaultDoc, 'fo<body>ob</body>ar')).toEqual('foobar');
});
| {
"end_byte": 7606,
"start_byte": 487,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/sanitization/html_sanitizer_spec.ts"
} |
angular/packages/core/test/sanitization/html_sanitizer_spec.ts_7610_12328 | ('should not enter an infinite loop on clobbered elements', () => {
// Some browsers are vulnerable to clobbered elements and will throw an expected exception
// IE and EDGE does not seems to be affected by those cases
// Anyway what we want to test is that browsers do not enter an infinite loop which would
// result in a timeout error for the test.
try {
sanitizeHtml(defaultDoc, '<form><input name="parentNode" /></form>');
} catch (e) {
// depending on the browser, we might get an exception
}
try {
sanitizeHtml(defaultDoc, '<form><input name="nextSibling" /></form>');
} catch (e) {
// depending on the browser, we might get an exception
}
try {
sanitizeHtml(defaultDoc, '<form><div><div><input name="nextSibling" /></div></div></form>');
} catch (e) {
// depending on the browser, we might get an exception
}
try {
sanitizeHtml(defaultDoc, '<input name="nextSibling" form="a"><form id="a"></form>');
} catch (e) {
// depending on the browser, we might get an exception
}
});
it('should properly sanitize the content when `nodeName` is clobbered', () => {
const output = sanitizeHtml(defaultDoc, '<form><input name=nodeName></form>text');
expect(output).toBe('text');
});
it('should sanitize the content when `nextSibling` or `firstChild` were clobbered', () => {
const nextSibling = () =>
sanitizeHtml(defaultDoc, '<input name="nextSibling" form="a">A<form id="a"></form>');
const firstChild = () =>
sanitizeHtml(defaultDoc, '<object form="a" id="firstChild"></object>B<form id="a"></form>');
// Note: we have a different behavior here in a real browser and when running in Node,
// when Domino is used to emulate DOM:
//
// * In Node, Domino doesn't match browser behavior exactly, thus it's not susceptible to
// element clobbering. Both `.nextSibling` and `.firstChild` (that we use to traverse
// the DOM during sanitization) point to correct elements, as if no clobbering happens.
// In this case, we just sanitize the content (the content becomes safe).
//
// * In a real browser, sanitization code triggers a code path that recognizes that
// clobbering happened and throws an error.
//
// So in both cases we achieve the result of preventing potentially dangerous content from
// being included into an application, but there is a difference in observable behavior
// depending on a platform.
if (isBrowser) {
// Running in a real browser
const errorMsg = 'Failed to sanitize html because the element is clobbered: ';
expect(nextSibling).toThrowError(`${errorMsg}<input name="nextSibling" form="a">`);
expect(firstChild).toThrowError(`${errorMsg}<object form="a" id="firstChild"></object>`);
} else {
// Running in Node, using Domino DOM emulation
expect(nextSibling()).toBe('A');
expect(firstChild()).toBe('B');
}
});
// See
// https://github.com/cure53/DOMPurify/blob/a992d3a75031cb8bb032e5ea8399ba972bdf9a65/src/purify.js#L439-L449
it('should not allow JavaScript execution when creating inert document', () => {
const output = sanitizeHtml(defaultDoc, '<svg><g onload="window.xxx = 100"></g></svg>');
const window = defaultDoc.defaultView;
if (window) {
expect(window.xxx).toBe(undefined);
window.xxx = undefined;
}
expect(output).toEqual('');
});
// See https://github.com/cure53/DOMPurify/releases/tag/0.6.7
it('should not allow JavaScript hidden in badly formed HTML to get through sanitization (Firefox bug)', () => {
expect(
sanitizeHtml(defaultDoc, '<svg><p><style><img src="</style><img src=x onerror=alert(1)//">'),
).toEqual(
isDOMParserAvailable()
? // PlatformBrowser output
'<p><img src="x"></p>'
: // PlatformServer output
'<p></p>',
);
});
it('should prevent mXSS attacks', function () {
// In Chrome Canary 62, the ideographic space character is kept as a stringified HTML entity
expect(sanitizeHtml(defaultDoc, '<a href=" javascript:alert(1)">CLICKME</a>')).toMatch(
/<a href="unsafe:( )?javascript:alert\(1\)">CLICKME<\/a>/,
);
});
if (isDOMParserAvailable()) {
it('should work even if DOMParser returns a null body', () => {
// Simulate `DOMParser.parseFromString()` returning a null body.
// See https://github.com/angular/angular/issues/39834
spyOn(window.DOMParser.prototype, 'parseFromString').and.returnValue({body: null} as any);
expect(sanitizeHtml(defaultDoc, 'Hello, World')).toEqual('Hello, World');
});
}
});
| {
"end_byte": 12328,
"start_byte": 7610,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/sanitization/html_sanitizer_spec.ts"
} |
angular/packages/core/test/sanitization/sanitization_spec.ts_0_7674 | /**
* @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 {SECURITY_SCHEMA} from '@angular/compiler/src/schema/dom_security_schema';
import {ENVIRONMENT, LView} from '@angular/core/src/render3/interfaces/view';
import {enterView, leaveView} from '@angular/core/src/render3/state';
import {
bypassSanitizationTrustHtml,
bypassSanitizationTrustResourceUrl,
bypassSanitizationTrustScript,
bypassSanitizationTrustStyle,
bypassSanitizationTrustUrl,
} from '../../src/sanitization/bypass';
import {
getUrlSanitizer,
ɵɵsanitizeHtml,
ɵɵsanitizeResourceUrl,
ɵɵsanitizeScript,
ɵɵsanitizeStyle,
ɵɵsanitizeUrl,
ɵɵsanitizeUrlOrResourceUrl,
ɵɵtrustConstantHtml,
ɵɵtrustConstantResourceUrl,
} from '../../src/sanitization/sanitization';
import {SecurityContext} from '../../src/sanitization/security';
function fakeLView(): LView {
const fake = [null, {}] as LView;
fake[ENVIRONMENT] = {} as any;
return fake;
}
describe('sanitization', () => {
beforeEach(() => enterView(fakeLView()));
afterEach(() => leaveView());
class Wrap {
constructor(private value: string) {}
toString() {
return this.value;
}
}
it('should sanitize html', () => {
expect(ɵɵsanitizeHtml('<div></div>').toString()).toEqual('<div></div>');
expect(ɵɵsanitizeHtml(new Wrap('<div></div>')).toString()).toEqual('<div></div>');
expect(ɵɵsanitizeHtml('<img src="javascript:true">').toString()).toEqual(
'<img src="unsafe:javascript:true">',
);
expect(ɵɵsanitizeHtml(new Wrap('<img src="javascript:true">')).toString()).toEqual(
'<img src="unsafe:javascript:true">',
);
expect(() =>
ɵɵsanitizeHtml(bypassSanitizationTrustUrl('<img src="javascript:true">')),
).toThrowError(/Required a safe HTML, got a URL/);
expect(
ɵɵsanitizeHtml(bypassSanitizationTrustHtml('<img src="javascript:true">')).toString(),
).toEqual('<img src="javascript:true">');
});
it('should sanitize url', () => {
expect(ɵɵsanitizeUrl('http://server')).toEqual('http://server');
expect(ɵɵsanitizeUrl(new Wrap('http://server'))).toEqual('http://server');
expect(ɵɵsanitizeUrl('javascript:true')).toEqual('unsafe:javascript:true');
expect(ɵɵsanitizeUrl(new Wrap('javascript:true'))).toEqual('unsafe:javascript:true');
expect(() => ɵɵsanitizeUrl(bypassSanitizationTrustHtml('javascript:true'))).toThrowError(
/Required a safe URL, got a HTML/,
);
expect(ɵɵsanitizeUrl(bypassSanitizationTrustUrl('javascript:true'))).toEqual('javascript:true');
});
it('should sanitize resourceUrl', () => {
const ERROR = /NG0904: unsafe value used in a resource URL context.*/;
expect(() => ɵɵsanitizeResourceUrl('http://server')).toThrowError(ERROR);
expect(() => ɵɵsanitizeResourceUrl('javascript:true')).toThrowError(ERROR);
expect(() =>
ɵɵsanitizeResourceUrl(bypassSanitizationTrustHtml('javascript:true')),
).toThrowError(/Required a safe ResourceURL, got a HTML/);
expect(
ɵɵsanitizeResourceUrl(bypassSanitizationTrustResourceUrl('javascript:true')).toString(),
).toEqual('javascript:true');
});
it('should sanitize style', () => {
expect(ɵɵsanitizeStyle('red')).toEqual('red');
expect(ɵɵsanitizeStyle(new Wrap('red'))).toEqual('red');
expect(ɵɵsanitizeStyle('url("http://server")')).toEqual('url("http://server")');
expect(ɵɵsanitizeStyle(new Wrap('url("http://server")'))).toEqual('url("http://server")');
expect(() => ɵɵsanitizeStyle(bypassSanitizationTrustHtml('url("http://server")'))).toThrowError(
/Required a safe Style, got a HTML/,
);
expect(ɵɵsanitizeStyle(bypassSanitizationTrustStyle('url("http://server")'))).toEqual(
'url("http://server")',
);
});
it('should sanitize script', () => {
const ERROR = 'NG0905: unsafe value used in a script context';
expect(() => ɵɵsanitizeScript('true')).toThrowError(ERROR);
expect(() => ɵɵsanitizeScript('true')).toThrowError(ERROR);
expect(() => ɵɵsanitizeScript(bypassSanitizationTrustHtml('true'))).toThrowError(
/Required a safe Script, got a HTML/,
);
expect(ɵɵsanitizeScript(bypassSanitizationTrustScript('true')).toString()).toEqual('true');
});
it('should select correct sanitizer for URL props', () => {
// making sure security schema we have on compiler side is in sync with the `getUrlSanitizer`
// runtime function definition
const schema = SECURITY_SCHEMA();
const contextsByProp: Map<string, Set<number>> = new Map();
const sanitizerNameByContext: Map<number, Function> = new Map([
[SecurityContext.URL, ɵɵsanitizeUrl],
[SecurityContext.RESOURCE_URL, ɵɵsanitizeResourceUrl],
]);
Object.entries(schema).forEach(([key, context]) => {
if (context === SecurityContext.URL || SecurityContext.RESOURCE_URL) {
const [tag, prop] = key.split('|');
const contexts = contextsByProp.get(prop) || new Set<number>();
contexts.add(context);
contextsByProp.set(prop, contexts);
// check only in case a prop can be a part of both URL contexts
if (contexts.size === 2) {
expect(getUrlSanitizer(tag, prop)).toEqual(sanitizerNameByContext.get(context)!);
}
}
});
});
it('should sanitize resourceUrls via sanitizeUrlOrResourceUrl', () => {
const ERROR = /NG0904: unsafe value used in a resource URL context.*/;
expect(() => ɵɵsanitizeUrlOrResourceUrl('http://server', 'iframe', 'src')).toThrowError(ERROR);
expect(() => ɵɵsanitizeUrlOrResourceUrl('javascript:true', 'iframe', 'src')).toThrowError(
ERROR,
);
expect(() =>
ɵɵsanitizeUrlOrResourceUrl(bypassSanitizationTrustHtml('javascript:true'), 'iframe', 'src'),
).toThrowError(/Required a safe ResourceURL, got a HTML/);
expect(
ɵɵsanitizeUrlOrResourceUrl(
bypassSanitizationTrustResourceUrl('javascript:true'),
'iframe',
'src',
).toString(),
).toEqual('javascript:true');
});
it('should sanitize urls via sanitizeUrlOrResourceUrl', () => {
expect(ɵɵsanitizeUrlOrResourceUrl('http://server', 'a', 'href')).toEqual('http://server');
expect(ɵɵsanitizeUrlOrResourceUrl(new Wrap('http://server'), 'a', 'href')).toEqual(
'http://server',
);
expect(ɵɵsanitizeUrlOrResourceUrl('javascript:true', 'a', 'href')).toEqual(
'unsafe:javascript:true',
);
expect(ɵɵsanitizeUrlOrResourceUrl(new Wrap('javascript:true'), 'a', 'href')).toEqual(
'unsafe:javascript:true',
);
expect(() =>
ɵɵsanitizeUrlOrResourceUrl(bypassSanitizationTrustHtml('javascript:true'), 'a', 'href'),
).toThrowError(/Required a safe URL, got a HTML/);
expect(
ɵɵsanitizeUrlOrResourceUrl(bypassSanitizationTrustUrl('javascript:true'), 'a', 'href'),
).toEqual('javascript:true');
});
it('should only trust constant strings from template literal tags without interpolation', () => {
expect(ɵɵtrustConstantHtml`<h1>good</h1>`.toString()).toEqual('<h1>good</h1>');
expect(ɵɵtrustConstantResourceUrl`http://good.com`.toString()).toEqual('http://good.com');
expect(() => (ɵɵtrustConstantHtml as any)`<h1>${'evil'}</h1>`).toThrowError(
/Unexpected interpolation in trusted HTML constant/,
);
expect(() => (ɵɵtrustConstantResourceUrl as any)`http://${'evil'}.com`).toThrowError(
/Unexpected interpolation in trusted URL constant/,
);
});
});
| {
"end_byte": 7674,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/sanitization/sanitization_spec.ts"
} |
angular/packages/core/test/sanitization/url_sanitizer_spec.ts_0_2308 | /**
* @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 {_sanitizeUrl} from '../../src/sanitization/url_sanitizer';
describe('URL sanitizer', () => {
let logMsgs: string[];
let originalLog: (msg: any) => any;
beforeEach(() => {
logMsgs = [];
originalLog = console.warn; // Monkey patch DOM.log.
console.warn = (msg: any) => logMsgs.push(msg);
});
afterEach(() => {
console.warn = originalLog;
});
it('reports unsafe URLs', () => {
expect(_sanitizeUrl('javascript:evil()')).toBe('unsafe:javascript:evil()');
expect(logMsgs.join('\n')).toMatch(/sanitizing unsafe URL value/);
});
describe('valid URLs', () => {
const validUrls = [
'',
'http://abc',
'HTTP://abc',
'https://abc',
'HTTPS://abc',
'ftp://abc',
'FTP://abc',
'mailto:me@example.com',
'MAILTO:me@example.com',
'tel:123-123-1234',
'TEL:123-123-1234',
'#anchor',
'/page1.md',
'http://JavaScript/my.js',
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/', // Truncated.
'data:video/webm;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:audio/opus;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'unknown-scheme:abc',
];
for (const url of validUrls) {
it(`valid ${url}`, () => expect(_sanitizeUrl(url)).toEqual(url));
}
});
describe('invalid URLs', () => {
const invalidUrls = [
'javascript:evil()',
'JavaScript:abc',
' javascript:abc',
' \n Java\n Script:abc',
'javascript:',
'javascript:',
'j avascript:',
'javascript:',
'javascript:',
'jav	ascript:alert();',
'jav\u0000ascript:alert();',
];
for (const url of invalidUrls) {
it(`valid ${url}`, () => expect(_sanitizeUrl(url)).toMatch(/^unsafe:/));
}
});
});
| {
"end_byte": 2308,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/sanitization/url_sanitizer_spec.ts"
} |
angular/packages/core/test/metadata/resource_loading_spec.ts_0_8316 | /**
* @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} from '../../src/core';
import {
clearResolutionOfComponentResourcesQueue,
isComponentResourceResolutionQueueEmpty,
resolveComponentResources,
} from '../../src/metadata/resource_loading';
import {ComponentType} from '../../src/render3/interfaces/definition';
import {compileComponent} from '../../src/render3/jit/directive';
describe('resource_loading', () => {
afterEach(clearResolutionOfComponentResourcesQueue);
describe('error handling', () => {
it('should throw an error when compiling component that has unresolved templateUrl', () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
compileComponent(MyComponent, {templateUrl: 'someUrl'});
expect(() => MyComponent.ɵcmp).toThrowError(
`
Component 'MyComponent' is not resolved:
- templateUrl: someUrl
Did you run and wait for 'resolveComponentResources()'?`.trim(),
);
});
it('should throw an error when compiling component that has unresolved styleUrls', () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
compileComponent(MyComponent, {styleUrls: ['someUrl1', 'someUrl2']});
expect(() => MyComponent.ɵcmp).toThrowError(
`
Component 'MyComponent' is not resolved:
- styleUrls: ["someUrl1","someUrl2"]
Did you run and wait for 'resolveComponentResources()'?`.trim(),
);
});
it('should throw an error when compiling component that has unresolved templateUrl and styleUrls', () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
compileComponent(MyComponent, {templateUrl: 'someUrl', styleUrls: ['someUrl1', 'someUrl2']});
expect(() => MyComponent.ɵcmp).toThrowError(
`
Component 'MyComponent' is not resolved:
- templateUrl: someUrl
- styleUrls: ["someUrl1","someUrl2"]
Did you run and wait for 'resolveComponentResources()'?`.trim(),
);
});
});
describe('resolution', () => {
const URLS: {[url: string]: Promise<string>} = {
'test://content': Promise.resolve('content'),
'test://style': Promise.resolve('style'),
'test://style1': Promise.resolve('style1'),
'test://style2': Promise.resolve('style2'),
};
let resourceFetchCount: number;
function testResolver(url: string): Promise<string> {
resourceFetchCount++;
return URLS[url] || Promise.reject('NOT_FOUND: ' + url);
}
beforeEach(() => (resourceFetchCount = 0));
it('should resolve template', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {templateUrl: 'test://content'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.template).toBe('content');
expect(resourceFetchCount).toBe(1);
});
it('should resolve styleUrls', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {template: '', styleUrls: ['test://style1', 'test://style2']};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['style1', 'style2']);
expect(resourceFetchCount).toBe(2);
});
it('should cache multiple resolution to same URL', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {template: '', styleUrls: ['test://style1', 'test://style1']};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['style1', 'style1']);
expect(resourceFetchCount).toBe(1);
});
it('should keep order even if the resolution is out of order', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {
template: '',
styles: ['existing'],
styleUrls: ['test://style1', 'test://style2'],
};
compileComponent(MyComponent, metadata);
const resolvers: any[] = [];
const resolved = resolveComponentResources(
(url) => new Promise((resolve, response) => resolvers.push(url, resolve)),
);
// Out of order resolution
expect(resolvers[0]).toEqual('test://style1');
expect(resolvers[2]).toEqual('test://style2');
resolvers[3]('second');
resolvers[1]('first');
await resolved;
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['existing', 'first', 'second']);
});
it('should not add components without external resources to resolution queue', () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const MyComponent2: ComponentType<any> = class MyComponent {} as any;
compileComponent(MyComponent, {template: ''});
expect(isComponentResourceResolutionQueueEmpty()).toBe(true);
compileComponent(MyComponent2, {templateUrl: 'test://template'});
expect(isComponentResourceResolutionQueueEmpty()).toBe(false);
});
it('should resolve styles passed in as a string', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {template: '', styles: 'existing'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual('existing');
expect(resourceFetchCount).toBe(0);
});
it('should resolve styleUrl', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {template: '', styleUrl: 'test://style'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.styleUrl).toBe(undefined);
expect(metadata.styles).toEqual(['style']);
expect(resourceFetchCount).toBe(1);
});
it('should resolve both styles passed in as a string together with styleUrl', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {template: '', styleUrl: 'test://style', styles: 'existing'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(testResolver);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.styleUrls).toBe(undefined);
expect(metadata.styles).toEqual(['existing', 'style']);
expect(resourceFetchCount).toBe(1);
});
it('should throw if both styleUrls and styleUrl are passed in', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {
template: '',
styleUrl: 'test://style1',
styleUrls: ['test://style2'],
};
compileComponent(MyComponent, metadata);
expect(() => resolveComponentResources(testResolver)).toThrowError(
/@Component cannot define both `styleUrl` and `styleUrls`/,
);
});
});
describe('fetch', () => {
function fetch(url: string): Promise<Response> {
return Promise.resolve({
text() {
return 'response for ' + url;
},
} as any as Response);
}
it('should work with fetch', async () => {
const MyComponent: ComponentType<any> = class MyComponent {} as any;
const metadata: Component = {templateUrl: 'test://content'};
compileComponent(MyComponent, metadata);
await resolveComponentResources(fetch);
expect(MyComponent.ɵcmp).toBeDefined();
expect(metadata.template).toBe('response for test://content');
});
});
});
| {
"end_byte": 8316,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/metadata/resource_loading_spec.ts"
} |
angular/packages/core/test/metadata/di_spec.ts_0_3518 | /**
* @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,
Directive,
ElementRef,
Input,
NO_ERRORS_SCHEMA,
QueryList,
ViewChild,
ViewChildren,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
describe('ViewChild', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ViewChildTypeSelectorComponent, ViewChildStringSelectorComponent, Simple],
schemas: [NO_ERRORS_SCHEMA],
});
});
it('should support type selector', () => {
TestBed.overrideComponent(ViewChildTypeSelectorComponent, {
set: {template: `<simple [marker]="'1'"></simple><simple [marker]="'2'"></simple>`},
});
const view = TestBed.createComponent(ViewChildTypeSelectorComponent);
view.detectChanges();
expect(view.componentInstance.child).toBeDefined();
expect(view.componentInstance.child.marker).toBe('1');
});
it('should support string selector', () => {
TestBed.overrideComponent(ViewChildStringSelectorComponent, {
set: {template: `<simple #child></simple>`},
});
const view = TestBed.createComponent(ViewChildStringSelectorComponent);
view.detectChanges();
expect(view.componentInstance.child).toBeDefined();
});
});
describe('ViewChildren', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
ViewChildrenTypeSelectorComponent,
ViewChildrenStringSelectorComponent,
Simple,
],
schemas: [NO_ERRORS_SCHEMA],
});
});
it('should support type selector', () => {
TestBed.overrideComponent(ViewChildrenTypeSelectorComponent, {
set: {template: `<simple></simple><simple></simple>`},
});
const view = TestBed.createComponent(ViewChildrenTypeSelectorComponent);
view.detectChanges();
expect(view.componentInstance.children).toBeDefined();
expect(view.componentInstance.children.length).toBe(2);
});
it('should support string selector', () => {
TestBed.overrideComponent(ViewChildrenStringSelectorComponent, {
set: {template: `<simple #child1></simple><simple #child2></simple>`},
});
const view = TestBed.configureTestingModule({schemas: [NO_ERRORS_SCHEMA]}).createComponent(
ViewChildrenStringSelectorComponent,
);
view.detectChanges();
expect(view.componentInstance.children).toBeDefined();
expect(view.componentInstance.children.length).toBe(2);
});
});
@Directive({
selector: 'simple',
standalone: false,
})
class Simple {
@Input() marker: string | undefined;
}
@Component({
selector: 'view-child-type-selector',
template: '',
standalone: false,
})
class ViewChildTypeSelectorComponent {
@ViewChild(Simple) child!: Simple;
}
@Component({
selector: 'view-child-string-selector',
template: '',
standalone: false,
})
class ViewChildStringSelectorComponent {
@ViewChild('child') child!: ElementRef;
}
@Component({
selector: 'view-children-type-selector',
template: '',
standalone: false,
})
class ViewChildrenTypeSelectorComponent {
@ViewChildren(Simple) children!: QueryList<Simple>;
}
@Component({
selector: 'view-child-string-selector',
template: '',
standalone: false,
})
class ViewChildrenStringSelectorComponent {
// Allow comma separated selector (with spaces).
@ViewChildren('child1 , child2') children!: QueryList<ElementRef>;
}
| {
"end_byte": 3518,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/metadata/di_spec.ts"
} |
angular/packages/core/test/compiler/compiler_facade_spec.ts_0_2839 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getCompilerFacade, JitCompilerUsage} from '../../src/compiler/compiler_facade';
import {CompilerFacade, ExportedCompilerFacade} from '../../src/compiler/compiler_facade_interface';
import {global} from '../../src/util/global';
describe('getCompilerFacade', () => {
describe('errors', () => {
beforeEach(clearCompilerFacade);
afterEach(restoreCompilerFacade);
it('reports an error when requested for a decorator', () => {
try {
getCompilerFacade({usage: JitCompilerUsage.Decorator, kind: 'directive', type: TestClass});
fail('Error expected as compiler facade is not available');
} catch (e) {
expect((e as Error).message).toEqual(
`The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.
JIT compilation is discouraged for production use-cases! Consider using AOT mode instead.
Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',
or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`,
);
}
});
it('reports an error when requested for a partial declaration', () => {
try {
getCompilerFacade({
usage: JitCompilerUsage.PartialDeclaration,
kind: 'directive',
type: TestClass,
});
fail('Error expected as compiler facade is not available');
} catch (e) {
expect((e as Error).message).toEqual(
`The directive 'TestClass' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available.
The directive is part of a library that has been partially compiled.
However, the Angular Linker has not processed the library such that JIT compilation is used as fallback.
Ideally, the library is processed using the Angular Linker to become fully AOT compiled.
Alternatively, the JIT compiler should be loaded by bootstrapping using '@angular/platform-browser-dynamic' or '@angular/platform-server',
or manually provide the compiler with 'import "@angular/compiler";' before bootstrapping.`,
);
}
});
});
});
class TestClass {}
let ɵcompilerFacade: CompilerFacade | null = null;
function clearCompilerFacade() {
const ng: ExportedCompilerFacade = global.ng;
ɵcompilerFacade = ng.ɵcompilerFacade;
ng.ɵcompilerFacade = undefined!;
}
function restoreCompilerFacade() {
if (ɵcompilerFacade === null) {
return;
}
const ng: ExportedCompilerFacade = global.ng;
ng.ɵcompilerFacade = ɵcompilerFacade;
ɵcompilerFacade = null;
}
| {
"end_byte": 2839,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/compiler/compiler_facade_spec.ts"
} |
angular/packages/core/test/compiler/BUILD.bazel_0_577 | load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library")
package(default_visibility = ["//visibility:private"])
ts_library(
name = "compiler_lib",
testonly = True,
srcs = glob(
["**/*.ts"],
),
deps = [
"//packages/core/src/compiler",
"//packages/core/src/util",
],
)
jasmine_node_test(
name = "compiler",
bootstrap = ["//tools/testing:node"],
deps = [
":compiler_lib",
],
)
karma_web_test_suite(
name = "compiler_web",
deps = [
":compiler_lib",
],
)
| {
"end_byte": 577,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/compiler/BUILD.bazel"
} |
angular/packages/core/test/debug/debug_node_spec.ts_0_6796 | /**
* @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, NgIfContext, ɵgetDOM as getDOM} from '@angular/common';
import {
Component,
DebugElement,
DebugNode,
Directive,
ElementRef,
EmbeddedViewRef,
EventEmitter,
HostBinding,
Injectable,
Input,
NgZone,
NO_ERRORS_SCHEMA,
OnInit,
Output,
Renderer2,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {createMouseEvent, hasClass} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
@Injectable()
class Logger {
logs: string[];
constructor() {
this.logs = [];
}
add(thing: string) {
this.logs.push(thing);
}
}
@Directive({
selector: '[message]',
inputs: ['message'],
standalone: false,
})
class MessageDir {
logger: Logger;
constructor(logger: Logger) {
this.logger = logger;
}
set message(newMessage: string) {
this.logger.add(newMessage);
}
}
@Directive({
selector: '[with-title]',
inputs: ['title'],
standalone: false,
})
class WithTitleDir {
title = '';
}
@Component({
selector: 'child-comp',
template: `<div class="child" message="child">
<span class="childnested" message="nestedchild">Child</span>
</div>
<span class="child" [innerHtml]="childBinding"></span>`,
standalone: false,
})
class ChildComp {
childBinding: string;
constructor() {
this.childBinding = 'Original';
}
}
@Component({
selector: 'parent-comp',
viewProviders: [Logger],
template: `<div class="parent" message="parent">
<span class="parentnested" message="nestedparent">Parent</span>
</div>
<span class="parent" [innerHtml]="parentBinding"></span>
<child-comp class="child-comp-class"></child-comp>`,
standalone: false,
})
class ParentComp {
parentBinding: string;
constructor() {
this.parentBinding = 'OriginalParent';
}
}
@Directive({
selector: 'custom-emitter',
outputs: ['myevent'],
standalone: false,
})
class CustomEmitter {
myevent: EventEmitter<any>;
constructor() {
this.myevent = new EventEmitter();
}
}
@Component({
selector: 'events-comp',
template: `<button (click)="handleClick()"></button>
<custom-emitter (myevent)="handleCustom()"></custom-emitter>`,
standalone: false,
})
class EventsComp {
clicked: boolean;
customed: boolean;
constructor() {
this.clicked = false;
this.customed = false;
}
handleClick() {
this.clicked = true;
}
handleCustom() {
this.customed = true;
}
}
@Component({
selector: 'cond-content-comp',
viewProviders: [Logger],
template: `<div class="child" message="child" *ngIf="myBool"><ng-content></ng-content></div>`,
standalone: false,
})
class ConditionalContentComp {
myBool: boolean = false;
}
@Component({
selector: 'conditional-parent-comp',
viewProviders: [Logger],
template: `<span class="parent" [innerHtml]="parentBinding"></span>
<cond-content-comp class="cond-content-comp-class">
<span class="from-parent"></span>
</cond-content-comp>`,
standalone: false,
})
class ConditionalParentComp {
parentBinding: string;
constructor() {
this.parentBinding = 'OriginalParent';
}
}
@Component({
selector: 'using-for',
viewProviders: [Logger],
template: `<span *ngFor="let thing of stuff" [innerHtml]="thing"></span>
<ul message="list">
<li *ngFor="let item of stuff" [innerHtml]="item"></li>
</ul>`,
standalone: false,
})
class UsingFor {
stuff: string[];
constructor() {
this.stuff = ['one', 'two', 'three'];
}
}
@Directive({
selector: '[mydir]',
exportAs: 'mydir',
standalone: false,
})
class MyDir {}
@Component({
selector: 'locals-comp',
template: `
<div mydir #alice="mydir"></div>
`,
standalone: false,
})
class LocalsComp {}
@Component({
selector: 'bank-account',
template: `
Bank Name: {{bank}}
Account Id: {{id}}
`,
host: {
'class': 'static-class',
'[class.absent-class]': 'false',
'[class.present-class]': 'true',
},
standalone: false,
})
class BankAccount {
@Input() bank: string | undefined;
@Input('account') id: string | undefined;
normalizedBankName: string | undefined;
}
@Component({
template: `
<div class="content" #content>Some content</div>
`,
standalone: false,
})
class SimpleContentComp {
@ViewChild('content') content!: ElementRef;
}
@Component({
selector: 'test-app',
template: `
<bank-account bank="RBC"
account="4747"
[style.width.px]="width"
[style.color]="color"
[class.closed]="isClosed"
[class.open]="!isClosed"></bank-account>
`,
standalone: false,
})
class TestApp {
width = 200;
color = 'red';
isClosed = true;
constructor(public renderer: Renderer2) {}
}
@Component({
selector: 'test-cmpt',
template: ``,
standalone: false,
})
class TestCmpt {}
@Component({
selector: 'test-cmpt-renderer',
template: ``,
standalone: false,
})
class TestCmptWithRenderer {
constructor(public renderer: Renderer2) {}
}
@Component({
selector: 'host-class-binding',
template: '',
standalone: false,
})
class HostClassBindingCmp {
@HostBinding('class') hostClasses = 'class-one class-two';
}
@Component({
selector: 'test-cmpt-vcref',
template: `<div></div>`,
standalone: false,
})
class TestCmptWithViewContainerRef {
constructor(private vcref: ViewContainerRef) {}
}
@Component({
template: `
<button
[disabled]="disabled"
[tabIndex]="tabIndex"
[title]="title">Click me</button>
`,
standalone: false,
})
class TestCmptWithPropBindings {
disabled = true;
tabIndex = 1337;
title = 'hello';
}
@Component({
template: `
<button title="{{0}}"></button>
<button title="a{{1}}b"></button>
<button title="a{{1}}b{{2}}c"></button>
<button title="a{{1}}b{{2}}c{{3}}d"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e{{5}}f"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e{{5}}f{{6}}g"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e{{5}}f{{6}}g{{7}}h"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e{{5}}f{{6}}g{{7}}h{{8}}i"></button>
<button title="a{{1}}b{{2}}c{{3}}d{{4}}e{{5}}f{{6}}g{{7}}h{{8}}i{{9}}j"></button>
`,
standalone: false,
})
class TestCmptWithPropInterpolation {}
| {
"end_byte": 6796,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/debug/debug_node_spec.ts_6798_15756 | escribe('debug element', () => {
let fixture: ComponentFixture<any>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
ChildComp,
ConditionalContentComp,
ConditionalParentComp,
CustomEmitter,
EventsComp,
LocalsComp,
MessageDir,
MyDir,
ParentComp,
TestApp,
UsingFor,
BankAccount,
TestCmpt,
HostClassBindingCmp,
TestCmptWithViewContainerRef,
SimpleContentComp,
TestCmptWithPropBindings,
TestCmptWithPropInterpolation,
TestCmptWithRenderer,
WithTitleDir,
],
providers: [Logger],
schemas: [NO_ERRORS_SCHEMA],
});
}));
it('should list all child nodes', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement.childNodes.length).toEqual(3);
});
it('should list all component child elements', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
// The root component has 3 elements in its view.
expect(childEls.length).toEqual(3);
expect(hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[1].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true);
const nested = childEls[0].children;
expect(nested.length).toEqual(1);
expect(hasClass(nested[0].nativeElement, 'parentnested')).toBe(true);
const childComponent = childEls[2];
const childCompChildren = childComponent.children;
expect(childCompChildren.length).toEqual(2);
expect(hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true);
expect(hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true);
const childNested = childCompChildren[0].children;
expect(childNested.length).toEqual(1);
expect(hasClass(childNested[0].nativeElement, 'childnested')).toBe(true);
});
it('should list conditional component child elements', () => {
fixture = TestBed.createComponent(ConditionalParentComp);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
// The root component has 2 elements in its view.
expect(childEls.length).toEqual(2);
expect(hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[1].nativeElement, 'cond-content-comp-class')).toBe(true);
const conditionalContentComp = childEls[1];
expect(conditionalContentComp.children.length).toEqual(0);
conditionalContentComp.componentInstance.myBool = true;
fixture.detectChanges();
expect(conditionalContentComp.children.length).toEqual(1);
});
it('should list child elements within viewports', () => {
fixture = TestBed.createComponent(UsingFor);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
expect(childEls.length).toEqual(4);
// The 4th child is the <ul>
const list = childEls[3];
expect(list.children.length).toEqual(3);
});
it('should list element attributes', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.attributes['bank']).toEqual('RBC');
expect(bankElem.attributes['account']).toEqual('4747');
});
it('should list element classes', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.classes['closed']).toBe(true);
expect(bankElem.classes['open']).toBeFalsy();
});
it('should get element classes from host bindings', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElement = fixture.debugElement.children[0];
expect(debugElement.classes['present-class']).toBe(
true,
'Expected bound host CSS class "present-class" to be present',
);
expect(debugElement.classes['absent-class']).toBeFalsy(
'Expected bound host CSS class "absent-class" to be absent',
);
});
it('should list classes on SVG nodes', () => {
// Class bindings on SVG elements require a polyfill
// on IE which we don't include when running tests.
if (typeof SVGElement !== 'undefined' && !('classList' in SVGElement.prototype)) {
return;
}
TestBed.overrideTemplate(TestApp, `<svg [class.foo]="true" [class.bar]="true"></svg>`);
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const classes = fixture.debugElement.children[0].classes;
expect(classes['foo']).toBe(true);
expect(classes['bar']).toBe(true);
});
it('should list element styles', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.styles['width']).toEqual('200px');
expect(bankElem.styles['color']).toEqual('red');
});
it('should query child elements by css', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestEls = fixture.debugElement.queryAll(By.css('child-comp'));
expect(childTestEls.length).toBe(1);
expect(hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true);
});
it('should query child elements by directive', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir));
expect(childTestEls.length).toBe(4);
expect(hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true);
expect(hasClass(childTestEls[2].nativeElement, 'child')).toBe(true);
expect(hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true);
});
it('should query projected child elements by directive', () => {
@Directive({
selector: 'example-directive-a',
standalone: false,
})
class ExampleDirectiveA {}
@Component({
selector: 'wrapper-component',
template: `
<ng-content select="example-directive-a"></ng-content>
`,
standalone: false,
})
class WrapperComponent {}
TestBed.configureTestingModule({
declarations: [WrapperComponent, ExampleDirectiveA],
});
TestBed.overrideTemplate(
TestApp,
`<wrapper-component>
<div></div>
<example-directive-a></example-directive-a>
</wrapper-component>`,
);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElement = fixture.debugElement.query(By.directive(ExampleDirectiveA));
expect(debugElement).toBeTruthy();
});
it('should query re-projected child elements by directive', () => {
@Directive({
selector: 'example-directive-a',
standalone: false,
})
class ExampleDirectiveA {}
@Component({
selector: 'proxy-component',
template: `
<ng-content></ng-content>
`,
standalone: false,
})
class ProxyComponent {}
@Component({
selector: 'wrapper-component',
template: `
<proxy-component>
<ng-content select="div"></ng-content>
<ng-content select="example-directive-a"></ng-content>
</proxy-component>
`,
standalone: false,
})
class WrapperComponent {}
TestBed.configureTestingModule({
declarations: [ProxyComponent, WrapperComponent, ExampleDirectiveA],
});
TestBed.overrideTemplate(
TestApp,
`<wrapper-component>
<div></div>
<example-directive-a></example-directive-a>
</wrapper-component>`,
);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElements = fixture.debugElement.queryAll(By.directive(ExampleDirectiveA));
expect(debugElements.length).toBe(1);
});
it('should query directives on containers before directives in a view', () => {
@Directive({
selector: '[text]',
standalone: false,
})
class TextDirective {
@Input() text: string | undefined;
}
TestBed.configureTestingModule({declarations: [TextDirective]});
TestBed.overrideTemplate(
TestApp,
`<ng-template text="first" [ngIf]="true"><div text="second"></div></ng-template>`,
);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
expect(debugNodes[1].injector.get(TextDirective).text).toBe('second');
});
| {
"end_byte": 15756,
"start_byte": 6798,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/debug/debug_node_spec.ts_15760_24724 | t('should query directives on views moved in the DOM', () => {
@Directive({
selector: '[text]',
standalone: false,
})
class TextDirective {
@Input() text: string | undefined;
}
@Directive({
selector: '[moveView]',
standalone: false,
})
class ViewManipulatingDirective {
constructor(
private _vcRef: ViewContainerRef,
private _tplRef: TemplateRef<any>,
) {}
insert() {
this._vcRef.createEmbeddedView(this._tplRef);
}
removeFromTheDom() {
const viewRef = this._vcRef.get(0) as EmbeddedViewRef<any>;
viewRef.rootNodes.forEach((rootNode) => {
getDOM().remove(rootNode);
});
}
}
TestBed.configureTestingModule({declarations: [TextDirective, ViewManipulatingDirective]});
TestBed.overrideTemplate(
TestApp,
`<ng-template text="first" moveView><div text="second"></div></ng-template>`,
);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const viewMover = fixture.debugElement
.queryAllNodes(By.directive(ViewManipulatingDirective))[0]
.injector.get(ViewManipulatingDirective);
let debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
// we've got just one directive on <ng-template>
expect(debugNodes.length).toBe(1);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
// insert a view - now we expect to find 2 directive instances
viewMover.insert();
fixture.detectChanges();
debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
// remove a view from the DOM (equivalent to moving it around)
// the logical tree is the same but DOM has changed
viewMover.removeFromTheDom();
debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
expect(debugNodes[1].injector.get(TextDirective).text).toBe('second');
});
it('DebugElement.query should work with dynamically created elements', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
@Input('dir') dir: number | undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(element.nativeElement, div);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div>',
standalone: false,
})
class MyComponent {}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.myclass'))).toBeTruthy();
});
it('should not throw when calling DebugRenderer2.destroyNode twice in a row', () => {
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const firstChild = fixture.debugElement.children[0];
const renderer = fixture.componentInstance.renderer;
expect(firstChild).toBeTruthy();
expect(() => {
// `destroyNode` needs to be null checked, because only ViewEngine provides a
// `DebugRenderer2` which has the behavior we're testing for. Ivy provides
// `BaseAnimationRenderer` which doesn't have the issue.
renderer.destroyNode?.(firstChild);
renderer.destroyNode?.(firstChild);
}).not.toThrow();
});
describe('DebugElement.query with dynamically created descendant elements', () => {
let fixture: ComponentFixture<{}>;
beforeEach(() => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
@Input('dir') dir: number | undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const outerDiv = renderer.createElement('div');
const innerDiv = renderer.createElement('div');
innerDiv.classList.add('inner');
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(innerDiv, div);
renderer.appendChild(outerDiv, innerDiv);
renderer.appendChild(element.nativeElement, outerDiv);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div>',
standalone: false,
})
class MyComponent {}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
});
it('should find the dynamic elements from fixture root', () => {
expect(fixture.debugElement.query(By.css('.myclass'))).toBeTruthy();
});
it('can use a dynamic element as root for another query', () => {
const inner = fixture.debugElement.query(By.css('.inner'));
expect(inner).toBeTruthy();
expect(inner.query(By.css('.myclass'))).toBeTruthy();
});
});
describe("DebugElement.query doesn't fail on elements outside Angular context", () => {
@Component({
template: '<div></div>',
standalone: false,
})
class NativeEl {
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
const ul = document.createElement('ul');
ul.appendChild(document.createElement('li'));
this.elementRef.nativeElement.children[0].appendChild(ul);
}
}
let el: DebugElement;
beforeEach(() => {
const fixture = TestBed.configureTestingModule({declarations: [NativeEl]}).createComponent(
NativeEl,
);
fixture.detectChanges();
el = fixture.debugElement;
});
it('when searching for elements by name', () => {
expect(() => el.query((e) => e.name === 'any search text')).not.toThrow();
});
it('when searching for elements by their attributes', () => {
expect(() => el.query((e) => e.attributes!['name'] === 'any attribute')).not.toThrow();
});
it('when searching for elements by their classes', () => {
expect(() => el.query((e) => e.classes['any class'] === true)).not.toThrow();
});
it('when searching for elements by their styles', () => {
expect(() => el.query((e) => e.styles['any style'] === 'any value')).not.toThrow();
});
it('when searching for elements by their properties', () => {
expect(() => el.query((e) => e.properties['any prop'] === 'any value')).not.toThrow();
});
it('when searching by componentInstance', () => {
expect(() => el.query((e) => e.componentInstance === null)).not.toThrow();
});
it('when searching by context', () => {
expect(() => el.query((e) => e.context === null)).not.toThrow();
});
it('when searching by listeners', () => {
expect(() => el.query((e) => e.listeners.length === 0)).not.toThrow();
});
it('when searching by references', () => {
expect(() => el.query((e) => e.references === null)).not.toThrow();
});
it('when searching by providerTokens', () => {
expect(() => el.query((e) => e.providerTokens.length === 0)).not.toThrow();
});
it('when searching by injector', () => {
expect(() => el.query((e) => e.injector === null)).not.toThrow();
});
it('when using the out-of-context element as the DebugElement query root', () => {
const debugElOutsideAngularContext = el.query(By.css('ul'));
expect(debugElOutsideAngularContext.queryAll(By.css('li')).length).toBe(1);
expect(debugElOutsideAngularContext.query(By.css('li'))).toBeDefined();
});
});
it('DebugElement.queryAll should pick up both elements inserted via the view and through Renderer2', () => {
@Directive({
selector: '[dir]',
standalone: false,
})
class MyDir {
@Input('dir') dir: number | undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(element.nativeElement, div);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div><span class="myclass"></span>',
standalone: false,
})
class MyComponent {}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
const results = fixture.debugElement.queryAll(By.css('.myclass'));
expect(results.map((r) => r.nativeElement.nodeName.toLowerCase())).toEqual(['div', 'span']);
});
it('should list providerTokens', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement.providerTokens).toContain(Logger);
});
| {
"end_byte": 24724,
"start_byte": 15760,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/debug/debug_node_spec.ts_24728_32648 | t('should list locals', () => {
fixture = TestBed.createComponent(LocalsComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].references['alice']).toBeInstanceOf(MyDir);
});
it('should allow injecting from the element injector', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect((<Logger>fixture.debugElement.children[0].injector.get(Logger)).logs).toEqual([
'parent',
'nestedparent',
'child',
'nestedchild',
]);
});
it('should list event listeners', () => {
fixture = TestBed.createComponent(EventsComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].listeners.length).toEqual(1);
expect(fixture.debugElement.children[1].listeners.length).toEqual(1);
});
it('should trigger event handlers', () => {
fixture = TestBed.createComponent(EventsComp);
fixture.detectChanges();
expect(fixture.componentInstance.clicked).toBe(false);
expect(fixture.componentInstance.customed).toBe(false);
fixture.debugElement.children[0].triggerEventHandler('click', <Event>{});
expect(fixture.componentInstance.clicked).toBe(true);
fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{});
expect(fixture.componentInstance.customed).toBe(true);
});
describe('properties', () => {
it('should include classes in properties.className', () => {
fixture = TestBed.createComponent(HostClassBindingCmp);
fixture.detectChanges();
const debugElement = fixture.debugElement;
expect(debugElement.properties['className']).toBe('class-one class-two');
fixture.componentInstance.hostClasses = 'class-three';
fixture.detectChanges();
expect(debugElement.properties['className']).toBe('class-three');
fixture.componentInstance.hostClasses = '';
fixture.detectChanges();
expect(debugElement.properties['className']).toBeFalsy();
});
it('should preserve the type of the property values', () => {
const fixture = TestBed.createComponent(TestCmptWithPropBindings);
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'));
expect(button.properties['disabled']).toEqual(true);
expect(button.properties['tabIndex']).toEqual(1337);
expect(button.properties['title']).toEqual('hello');
});
it('should include interpolated properties in the properties map', () => {
const fixture = TestBed.createComponent(TestCmptWithPropInterpolation);
fixture.detectChanges();
const buttons = fixture.debugElement.children;
expect(buttons.length).toBe(10);
expect(buttons[0].properties['title']).toBe('0');
expect(buttons[1].properties['title']).toBe('a1b');
expect(buttons[2].properties['title']).toBe('a1b2c');
expect(buttons[3].properties['title']).toBe('a1b2c3d');
expect(buttons[4].properties['title']).toBe('a1b2c3d4e');
expect(buttons[5].properties['title']).toBe('a1b2c3d4e5f');
expect(buttons[6].properties['title']).toBe('a1b2c3d4e5f6g');
expect(buttons[7].properties['title']).toBe('a1b2c3d4e5f6g7h');
expect(buttons[8].properties['title']).toBe('a1b2c3d4e5f6g7h8i');
expect(buttons[9].properties['title']).toBe('a1b2c3d4e5f6g7h8i9j');
});
it('should not include directive-shadowed properties in the properties map', () => {
TestBed.overrideTemplate(
TestCmptWithPropInterpolation,
`<button with-title [title]="'goes to input'"></button>`,
);
const fixture = TestBed.createComponent(TestCmptWithPropInterpolation);
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'));
expect(button.properties['title']).not.toEqual('goes to input');
});
it('should return native properties from DOM element even if no binding present', () => {
TestBed.overrideTemplate(TestCmptWithRenderer, `<button></button>`);
const fixture = TestBed.createComponent(TestCmptWithRenderer);
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'));
fixture.componentInstance.renderer.setProperty(button.nativeElement, 'title', 'myTitle');
expect(button.properties['title']).toBe('myTitle');
});
it('should not include patched properties (starting with __) and on* properties', () => {
TestBed.overrideTemplate(
TestCmptWithPropInterpolation,
`<button title="myTitle" (click)="true;"></button>`,
);
const fixture = TestBed.createComponent(TestCmptWithPropInterpolation);
fixture.detectChanges();
const host = fixture.debugElement;
const button = fixture.debugElement.query(By.css('button'));
expect(Object.keys(host.properties).filter((key) => key.startsWith('__'))).toEqual([]);
expect(Object.keys(host.properties).filter((key) => key.startsWith('on'))).toEqual([]);
expect(Object.keys(button.properties).filter((key) => key.startsWith('__'))).toEqual([]);
expect(Object.keys(button.properties).filter((key) => key.startsWith('on'))).toEqual([]);
});
it('should pickup all of the element properties', () => {
TestBed.overrideTemplate(TestCmptWithPropInterpolation, `<button title="myTitle"></button>`);
const fixture = TestBed.createComponent(TestCmptWithPropInterpolation);
fixture.detectChanges();
const host = fixture.debugElement;
const button = fixture.debugElement.query(By.css('button'));
expect(button.properties['title']).toEqual('myTitle');
});
});
it('should trigger events registered via Renderer2', () => {
@Component({
template: '',
standalone: false,
})
class TestComponent implements OnInit {
count = 0;
eventObj1: any;
eventObj2: any;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef,
private ngZone: NgZone,
) {}
ngOnInit() {
this.renderer.listen(this.elementRef.nativeElement, 'click', (event: any) => {
this.count++;
this.eventObj1 = event;
});
this.ngZone.runOutsideAngular(() => {
this.renderer.listen(this.elementRef.nativeElement, 'click', (event: any) => {
this.count++;
this.eventObj2 = event;
});
});
}
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
// Ivy depends on `eventListeners` to pick up events that haven't been registered through
// Angular templates. At the time of writing Zone.js doesn't add `eventListeners` in Node
// environments so we have to skip the test.
if (typeof fixture.debugElement.nativeElement.eventListeners === 'function') {
const event = {value: true};
fixture.detectChanges();
fixture.debugElement.triggerEventHandler('click', event);
expect(fixture.componentInstance.count).toBe(2);
expect(fixture.componentInstance.eventObj2).toBe(event);
}
});
it('should be able to trigger an event with a null value', () => {
let value = undefined;
@Component({
template: '<button (click)="handleClick($event)"></button>',
standalone: false,
})
class TestComponent {
handleClick(_event: any) {
value = _event;
// Returning `false` is what causes the renderer to call `event.preventDefault`.
return false;
}
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
const button = fixture.debugElement.query(By.css('button'));
expect(() => {
button.triggerEventHandler('click');
fixture.detectChanges();
}).not.toThrow();
expect(value).toBeUndefined();
});
| {
"end_byte": 32648,
"start_byte": 24728,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/debug/debug_node_spec.ts_32652_41632 | escribe('componentInstance on DebugNode', () => {
it('should return component associated with a node if a node is a component host', () => {
TestBed.overrideTemplate(TestCmpt, `<parent-comp></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0];
expect(debugEl.componentInstance).toBeInstanceOf(ParentComp);
});
it('should return component associated with a node if a node is a component host (content projection)', () => {
TestBed.overrideTemplate(TestCmpt, `<parent-comp><child-comp></child-comp></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.query(By.directive(ChildComp));
expect(debugEl.componentInstance).toBeInstanceOf(ChildComp);
});
it('should return host component instance if a node has no associated component and there is no component projecting this node', () => {
TestBed.overrideTemplate(TestCmpt, `<div></div>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0];
expect(debugEl.componentInstance).toBeInstanceOf(TestCmpt);
});
it('should return host component instance if a node has no associated component and there is no component projecting this node (nested embedded views)', () => {
TestBed.overrideTemplate(
TestCmpt,
`
<ng-template [ngIf]="true">
<ng-template [ngIf]="true">
<div mydir></div>
</ng-template>
</ng-template>`,
);
fixture = TestBed.createComponent(TestCmpt);
fixture.detectChanges();
const debugEl = fixture.debugElement.query(By.directive(MyDir));
expect(debugEl.componentInstance).toBeInstanceOf(TestCmpt);
});
it('should return component instance that projects a given node if a node has no associated component', () => {
TestBed.overrideTemplate(TestCmpt, `<parent-comp><span><div></div></span></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0].children[0].children[0]; // <div>
expect(debugEl.componentInstance).toBeInstanceOf(ParentComp);
});
});
describe('context on DebugNode', () => {
it('should return component associated with the node if both a structural directive and a component match the node', () => {
@Component({
selector: 'example-component',
template: '',
standalone: false,
})
class ExampleComponent {}
TestBed.configureTestingModule({imports: [CommonModule], declarations: [ExampleComponent]});
TestBed.overrideTemplate(TestApp, '<example-component *ngIf="true"></example-component>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.directive(ExampleComponent));
expect(debugNode.context instanceof ExampleComponent).toBe(true);
});
it('should return structural directive context if there is a structural directive on the node', () => {
TestBed.configureTestingModule({imports: [CommonModule]});
TestBed.overrideTemplate(TestApp, '<span *ngIf="true"></span>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.css('span'));
expect(debugNode.context instanceof NgIfContext).toBe(true);
});
it('should return the containing component if there is no structural directive or component on the node', () => {
TestBed.configureTestingModule({declarations: [MyDir]});
TestBed.overrideTemplate(TestApp, '<span mydir></span>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.directive(MyDir));
expect(debugNode.context instanceof TestApp).toBe(true);
});
});
it('should be able to query for elements that are not in the same DOM tree anymore', () => {
fixture = TestBed.createComponent(SimpleContentComp);
fixture.detectChanges();
const parent = fixture.nativeElement.parentElement;
const content = fixture.componentInstance.content.nativeElement;
// Move the content element outside the component
// so that it can't be reached via querySelector.
parent.appendChild(content);
expect(fixture.debugElement.query(By.css('.content'))).toBeTruthy();
getDOM().remove(content);
});
it('should support components with ViewContainerRef', () => {
fixture = TestBed.createComponent(TestCmptWithViewContainerRef);
const divEl = fixture.debugElement.query(By.css('div'));
expect(divEl).not.toBeNull();
});
it('should support querying on any debug element', () => {
TestBed.overrideTemplate(TestCmpt, `<span><div id="a"><div id="b"></div></div></span>`);
fixture = TestBed.createComponent(TestCmpt);
const divA = fixture.debugElement.query(By.css('div'));
expect(divA.nativeElement.getAttribute('id')).toBe('a');
const divB = divA.query(By.css('div'));
expect(divB.nativeElement.getAttribute('id')).toBe('b');
});
it('should be an instance of DebugNode', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement).toBeInstanceOf(DebugNode);
});
it('should return the same element when queried twice', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestElsFirst = fixture.debugElement.queryAll(By.css('child-comp'));
const childTestElsSecond = fixture.debugElement.queryAll(By.css('child-comp'));
expect(childTestElsFirst.length).toBe(1);
expect(childTestElsSecond[0]).toBe(childTestElsFirst[0]);
});
it('should not query the descendants of a sibling node', () => {
@Component({
selector: 'my-comp',
template: `
<div class="div.1">
<p class="p.1">
<span class="span.1">span.1</span>
<span class="span.2">span.2</span>
</p>
<p class="p.2">
<span class="span.3">span.3</span>
<span class="span.4">span.4</span>
</p>
</div>
<div class="div.2">
<p class="p.3">
<span class="span.5">span.5</span>
<span class="span.6">span.6</span>
</p>
<p class="p.4">
<span class="span.7">span.7</span>
<span class="span.8">span.8</span>
</p>
</div>
`,
standalone: false,
})
class MyComp {}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const firstDiv = fixture.debugElement.query(By.css('div'));
const firstDivChildren = firstDiv.queryAll(By.css('span'));
expect(firstDivChildren.map((child) => child.nativeNode.textContent.trim())).toEqual([
'span.1',
'span.2',
'span.3',
'span.4',
]);
});
it('should preserve the attribute case in DebugNode.attributes', () => {
@Component({
selector: 'my-icon',
template: '',
standalone: false,
})
class Icon {
@Input() svgIcon: any = '';
}
@Component({
template: `<my-icon svgIcon="test"></my-icon>`,
standalone: false,
})
class App {}
TestBed.configureTestingModule({declarations: [App, Icon]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const element = fixture.debugElement.children[0];
// Assert that the camel-case attribute is correct.
expect(element.attributes['svgIcon']).toBe('test');
// Make sure that we somehow didn't preserve the native lower-cased value.
expect(element.attributes['svgicon']).toBeFalsy();
});
it('should include namespaced attributes in DebugNode.attributes', () => {
@Component({
template: `<div xlink:href="foo"></div>`,
standalone: false,
})
class Comp {}
TestBed.configureTestingModule({declarations: [Comp]});
const fixture = TestBed.createComponent(Comp);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('div')).attributes['xlink:href']).toBe('foo');
});
it('should include attributes added via Renderer2 in DebugNode.attributes', () => {
@Component({
template: '<div></div>',
standalone: false,
})
class Comp {
constructor(public renderer: Renderer2) {}
}
TestBed.configureTestingModule({declarations: [Comp]});
const fixture = TestBed.createComponent(Comp);
const div = fixture.debugElement.query(By.css('div'));
fixture.componentInstance.renderer.setAttribute(div.nativeElement, 'foo', 'bar');
expect(div.attributes['foo']).toBe('bar');
});
| {
"end_byte": 41632,
"start_byte": 32652,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/debug/debug_node_spec.ts_41636_44756 | t('should clear event listeners when node is destroyed', () => {
let calls = 0;
@Component({
selector: 'cancel-button',
template: '',
standalone: false,
})
class CancelButton {
@Output() cancel = new EventEmitter<void>();
}
@Component({
template: '<cancel-button *ngIf="visible" (cancel)="cancel()"></cancel-button>',
standalone: false,
})
class App {
visible = true;
cancel() {
calls++;
}
}
TestBed.configureTestingModule({declarations: [App, CancelButton]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const button = fixture.debugElement.query(By.directive(CancelButton));
button.triggerEventHandler('cancel', {});
expect(calls).toBe(1, 'Expected calls to be 1 after one event.');
fixture.componentInstance.visible = false;
fixture.detectChanges();
button.triggerEventHandler('cancel', {});
expect(calls).toBe(1, 'Expected calls to stay 1 after destroying the node.');
});
it('should not error when accessing node name', () => {
@Component({
template: '',
standalone: false,
})
class EmptyComponent {}
const fixture = TestBed.configureTestingModule({
declarations: [EmptyComponent],
}).createComponent(EmptyComponent);
let node = fixture.debugElement;
let superParentName = '';
// Traverse upwards, all the way to #document, which is not a
// Node.ELEMENT_NODE
while (node) {
superParentName = node.name;
node = node.parent!;
}
expect(superParentName).not.toEqual('');
});
it('should match node name with declared casing', () => {
@Component({
template: `<div></div><myComponent></myComponent>`,
standalone: false,
})
class Wrapper {}
@Component({
selector: 'myComponent',
template: '',
standalone: false,
})
class MyComponent {}
const fixture = TestBed.configureTestingModule({
declarations: [Wrapper, MyComponent],
}).createComponent(Wrapper);
expect(fixture.debugElement.query((e) => e.name === 'myComponent')).toBeTruthy();
expect(fixture.debugElement.query((e) => e.name === 'div')).toBeTruthy();
});
it('does not call event listeners added outside angular context', () => {
let listenerCalled = false;
const eventToTrigger = createMouseEvent('mouseenter');
function listener() {
listenerCalled = true;
}
@Component({
template: '',
standalone: false,
})
class MyComp {
constructor(
private readonly zone: NgZone,
private readonly element: ElementRef,
) {}
ngOnInit() {
this.zone.runOutsideAngular(() => {
this.element.nativeElement.addEventListener('mouseenter', listener);
});
}
}
const fixture = TestBed.configureTestingModule({declarations: [MyComp]}).createComponent(
MyComp,
);
fixture.detectChanges();
fixture.debugElement.triggerEventHandler('mouseenter', eventToTrigger);
expect(listenerCalled).toBe(false);
});
});
| {
"end_byte": 44756,
"start_byte": 41636,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/debug/debug_node_spec.ts"
} |
angular/packages/core/test/reflection/es2015_inheritance_fixture.ts_0_595 | /**
* @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
*/
// AMD module name is required so that this file can be loaded in the Karma tests.
/// <amd-module name="angular/packages/core/test/reflection/es5_downleveled_inheritance_fixture" />
class Parent {}
export class ChildNoCtor extends Parent {}
export class ChildWithCtor extends Parent {
constructor() {
super();
}
}
export class ChildNoCtorPrivateProps extends Parent {
x = 10;
}
| {
"end_byte": 595,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/test/reflection/es2015_inheritance_fixture.ts"
} |
angular/packages/core/reference-manifests/README.md_0_137 | # Manual API manifests
This directory contains handwritten JSON entries that are aggregated into Angular's
API documentation manifest.
| {
"end_byte": 137,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/reference-manifests/README.md"
} |
angular/packages/core/reference-manifests/BUILD.bazel_0_118 | filegroup(
name = "reference-manifests",
srcs = glob(["*.json"]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/reference-manifests/BUILD.bazel"
} |
angular/packages/core/primitives/signals/README.md_0_7977 | # Angular Signals Implementation
This directory contains the code which powers Angular's reactive primitive, an implementation of the "signal" concept. A signal is a value which is "reactive", meaning it can notify interested consumers when it changes. There are many different implementations of this concept, with different designs for how these notifications are subscribed to and propagated, how cleanup/unsubscription works, how dependencies are tracked, etc. This document describes the algorithm behind our specific implementation of the signal pattern.
## Conceptual surface
Angular Signals are zero-argument functions (`() => T`). When executed, they return the current value of the signal. Executing signals does not trigger side effects, though it may lazily recompute intermediate values (lazy memoization).
Particular contexts (such as template expressions) can be _reactive_. In such contexts, executing a signal will return the value, but also register the signal as a dependency of the context in question. The context's owner will then be notified if any of its signal dependencies produces a new value (usually, this results in the re-execution of those expressions to consume the new values).
This context and getter function mechanism allows for signal dependencies of a context to be tracked _automatically_ and _implicitly_. Users do not need to declare arrays of dependencies, nor does the set of dependencies of a particular context need to remain static across executions.
### Source signals
### Writable signals: `signal()`
The `createSignal()` function produces a specific type of signal that tracks a stored value. In addition to providing a getter function, these signals can be wired up with additional APIs for changing the value of the signal (along with notifying any dependents of the change). These include the `.set` operation for replacing the signal value, and `.update` for deriving a new value. In Angular, these are exposed as functions on the signal getter itself. For example:
```typescript
const counter = signal(0);
counter.set(2);
counter.update(count => count + 1);
```
#### Equality
The signal creation function one can, optionally, specify an equality comparator function. The comparator is used to decide whether the new supplied value is the same, or different, as compared to the current signal’s value.
If the equality function determines that 2 values are equal it will:
* block update of signal’s value;
* skip change propagation.
### Declarative derived values
`createComputed()` creates a memoizing signal, which calculates its value from the values of some number of input signals. In Angular this is wrapped into the `computed` constructor:
```typescript
const counter = signal(0);
// Automatically updates when `counter` changes:
const isEven = computed(() => counter() % 2 === 0);
```
Because the calculation function used to create the `computed` is executed in a reactive context, any signals read by that calculation will be tracked as dependencies, and the value of the computed signal recalculated whenever any of those dependencies changes.
Similarly to signals, the `computed` can (optionally) specify an equality comparator function.
### Side effects: `createWatch()`
The signals library provides an operation to watch a reactive function and receive notifications when the dependencies of that function change. This is used within Angular to build `effect()`.
`effect()` schedules and runs a side-effectful function inside a reactive context. Signal dependencies of this function are captured, and the side effect is re-executed whenever any of its dependencies produces a new value.
```typescript
const counter = signal(0);
effect(() => console.log('The counter is:', counter()));
// The counter is: 0
counter.set(1);
// The counter is: 1
```
Effects do not execute synchronously with the set (see the section on glitch-free execution below), but are scheduled and resolved by the framework. The exact timing of effects is unspecified.
## Producer and Consumer
Internally, the signals implementation is defined in terms of two abstractions, producers and consumers. Producers represents values which can deliver change notifications, such as the various flavors of `Signal`s. Consumers represents a reactive context which may depend on some number of producers. In other words, producers produce reactivity, and consumers consume it.
Implementers of either abstraction define a node object which implements the `ReactiveNode` interface, which models participation in the reactive graph. Any `ReactiveNode` can act in the role of a producer, a consumer, or both, by interacting with the appropriate subset of APIs. For example, `WritableSignal`s implement `ReactiveNode` but only operate against the producer APIs, since `WritableSignal`s don't consume other signal values.
Some concepts are both producers _and_ consumers. For example, derived `computed` expressions consume other signals to produce new reactive values.
Throughout the rest of this document, "producer" and "consumer" are used to describe `ReactiveNode`s acting in that capacity.
### The Dependency Graph
`ReactiveNode`s are linked together through a dependency graph. This dependency graph is bidirectional, but there are differences in which dependencies are tracked in each direction.
Consumers always keep track of the producers they depend on. Producers only track dependencies from consumers which are considered "live". A consumer is "live" when either:
* It sets the `consumerIsAlwaysLive` property of its `ReactiveNode` to `true`, or
* It's also a producer which is depended upon by a live consumer.
In that sense, "liveness" is a transitive property of consumers.
In practice, effects (including template pseudo-effects) are live consumers, which `computed`s are not inherently live. This means that any `computed` used in an `effect` will be treated as live, but a `computed` not read in any effects will not be.
#### Liveness and memory management
The concept of liveness allows for producer-to-consumer dependency tracking without risking memory leaks.
Consider this contrived case of a `signal` and a `computed`:
```typescript
const counter = signal(1);
let double = computed(() => counter() * 2);
console.log(double()); // 2
double = null;
```
If the dependency graph maintained a hard reference from `counter` to `double`, then `double` would be retained(not garbage collected) even though the user dropped their last reference to the actual signal. But because `double` is not live, the graph doesn't hold a reference from `counter` to `double`, and `double` can be freed when the user drops it.
#### Non-live consumers and polling
A consequence of not tracking an edge from `counter` to `double` is that when counter is changed:
```typescript
counter.set(2);
```
No notification can propagate in the graph from `counter` to `double`, to let the `computed` know that it needs to throw away its memoized value (2) and recompute (producing 4).
Instead, when `double()` is read, it polls its producers (which _are_ tracked in the graph) and checks whether any of them report having changed since the last time `double` was calculated. If not, it can safely use its memoized value.
#### With a live consumer
If an `effect` is created:
```typescript
effect(() => console.log(double()));
```
Then `double` becomes a live consumer, as it's a dependency of a live consumer (the effect), and the graph will have a hard reference from `counter` to `double` to the effect consumer. There is no risk of memory leaks though, since the effect is referencing `double` directly anyway, and the effect cannot just be dropped and must be manually destroyed (which would cause `double` to no longer be live). That is, there is no way for a reference from a producer to a live consumer to exist in the graph _without_ the consumer also referencing the producer outside of the graph.`
## " | {
"end_byte": 7977,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/README.md"
} |
angular/packages/core/primitives/signals/README.md_7977_14890 | Glitch Free" property
Consider the following setup:
```typescript
const counter = signal(0);
const evenOrOdd = computed(() => counter() % 2 === 0 ? 'even' : 'odd');
effect(() => console.log(counter() + ' is ' + evenOrOdd()));
counter.set(1);
```
When the effect is first created, it will print "0 is even", as expected, and record that both `counter` and `evenOrOdd` are dependencies of the logging effect.
When `counter` is set to `1`, this invalidates both `evenOrOdd` and the logging effect. If `counter.set()` iterated through the dependencies of `counter` and triggered the logging effect first, before notifying `evenOrOdd` of the change, however, we might observe the inconsistent logging statement "1 is even". Eventually `evenOrOdd` would be notified, which would trigger the logging effect again, logging the correct statement "1 is odd".
In this situation, the logging effect's observation of the inconsistent state "1 is even" is known as a _glitch_. A major goal of reactive system design is to prevent such intermediate states from ever being observed, and ensure _glitch-free execution_.
### Push/Pull Algorithm
Angular Signals guarantees glitch-free execution by separating updates to the `ReactiveNode` graph into two phases. The first phase is performed eagerly when a producer value is changed. This change notification is propagated through the graph, notifying live consumers which depend on the producer of the potential update. Some of these consumers may be derived values and thus also producers, which invalidate their cached values and then continue the propagation of the change notification to their own live consumers, and so on. Ultimately this notification reaches effects, which schedule themselves for re-execution.
Crucially, during this first phase, no side effects are run, and no recomputation of intermediate or derived values is performed, only invalidation of cached values. This allows the change notification to reach all affected nodes in the graph without the possibility of observing intermediate or glitchy states.
Once this change propagation has completed (synchronously), the second phase can begin. In this second phase, signal values may be read by the application or framework, triggering recomputation of any needed derived values which were previously invalidated.
We refer to this as the "push/pull" algorithm: "dirtiness" is eagerly _pushed_ through the graph when a source signal is changed, but recalculation is performed lazily, only when values are _pulled_ by reading their signals.
## Dynamic Dependency Tracking
When a reactive context operation (for example, an `effect`'s side effect function) is executed, the signals that it reads are tracked as dependencies. However, this may not be the same set of signals from one execution to the next. For example, this computed signal:
```typescript
const dynamic = computed(() => useA() ? dataA() : dataB());
```
reads either `dataA` or `dataB` depending on the value of the `useA` signal. At any given point, it will have a dependency set of either `[useA, dataA]` or `[useA, dataB]`, and it can never depend on `dataA` and `dataB` at the same time.
The potential dependencies of a reactive context are unbounded. Signals may be stored in variables or other data structures and swapped out with other signals from time to time. Thus, the signals implementation must deal with potential changes in the set of dependencies of a consumer on each execution.
Dependencies of a computation are tracked in an array. When the computation is rerun, a pointer into that array is initialized to the index `0`, and each dependency read is compared against the dependency from the previous run at the pointer's current location. If there's a mismatch, then the dependencies have changed since the last run, and the old dependency can be dropped and replaced with the new one. At the end of the run, any remaining unmatched dependencies can be dropped.
## Equality Semantics
Producers may lazily produce their value (such as a `computed` which only recalculates its value when pulled). However, a producer may also choose to apply an equality check to the values that it produces, and determine that the newly computed value is "equal" semantically to the previous. In this case, consumers which depend on that value should not be re-executed. For example, the following effect:
```typescript
const counter = signal(0);
const isEven = computed(() => counter() % 2 === 0);
effect(() => console.log(isEven() ? 'even!' : 'odd!'));
```
should run if `counter` is updated to `1` as the value of `isEven` switches from `true` to `false`. But if `counter` is then set to `3`, `isEven` will recompute the same value: `false`. Therefore the logging effect should not run.
This is a tricky property to guarantee in our implementation because values are not recomputed during the push phase of change propagation. `isEven` is invalidated when `counter` is changed, which causes the logging `effect` to also be invalidated and scheduled. Naively, `isEven` wouldn't be recomputed until the logging effect actually runs and attempts to read its value, which is too late to notice that it didn't need to run at all.
### Value Versioning
To solve this problem, our implementation uses a similar technique to tracking dependency staleness. Producers track a monotonically increasing `version`, representing the semantic identity of their value. `version` is incremented when the producer produces a semantically new value. The current `version` of each dependency (producer) is saved as part of the tracked dependencies of a consumer.
Before consumers trigger their reactive operations (e.g. the side effect function for `effect`s, or the recomputation for `computed`s), they poll their dependencies and ask for `version` to be refreshed if needed. For a `computed`, this will trigger recomputation of the value and the subsequent equality check, if the value is stale (which makes this polling a recursive process as the `computed` is also a consumer which will poll its own producers). If this recomputation produces a semantically changed value, `version` is incremented.
The consumer can then compare the `version` of the new value with its last read version to determine if that particular dependency really did change. By doing this for all producers the consumer can determine that, if all `version`s match, that no _actual_ change to any dependency has occurred, and it can skip reacting to that change (e.g. skip running the side effect function).
## `Watch` primitive
`Watch` is a primitive used to build different types of effects. `Watch`es are consumers that run side-effectful functions in their reactive context, but where the scheduling of the side effect is delegated to the implementor. The `Watch` will call this scheduling operation when it receives a notification that it's stale.
| {
"end_byte": 14890,
"start_byte": 7977,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/README.md"
} |
angular/packages/core/primitives/signals/BUILD.bazel_0_608 | load("//tools:defaults.bzl", "ts_library", "tsec_test")
package(default_visibility = [
"//packages:__pkg__",
"//packages/core:__subpackages__",
"//packages/rxjs-interop/test:__subpackages__",
"//tools/public_api_guard:__pkg__",
])
ts_library(
name = "signals",
srcs = glob(
[
"**/*.ts",
],
),
)
tsec_test(
name = "tsec_test",
target = "signals",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]),
visibility = ["//visibility:public"],
)
| {
"end_byte": 608,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/BUILD.bazel"
} |
angular/packages/core/primitives/signals/index.ts_0_1154 | /**
* @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 {ComputedNode, createComputed} from './src/computed';
export {ValueEqualityFn, defaultEquals} from './src/equality';
export {setThrowInvalidWriteToSignalError} from './src/errors';
export {
REACTIVE_NODE,
Reactive,
ReactiveNode,
SIGNAL,
consumerAfterComputation,
consumerBeforeComputation,
consumerDestroy,
consumerMarkDirty,
consumerPollProducersForChange,
getActiveConsumer,
isInNotificationPhase,
isReactive,
producerAccessed,
producerIncrementEpoch,
producerMarkClean,
producerNotifyConsumers,
producerUpdateValueVersion,
producerUpdatesAllowed,
setActiveConsumer,
} from './src/graph';
export {
SIGNAL_NODE,
SignalGetter,
SignalNode,
createSignal,
runPostSignalSetFn,
setPostSignalSetFn,
signalSetFn,
signalUpdateFn,
} from './src/signal';
export {Watch, WatchCleanupFn, WatchCleanupRegisterFn, createWatch} from './src/watch';
export {setAlternateWeakRefImpl} from './src/weak_ref';
| {
"end_byte": 1154,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/index.ts"
} |
angular/packages/core/primitives/signals/src/watch.ts_0_3915 | /**
* @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 {
consumerAfterComputation,
consumerBeforeComputation,
consumerDestroy,
consumerMarkDirty,
consumerPollProducersForChange,
isInNotificationPhase,
REACTIVE_NODE,
ReactiveNode,
SIGNAL,
} from './graph';
/**
* A cleanup function that can be optionally registered from the watch logic. If registered, the
* cleanup logic runs before the next watch execution.
*/
export type WatchCleanupFn = () => void;
/**
* A callback passed to the watch function that makes it possible to register cleanup logic.
*/
export type WatchCleanupRegisterFn = (cleanupFn: WatchCleanupFn) => void;
export interface Watch {
notify(): void;
/**
* Execute the reactive expression in the context of this `Watch` consumer.
*
* Should be called by the user scheduling algorithm when the provided
* `schedule` hook is called by `Watch`.
*/
run(): void;
cleanup(): void;
/**
* Destroy the watcher:
* - disconnect it from the reactive graph;
* - mark it as destroyed so subsequent run and notify operations are noop.
*/
destroy(): void;
[SIGNAL]: WatchNode;
}
export interface WatchNode extends ReactiveNode {
hasRun: boolean;
fn: ((onCleanup: WatchCleanupRegisterFn) => void) | null;
schedule: ((watch: Watch) => void) | null;
cleanupFn: WatchCleanupFn;
ref: Watch;
}
export function createWatch(
fn: (onCleanup: WatchCleanupRegisterFn) => void,
schedule: (watch: Watch) => void,
allowSignalWrites: boolean,
): Watch {
const node: WatchNode = Object.create(WATCH_NODE);
if (allowSignalWrites) {
node.consumerAllowSignalWrites = true;
}
node.fn = fn;
node.schedule = schedule;
const registerOnCleanup = (cleanupFn: WatchCleanupFn) => {
node.cleanupFn = cleanupFn;
};
function isWatchNodeDestroyed(node: WatchNode) {
return node.fn === null && node.schedule === null;
}
function destroyWatchNode(node: WatchNode) {
if (!isWatchNodeDestroyed(node)) {
consumerDestroy(node); // disconnect watcher from the reactive graph
node.cleanupFn();
// nullify references to the integration functions to mark node as destroyed
node.fn = null;
node.schedule = null;
node.cleanupFn = NOOP_CLEANUP_FN;
}
}
const run = () => {
if (node.fn === null) {
// trying to run a destroyed watch is noop
return;
}
if (isInNotificationPhase()) {
throw new Error(`Schedulers cannot synchronously execute watches while scheduling.`);
}
node.dirty = false;
if (node.hasRun && !consumerPollProducersForChange(node)) {
return;
}
node.hasRun = true;
const prevConsumer = consumerBeforeComputation(node);
try {
node.cleanupFn();
node.cleanupFn = NOOP_CLEANUP_FN;
node.fn(registerOnCleanup);
} finally {
consumerAfterComputation(node, prevConsumer);
}
};
node.ref = {
notify: () => consumerMarkDirty(node),
run,
cleanup: () => node.cleanupFn(),
destroy: () => destroyWatchNode(node),
[SIGNAL]: node,
};
return node.ref;
}
const NOOP_CLEANUP_FN: WatchCleanupFn = () => {};
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const WATCH_NODE: Partial<WatchNode> = /* @__PURE__ */ (() => {
return {
...REACTIVE_NODE,
consumerIsAlwaysLive: true,
consumerAllowSignalWrites: false,
consumerMarkedDirty: (node: WatchNode) => {
if (node.schedule !== null) {
node.schedule(node.ref);
}
},
hasRun: false,
cleanupFn: NOOP_CLEANUP_FN,
};
})();
| {
"end_byte": 3915,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/watch.ts"
} |
angular/packages/core/primitives/signals/src/errors.ts_0_535 | /**
* @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
*/
function defaultThrowError(): never {
throw new Error();
}
let throwInvalidWriteToSignalErrorFn = defaultThrowError;
export function throwInvalidWriteToSignalError() {
throwInvalidWriteToSignalErrorFn();
}
export function setThrowInvalidWriteToSignalError(fn: () => never): void {
throwInvalidWriteToSignalErrorFn = fn;
}
| {
"end_byte": 535,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/errors.ts"
} |
angular/packages/core/primitives/signals/src/equality.ts_0_524 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* A comparison function which can determine if two values are equal.
*/
export type ValueEqualityFn<T> = (a: T, b: T) => boolean;
/**
* The default equality function used for `signal` and `computed`, which uses referential equality.
*/
export function defaultEquals<T>(a: T, b: T) {
return Object.is(a, b);
}
| {
"end_byte": 524,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/equality.ts"
} |
angular/packages/core/primitives/signals/src/weak_ref.ts_0_295 | /**
* @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 function setAlternateWeakRefImpl(impl: unknown) {
// TODO: remove this function
}
| {
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/weak_ref.ts"
} |
angular/packages/core/primitives/signals/src/graph.ts_0_8652 | /**
* @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
*/
// Required as the signals library is in a separate package, so we need to explicitly ensure the
// global `ngDevMode` type is defined.
declare const ngDevMode: boolean | undefined;
/**
* The currently active consumer `ReactiveNode`, if running code in a reactive context.
*
* Change this via `setActiveConsumer`.
*/
let activeConsumer: ReactiveNode | null = null;
let inNotificationPhase = false;
type Version = number & {__brand: 'Version'};
/**
* Global epoch counter. Incremented whenever a source signal is set.
*/
let epoch: Version = 1 as Version;
/**
* Symbol used to tell `Signal`s apart from other functions.
*
* This can be used to auto-unwrap signals in various cases, or to auto-wrap non-signal values.
*/
export const SIGNAL = /* @__PURE__ */ Symbol('SIGNAL');
export function setActiveConsumer(consumer: ReactiveNode | null): ReactiveNode | null {
const prev = activeConsumer;
activeConsumer = consumer;
return prev;
}
export function getActiveConsumer(): ReactiveNode | null {
return activeConsumer;
}
export function isInNotificationPhase(): boolean {
return inNotificationPhase;
}
export interface Reactive {
[SIGNAL]: ReactiveNode;
}
export function isReactive(value: unknown): value is Reactive {
return (value as Partial<Reactive>)[SIGNAL] !== undefined;
}
export const REACTIVE_NODE: ReactiveNode = {
version: 0 as Version,
lastCleanEpoch: 0 as Version,
dirty: false,
producerNode: undefined,
producerLastReadVersion: undefined,
producerIndexOfThis: undefined,
nextProducerIndex: 0,
liveConsumerNode: undefined,
liveConsumerIndexOfThis: undefined,
consumerAllowSignalWrites: false,
consumerIsAlwaysLive: false,
producerMustRecompute: () => false,
producerRecomputeValue: () => {},
consumerMarkedDirty: () => {},
consumerOnSignalRead: () => {},
};
/**
* A producer and/or consumer which participates in the reactive graph.
*
* Producer `ReactiveNode`s which are accessed when a consumer `ReactiveNode` is the
* `activeConsumer` are tracked as dependencies of that consumer.
*
* Certain consumers are also tracked as "live" consumers and create edges in the other direction,
* from producer to consumer. These edges are used to propagate change notifications when a
* producer's value is updated.
*
* A `ReactiveNode` may be both a producer and consumer.
*/
export interface ReactiveNode {
/**
* Version of the value that this node produces.
*
* This is incremented whenever a new value is produced by this node which is not equal to the
* previous value (by whatever definition of equality is in use).
*/
version: Version;
/**
* Epoch at which this node is verified to be clean.
*
* This allows skipping of some polling operations in the case where no signals have been set
* since this node was last read.
*/
lastCleanEpoch: Version;
/**
* Whether this node (in its consumer capacity) is dirty.
*
* Only live consumers become dirty, when receiving a change notification from a dependency
* producer.
*/
dirty: boolean;
/**
* Producers which are dependencies of this consumer.
*
* Uses the same indices as the `producerLastReadVersion` and `producerIndexOfThis` arrays.
*/
producerNode: ReactiveNode[] | undefined;
/**
* `Version` of the value last read by a given producer.
*
* Uses the same indices as the `producerNode` and `producerIndexOfThis` arrays.
*/
producerLastReadVersion: Version[] | undefined;
/**
* Index of `this` (consumer) in each producer's `liveConsumers` array.
*
* This value is only meaningful if this node is live (`liveConsumers.length > 0`). Otherwise
* these indices are stale.
*
* Uses the same indices as the `producerNode` and `producerLastReadVersion` arrays.
*/
producerIndexOfThis: number[] | undefined;
/**
* Index into the producer arrays that the next dependency of this node as a consumer will use.
*
* This index is zeroed before this node as a consumer begins executing. When a producer is read,
* it gets inserted into the producers arrays at this index. There may be an existing dependency
* in this location which may or may not match the incoming producer, depending on whether the
* same producers were read in the same order as the last computation.
*/
nextProducerIndex: number;
/**
* Array of consumers of this producer that are "live" (they require push notifications).
*
* `liveConsumerNode.length` is effectively our reference count for this node.
*/
liveConsumerNode: ReactiveNode[] | undefined;
/**
* Index of `this` (producer) in each consumer's `producerNode` array.
*
* Uses the same indices as the `liveConsumerNode` array.
*/
liveConsumerIndexOfThis: number[] | undefined;
/**
* Whether writes to signals are allowed when this consumer is the `activeConsumer`.
*
* This is used to enforce guardrails such as preventing writes to writable signals in the
* computation function of computed signals, which is supposed to be pure.
*/
consumerAllowSignalWrites: boolean;
readonly consumerIsAlwaysLive: boolean;
/**
* Tracks whether producers need to recompute their value independently of the reactive graph (for
* example, if no initial value has been computed).
*/
producerMustRecompute(node: unknown): boolean;
producerRecomputeValue(node: unknown): void;
consumerMarkedDirty(node: unknown): void;
/**
* Called when a signal is read within this consumer.
*/
consumerOnSignalRead(node: unknown): void;
/**
* A debug name for the reactive node. Used in Angular DevTools to identify the node.
*/
debugName?: string;
}
interface ConsumerNode extends ReactiveNode {
producerNode: NonNullable<ReactiveNode['producerNode']>;
producerIndexOfThis: NonNullable<ReactiveNode['producerIndexOfThis']>;
producerLastReadVersion: NonNullable<ReactiveNode['producerLastReadVersion']>;
}
interface ProducerNode extends ReactiveNode {
liveConsumerNode: NonNullable<ReactiveNode['liveConsumerNode']>;
liveConsumerIndexOfThis: NonNullable<ReactiveNode['liveConsumerIndexOfThis']>;
}
/**
* Called by implementations when a producer's signal is read.
*/
export function producerAccessed(node: ReactiveNode): void {
if (inNotificationPhase) {
throw new Error(
typeof ngDevMode !== 'undefined' && ngDevMode
? `Assertion error: signal read during notification phase`
: '',
);
}
if (activeConsumer === null) {
// Accessed outside of a reactive context, so nothing to record.
return;
}
activeConsumer.consumerOnSignalRead(node);
// This producer is the `idx`th dependency of `activeConsumer`.
const idx = activeConsumer.nextProducerIndex++;
assertConsumerNode(activeConsumer);
if (idx < activeConsumer.producerNode.length && activeConsumer.producerNode[idx] !== node) {
// There's been a change in producers since the last execution of `activeConsumer`.
// `activeConsumer.producerNode[idx]` holds a stale dependency which will be be removed and
// replaced with `this`.
//
// If `activeConsumer` isn't live, then this is a no-op, since we can replace the producer in
// `activeConsumer.producerNode` directly. However, if `activeConsumer` is live, then we need
// to remove it from the stale producer's `liveConsumer`s.
if (consumerIsLive(activeConsumer)) {
const staleProducer = activeConsumer.producerNode[idx];
producerRemoveLiveConsumerAtIndex(staleProducer, activeConsumer.producerIndexOfThis[idx]);
// At this point, the only record of `staleProducer` is the reference at
// `activeConsumer.producerNode[idx]` which will be overwritten below.
}
}
if (activeConsumer.producerNode[idx] !== node) {
// We're a new dependency of the consumer (at `idx`).
activeConsumer.producerNode[idx] = node;
// If the active consumer is live, then add it as a live consumer. If not, then use 0 as a
// placeholder value.
activeConsumer.producerIndexOfThis[idx] = consumerIsLive(activeConsumer)
? producerAddLiveConsumer(node, activeConsumer, idx)
: 0;
}
activeConsumer.producerLastReadVersion[idx] = node.version;
}
/**
* Increment the global epoch counter.
*
* Called by source producers (that is, not computeds) whenever their values change.
*/
export function producerIncrementEpoch(): void {
epoch++;
} | {
"end_byte": 8652,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/graph.ts"
} |
angular/packages/core/primitives/signals/src/graph.ts_8654_17189 | /**
* Ensure this producer's `version` is up-to-date.
*/
export function producerUpdateValueVersion(node: ReactiveNode): void {
if (consumerIsLive(node) && !node.dirty) {
// A live consumer will be marked dirty by producers, so a clean state means that its version
// is guaranteed to be up-to-date.
return;
}
if (!node.dirty && node.lastCleanEpoch === epoch) {
// Even non-live consumers can skip polling if they previously found themselves to be clean at
// the current epoch, since their dependencies could not possibly have changed (such a change
// would've increased the epoch).
return;
}
if (!node.producerMustRecompute(node) && !consumerPollProducersForChange(node)) {
// None of our producers report a change since the last time they were read, so no
// recomputation of our value is necessary, and we can consider ourselves clean.
producerMarkClean(node);
return;
}
node.producerRecomputeValue(node);
// After recomputing the value, we're no longer dirty.
producerMarkClean(node);
}
/**
* Propagate a dirty notification to live consumers of this producer.
*/
export function producerNotifyConsumers(node: ReactiveNode): void {
if (node.liveConsumerNode === undefined) {
return;
}
// Prevent signal reads when we're updating the graph
const prev = inNotificationPhase;
inNotificationPhase = true;
try {
for (const consumer of node.liveConsumerNode) {
if (!consumer.dirty) {
consumerMarkDirty(consumer);
}
}
} finally {
inNotificationPhase = prev;
}
}
/**
* Whether this `ReactiveNode` in its producer capacity is currently allowed to initiate updates,
* based on the current consumer context.
*/
export function producerUpdatesAllowed(): boolean {
return activeConsumer?.consumerAllowSignalWrites !== false;
}
export function consumerMarkDirty(node: ReactiveNode): void {
node.dirty = true;
producerNotifyConsumers(node);
node.consumerMarkedDirty?.(node);
}
export function producerMarkClean(node: ReactiveNode): void {
node.dirty = false;
node.lastCleanEpoch = epoch;
}
/**
* Prepare this consumer to run a computation in its reactive context.
*
* Must be called by subclasses which represent reactive computations, before those computations
* begin.
*/
export function consumerBeforeComputation(node: ReactiveNode | null): ReactiveNode | null {
node && (node.nextProducerIndex = 0);
return setActiveConsumer(node);
}
/**
* Finalize this consumer's state after a reactive computation has run.
*
* Must be called by subclasses which represent reactive computations, after those computations
* have finished.
*/
export function consumerAfterComputation(
node: ReactiveNode | null,
prevConsumer: ReactiveNode | null,
): void {
setActiveConsumer(prevConsumer);
if (
!node ||
node.producerNode === undefined ||
node.producerIndexOfThis === undefined ||
node.producerLastReadVersion === undefined
) {
return;
}
if (consumerIsLive(node)) {
// For live consumers, we need to remove the producer -> consumer edge for any stale producers
// which weren't dependencies after the recomputation.
for (let i = node.nextProducerIndex; i < node.producerNode.length; i++) {
producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
}
}
// Truncate the producer tracking arrays.
// Perf note: this is essentially truncating the length to `node.nextProducerIndex`, but
// benchmarking has shown that individual pop operations are faster.
while (node.producerNode.length > node.nextProducerIndex) {
node.producerNode.pop();
node.producerLastReadVersion.pop();
node.producerIndexOfThis.pop();
}
}
/**
* Determine whether this consumer has any dependencies which have changed since the last time
* they were read.
*/
export function consumerPollProducersForChange(node: ReactiveNode): boolean {
assertConsumerNode(node);
// Poll producers for change.
for (let i = 0; i < node.producerNode.length; i++) {
const producer = node.producerNode[i];
const seenVersion = node.producerLastReadVersion[i];
// First check the versions. A mismatch means that the producer's value is known to have
// changed since the last time we read it.
if (seenVersion !== producer.version) {
return true;
}
// The producer's version is the same as the last time we read it, but it might itself be
// stale. Force the producer to recompute its version (calculating a new value if necessary).
producerUpdateValueVersion(producer);
// Now when we do this check, `producer.version` is guaranteed to be up to date, so if the
// versions still match then it has not changed since the last time we read it.
if (seenVersion !== producer.version) {
return true;
}
}
return false;
}
/**
* Disconnect this consumer from the graph.
*/
export function consumerDestroy(node: ReactiveNode): void {
assertConsumerNode(node);
if (consumerIsLive(node)) {
// Drop all connections from the graph to this node.
for (let i = 0; i < node.producerNode.length; i++) {
producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
}
}
// Truncate all the arrays to drop all connection from this node to the graph.
node.producerNode.length =
node.producerLastReadVersion.length =
node.producerIndexOfThis.length =
0;
if (node.liveConsumerNode) {
node.liveConsumerNode.length = node.liveConsumerIndexOfThis!.length = 0;
}
}
/**
* Add `consumer` as a live consumer of this node.
*
* Note that this operation is potentially transitive. If this node becomes live, then it becomes
* a live consumer of all of its current producers.
*/
function producerAddLiveConsumer(
node: ReactiveNode,
consumer: ReactiveNode,
indexOfThis: number,
): number {
assertProducerNode(node);
if (node.liveConsumerNode.length === 0 && isConsumerNode(node)) {
// When going from 0 to 1 live consumers, we become a live consumer to our producers.
for (let i = 0; i < node.producerNode.length; i++) {
node.producerIndexOfThis[i] = producerAddLiveConsumer(node.producerNode[i], node, i);
}
}
node.liveConsumerIndexOfThis.push(indexOfThis);
return node.liveConsumerNode.push(consumer) - 1;
}
/**
* Remove the live consumer at `idx`.
*/
function producerRemoveLiveConsumerAtIndex(node: ReactiveNode, idx: number): void {
assertProducerNode(node);
if (typeof ngDevMode !== 'undefined' && ngDevMode && idx >= node.liveConsumerNode.length) {
throw new Error(
`Assertion error: active consumer index ${idx} is out of bounds of ${node.liveConsumerNode.length} consumers)`,
);
}
if (node.liveConsumerNode.length === 1 && isConsumerNode(node)) {
// When removing the last live consumer, we will no longer be live. We need to remove
// ourselves from our producers' tracking (which may cause consumer-producers to lose
// liveness as well).
for (let i = 0; i < node.producerNode.length; i++) {
producerRemoveLiveConsumerAtIndex(node.producerNode[i], node.producerIndexOfThis[i]);
}
}
// Move the last value of `liveConsumers` into `idx`. Note that if there's only a single
// live consumer, this is a no-op.
const lastIdx = node.liveConsumerNode.length - 1;
node.liveConsumerNode[idx] = node.liveConsumerNode[lastIdx];
node.liveConsumerIndexOfThis[idx] = node.liveConsumerIndexOfThis[lastIdx];
// Truncate the array.
node.liveConsumerNode.length--;
node.liveConsumerIndexOfThis.length--;
// If the index is still valid, then we need to fix the index pointer from the producer to this
// consumer, and update it from `lastIdx` to `idx` (accounting for the move above).
if (idx < node.liveConsumerNode.length) {
const idxProducer = node.liveConsumerIndexOfThis[idx];
const consumer = node.liveConsumerNode[idx];
assertConsumerNode(consumer);
consumer.producerIndexOfThis[idxProducer] = idx;
}
}
function consumerIsLive(node: ReactiveNode): boolean {
return node.consumerIsAlwaysLive || (node?.liveConsumerNode?.length ?? 0) > 0;
}
function assertConsumerNode(node: ReactiveNode): asserts node is ConsumerNode {
node.producerNode ??= [];
node.producerIndexOfThis ??= [];
node.producerLastReadVersion ??= [];
}
function assertProducerNode(node: ReactiveNode): asserts node is ProducerNode {
node.liveConsumerNode ??= [];
node.liveConsumerIndexOfThis ??= [];
} | {
"end_byte": 17189,
"start_byte": 8654,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/graph.ts"
} |
angular/packages/core/primitives/signals/src/graph.ts_17191_17302 | function isConsumerNode(node: ReactiveNode): node is ConsumerNode {
return node.producerNode !== undefined;
} | {
"end_byte": 17302,
"start_byte": 17191,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/graph.ts"
} |
angular/packages/core/primitives/signals/src/signal.ts_0_3084 | /**
* @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 {defaultEquals, ValueEqualityFn} from './equality';
import {throwInvalidWriteToSignalError} from './errors';
import {
producerAccessed,
producerIncrementEpoch,
producerNotifyConsumers,
producerUpdatesAllowed,
REACTIVE_NODE,
ReactiveNode,
SIGNAL,
} from './graph';
// Required as the signals library is in a separate package, so we need to explicitly ensure the
// global `ngDevMode` type is defined.
declare const ngDevMode: boolean | undefined;
/**
* If set, called after `WritableSignal`s are updated.
*
* This hook can be used to achieve various effects, such as running effects synchronously as part
* of setting a signal.
*/
let postSignalSetFn: (() => void) | null = null;
export interface SignalNode<T> extends ReactiveNode {
value: T;
equal: ValueEqualityFn<T>;
}
export type SignalBaseGetter<T> = (() => T) & {readonly [SIGNAL]: unknown};
// Note: Closure *requires* this to be an `interface` and not a type, which is why the
// `SignalBaseGetter` type exists to provide the correct shape.
export interface SignalGetter<T> extends SignalBaseGetter<T> {
readonly [SIGNAL]: SignalNode<T>;
}
/**
* Create a `Signal` that can be set or updated directly.
*/
export function createSignal<T>(initialValue: T): SignalGetter<T> {
const node: SignalNode<T> = Object.create(SIGNAL_NODE);
node.value = initialValue;
const getter = (() => {
producerAccessed(node);
return node.value;
}) as SignalGetter<T>;
(getter as any)[SIGNAL] = node;
return getter;
}
export function setPostSignalSetFn(fn: (() => void) | null): (() => void) | null {
const prev = postSignalSetFn;
postSignalSetFn = fn;
return prev;
}
export function signalGetFn<T>(this: SignalNode<T>): T {
producerAccessed(this);
return this.value;
}
export function signalSetFn<T>(node: SignalNode<T>, newValue: T) {
if (!producerUpdatesAllowed()) {
throwInvalidWriteToSignalError();
}
if (!node.equal(node.value, newValue)) {
node.value = newValue;
signalValueChanged(node);
}
}
export function signalUpdateFn<T>(node: SignalNode<T>, updater: (value: T) => T): void {
if (!producerUpdatesAllowed()) {
throwInvalidWriteToSignalError();
}
signalSetFn(node, updater(node.value));
}
export function runPostSignalSetFn(): void {
postSignalSetFn?.();
}
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
export const SIGNAL_NODE: SignalNode<unknown> = /* @__PURE__ */ (() => {
return {
...REACTIVE_NODE,
equal: defaultEquals,
value: undefined,
};
})();
function signalValueChanged<T>(node: SignalNode<T>): void {
node.version++;
producerIncrementEpoch();
producerNotifyConsumers(node);
postSignalSetFn?.();
}
| {
"end_byte": 3084,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/signal.ts"
} |
angular/packages/core/primitives/signals/src/computed.ts_0_4305 | /**
* @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 {defaultEquals, ValueEqualityFn} from './equality';
import {
consumerAfterComputation,
consumerBeforeComputation,
producerAccessed,
producerUpdateValueVersion,
REACTIVE_NODE,
ReactiveNode,
SIGNAL,
} from './graph';
/**
* A computation, which derives a value from a declarative reactive expression.
*
* `Computed`s are both producers and consumers of reactivity.
*/
export interface ComputedNode<T> extends ReactiveNode {
/**
* Current value of the computation, or one of the sentinel values above (`UNSET`, `COMPUTING`,
* `ERROR`).
*/
value: T;
/**
* If `value` is `ERRORED`, the error caught from the last computation attempt which will
* be re-thrown.
*/
error: unknown;
/**
* The computation function which will produce a new value.
*/
computation: () => T;
equal: ValueEqualityFn<T>;
}
export type ComputedGetter<T> = (() => T) & {
[SIGNAL]: ComputedNode<T>;
};
/**
* Create a computed signal which derives a reactive value from an expression.
*/
export function createComputed<T>(computation: () => T): ComputedGetter<T> {
const node: ComputedNode<T> = Object.create(COMPUTED_NODE);
node.computation = computation;
const computed = () => {
// Check if the value needs updating before returning it.
producerUpdateValueVersion(node);
// Record that someone looked at this signal.
producerAccessed(node);
if (node.value === ERRORED) {
throw node.error;
}
return node.value;
};
(computed as ComputedGetter<T>)[SIGNAL] = node;
return computed as unknown as ComputedGetter<T>;
}
/**
* A dedicated symbol used before a computed value has been calculated for the first time.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const UNSET: any = /* @__PURE__ */ Symbol('UNSET');
/**
* A dedicated symbol used in place of a computed signal value to indicate that a given computation
* is in progress. Used to detect cycles in computation chains.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const COMPUTING: any = /* @__PURE__ */ Symbol('COMPUTING');
/**
* A dedicated symbol used in place of a computed signal value to indicate that a given computation
* failed. The thrown error is cached until the computation gets dirty again.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const ERRORED: any = /* @__PURE__ */ Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `COMPUTED_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const COMPUTED_NODE = /* @__PURE__ */ (() => {
return {
...REACTIVE_NODE,
value: UNSET,
dirty: true,
error: null,
equal: defaultEquals,
producerMustRecompute(node: ComputedNode<unknown>): boolean {
// Force a recomputation if there's no current value, or if the current value is in the
// process of being calculated (which should throw an error).
return node.value === UNSET || node.value === COMPUTING;
},
producerRecomputeValue(node: ComputedNode<unknown>): void {
if (node.value === COMPUTING) {
// Our computation somehow led to a cyclic read of itself.
throw new Error('Detected cycle in computations.');
}
const oldValue = node.value;
node.value = COMPUTING;
const prevConsumer = consumerBeforeComputation(node);
let newValue: unknown;
try {
newValue = node.computation();
} catch (err) {
newValue = ERRORED;
node.error = err;
} finally {
consumerAfterComputation(node, prevConsumer);
}
if (
oldValue !== UNSET &&
oldValue !== ERRORED &&
newValue !== ERRORED &&
node.equal(oldValue, newValue)
) {
// No change to `valueVersion` - old and new values are
// semantically equivalent.
node.value = oldValue;
return;
}
node.value = newValue;
node.version++;
},
};
})();
| {
"end_byte": 4305,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/signals/src/computed.ts"
} |
angular/packages/core/primitives/event-dispatch/contract_binary.ts_0_366 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {bootstrapAppScopedEarlyEventContract} from './src/bootstrap_app_scoped';
(window as any)['__jsaction_bootstrap'] = bootstrapAppScopedEarlyEventContract;
| {
"end_byte": 366,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/contract_binary.ts"
} |
angular/packages/core/primitives/event-dispatch/README.md_0_5479 | # JSAction
> [!CAUTION] This document serves as a technical documentation of an internal
> library used within Angular. This is **not** a public API that Angular
> provides, avoid using it directly in Angular applications.
JSAction is a tiny, low-level event delegation library that decouples the
registration of event listeners from the JavaScript code for the listeners
themselves. This enables capturing user interactions before the application is
bootstrapped or hydrated as well as very fine grained lazy loading of event
handling code. It is typically used as a sub-component of a larger framework,
rather than as a stand-alone library.
## How it works
The traditional way of adding an event listener is to obtain a reference to the
node and call `.addEventListener` (or use `.onclick`-like properties). However,
this necessarily requires that the code that handles the event has been loaded.
This can introduce a couple problems:
1. Server rendered applications will silently ignore user events that happen
before the app hydrates and registers handlers
```html
<!-- Let's say this server-rendered page is streamed to the browser -->
<body>
<button id="buy_btn" type="button">Buy now!</button>
...
<!--
There's a window of time between when the button is rendered and the
script below reaches the client, either because there's a lot of content
streamed in-between, network lag, or the script is asynchronously loaded
via a follow-up network request rather than as part of the main document
content.
->
...
<script>
const btn = document.querySelector('#buy_btn');
// Until this line is executed, clicking on the button doesn't do
// anything. This can be a frustrating user experience.
btn.addEventListener('click', () => app.confirmPurchase());
</script>
```
2. Applications must eagerly load any possible handler that could be needed to
handle user interactions, even if that handler is never invoked or even
rendered on the page
```html
// This button is rarely clicked, but the code to show the dialog must be
// loaded for every user
<button type="button" (click)="showAdvancedOptionsDialog()">
Advanced options
</button>
// Non-admins will never see this button, and yet they still have to load
// this handler.
@if (isAdmin) {
<button type="button" (click)="showAdminOptionsDialog()">
Admin options
</button>
}
```
It's possible to write these handlers so that they will late-load their
inner logic, but that's a manual, opt-in solution.
Instead, JSAction "registers" event handlers by storing a map from event type
to handler name (which can map to whatever handler function or behavior the
application needs) on a custom HTML `jsaction` attribute.
```html
<button id="buy_btn" type="button" jsaction="click:confirmPurchase">
Buy now!
</button>
```
A small inline script is added before any application content which registers
global event handlers for event types that could be delegated. Any events
triggered on the page bubble up to the global handler and are queued until the
application has bootstrapped or hydrated.
Once ready, JSAction can "replay" the queued events to the application,
providing the events and their matched handler name. It's up to the user of
JSAction what to do with the replayed events. The handler name could be mapped
to some eagerly loaded handlers and called right away, or it could be used to
lazily load a handler. (Typically JSAction is not used directly, but configured
by a framework like Angular or Wiz).
Frameworks may continue using JSAction after hydration to take advantage of its
event delegation. This allows handling most if not all events in your
application with just a few global listeners, saving the cost of registering
a larger amount (potentially thousands) of listeners on individual elements.
### `jsaction` attribute syntax
The value of the `jsaction` attribute encodes a mapping from event type to
handler name. The grammar for its syntax in [EBNF
format](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) is as
follows:
```ebnf
; JSAction attribute syntax in ENBF format
jsaction-attr-value = binding, { ";", jsaction-attr-value }
binding = [ event-type, ":" ], event-handler
event-type = { white space characters }, [valid-name], { white space characters }
event-handler = { white space characters }, [valid-name], { white space characters }
valid-name = { valid-char }
valid-char = character - invalid-name-chars
invalid-name-chars = ":" | ";" | "."
```
- Omitting the event type and colon will default the binding to the `click`
event (e.g.`jsaction="handleClick;hover:handleHover"`)
- Both the event type and handler name can be the empty string (but make sure
to keep the colon: `jsaction="change:;"`)
- The `event-handler` is an arbitrary string that can store metadata needed to
find the handler that handles the event. The user of JSAction can choose to
define the semantics of the handler string however they like.
#### Example
```html
<div jsaction="click:handleClick;hover:handleHover"></div>
```
In this example, there are two event bindings:
1. The `click` event is bound to the handler name `handleClick`
2. The `hover` event is bound to the handler name `handleHover`
| {
"end_byte": 5479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/README.md"
} |
angular/packages/core/primitives/event-dispatch/README.md_5479_10852 | ## Setup
### 1. Create the `EventContract`
First, we need to set up the `EventContract`, which installs the global handlers
for JSAction. The contract can be configured as follows:
```javascript
import {EventContract} from '@angular/core/primitives/event-dispatch/src/eventcontract';
import {EventContractContainer} from '@angular/core/primitives/event-dispatch/src/event_contract_container';
/**
* The list of event types that you want JSAction to listen for. In Angular,
* this is dynamically generated at server render time.
*/
const EVENTS_TO_LISTEN_TO = ['click', 'keydown', ...];
// Events will be handled by JSAction for all elements under this container
const eventContract = new EventContract(
new EventContractContainer(document.body));
for (const eventType of EVENTS_TO_LISTEN_TO) {
eventContract.addEvent(eventType);
}
// Stash the contract somewhere the main application bundle can access.
window['__ec'] = eventContract;
```
This code should be compiled/bundled/minified separately from the main
application bundle. Code size is critical here since this code will be inlined
at the top of the page and will block rendering content.
For scroll-blocking events like `touchstart`, `touchmove`, `wheel` and `mousewheel`,
you can optimize scrolling performance by passing the `passive` option to the
`addEvent` function. This allows the browser to continue scrolling smoothly even
while the event listener is processing. For example:
```javascript
eventContract.addEvent(eventType, prefixedEventType, /* passive= */ true);
```
### 2. Embed the `EventContract`
In your server rendered application, embed the contract bundle at the top of
your `<body>`, before any other content is rendered. Make sure that the bundle
is inlined in a `<script>` tag rather than loaded from a URL, since inlined
scripts will block rendering and prevent showing content before JSAction is
installed.
```html
<body>
<script type="text/javascript">
<!-- inline bundled code from above here -->
</script>
<!-- ...page content here... -->
</body>
```
### 3. Bind to events with `jsaction` attributes
Add a `jsaction` attribute for every handler in your application that you want
to register with JSAction. If you're embedding JSAction into a framework, you
would probably update your event handling APIs to automatically render these
attributes for your users.
```html
<button type="button" jsaction="click:handleClick">Buy now!</button>
```
### 4. Register your application with JSAction
Finally, once your application is bootstrapped and ready to handle events,
you'll need to create a `Dispatcher` and register it with the `EventContract`
that has been queueing events.
```javascript
import {Dispatcher, registerDispatcher} from '@angular/core/primitives/event-dispatch';
function handleEvent(eventInfoWrapper) {
// eventInfoWrapper contains all the information about the event
const eventType = eventInfoWrapper.getEventType();
const handlerName = eventInfoWrapper.getAction().name;
const event = eventInfoWrapper.getEvent();
// Your application or framework must now decide how to get and call the
// appropriate handler.
myApp.runHandler(eventType, handlerName, event);
}
function eventReplayer(eventInfoWrappers) {
// The dispatcher uses a separate callback for replaying events to allow
// control over how the events are replayed. Here we simply handle them like
// any other event.
for (const eventInfoWrapper of eventInfoWrappers) {
handleEvent(eventInfoWrapper);
}
}
// Get the contract that we stashed in the other bundle.
const eventContract = window['__ec'];
const dispatcher = new Dispatcher(handleEvent, {eventReplayer});
// This will replay any queued events and call handleEvent for each one of them.
registerDispatcher(eventContract, dispatcher);
```
Now the application is set up to handle events through JSAction! What the
application does to handle the dispatched events is up to you. It can be as
simple as calling methods in a map keyed by handler name, or as complicated as a
dynamic lazy loading system to load a handler based on the handler name.
### 5. [optional] Cleanup event contract
Optionally, you can clean up and remove the event contract from the app if you
plan to replace all jsaction attributes with native event handlers. There are
some tradeoffs to doing this:
Pros of cleaning up event contract:
- Native handlers avoid the [quirks](#known-caveats) of JSAction dispatching
Pros of keeping event contract:
- JSAction's event delegation drastically reduces the number of event
listeners registered with the browser. In extreme cases, registering
thousands of listeners in your app can be noticably slow.
- There may be slight behavior differences when your event is dispatched via
JSAction vs native event listeners. Always using JSAction dispatch keeps
things consistent.
<!-- end list -->
```javascript
window['__ec'].cleanUp();
```
## Known caveats
Because JSAction may potentially replay queued events some time after the events
originally fired, certain APIs like `e.preventDefault()` or
`e.stopPropagation()` won't function correctly.
<!-- TODO: Add a comprehensive list of known behavior differences for both replayed and delegated events. There are also plans to emulate some browser behavior (i.e. stopPropagation) that may fix some of these. -->
| {
"end_byte": 10852,
"start_byte": 5479,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/README.md"
} |
angular/packages/core/primitives/event-dispatch/BUILD.bazel_0_977 | load("//tools:defaults.bzl", "esbuild", "ts_library", "tsec_test")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "event-dispatch",
srcs = glob(
[
"**/*.ts",
],
),
module_name = "@angular/core/primitives/event-dispatch",
deps = [
"//packages/core/src/util", # Implicit dependency on ngDevMode
],
)
tsec_test(
name = "tsec_test",
target = "event-dispatch",
tsconfig = "//packages:tsec_config",
)
filegroup(
name = "files_for_docgen",
srcs = glob([
"*.ts",
"src/**/*.ts",
]),
visibility = ["//visibility:public"],
)
esbuild(
name = "contract_bundle_min",
args = {
"sourcemap": False,
"resolveExtensions": [
".mjs",
],
"legalComments": "none",
},
entry_point = ":contract_binary.ts",
format = "iife",
minify = True,
sourcemap = "inline",
deps = [":event-dispatch"],
)
| {
"end_byte": 977,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/BUILD.bazel"
} |
angular/packages/core/primitives/event-dispatch/index.ts_0_934 | /**
* @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 {Attribute} from './src/attribute';
export {getDefaulted as getActionCache} from './src/cache';
export type {EarlyJsactionDataContainer} from './src/earlyeventcontract';
export {EventContractContainer} from './src/event_contract_container';
export {EventDispatcher, EventPhase, registerDispatcher} from './src/event_dispatcher';
export {EventInfoWrapper} from './src/event_info';
export {isEarlyEventType, isCaptureEventType} from './src/event_type';
export {EventContract} from './src/eventcontract';
export {
bootstrapAppScopedEarlyEventContract,
clearAppScopedEarlyEventContract,
getAppScopedQueuedEventInfos,
registerAppScopedDispatcher,
removeAllAppScopedEventListeners,
} from './src/bootstrap_app_scoped';
| {
"end_byte": 934,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/index.ts"
} |
angular/packages/core/primitives/event-dispatch/test/eventcontract_test.ts_0_4458 | /**
* @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 {
EarlyEventContract,
EarlyJsactionData,
EarlyJsactionDataContainer,
} from '../src/earlyeventcontract';
import {
EventContractContainer,
EventContractContainerManager,
} from '../src/event_contract_container';
import {EventContractMultiContainer} from '../src/event_contract_multi_container';
import {EventInfoWrapper} from '../src/event_info';
import {EventType} from '../src/event_type';
import {Dispatcher, EventContract} from '../src/eventcontract';
import {Restriction} from '../src/restriction';
import {safeElement, testonlyHtml} from './html';
declare global {
interface Window extends EarlyJsactionDataContainer {}
}
const domContent = `
<div id="container"></div>
<div id="container2">
</div>
<div id="click-container">
<div id="click-action-element" jsaction="handleClick">
<div id="click-target-element"></div>
</div>
</div>
<div id="animationend-container">
<div id="animationend-action-element" jsaction="animationend:handleAnimationEnd">
<div id="animationend-target-element"></div>
</div>
</div>
<div id="anchor-click-container">
<a id="anchor-click-action-element" href="javascript:void(0);" jsaction="handleClick">
<span id="anchor-click-target-element"></span>
</a>
</div>
<div id="nested-outer-container">
<div id="nested-outer-action-element" jsaction="outerHandleClick">
<div id="nested-outer-target-element">
<div id="nested-inner-container">
<div id="nested-inner-action-element" jsaction="innerHandleClick">
<div id="nested-inner-target-element"></div>
</div>
</div>
</div>
</div>
</div>
<div id="mouseleave-container">
<div id="mouseleave-action-element" jsaction="mouseleave:handleMouseLeave">
<div id="mouseleave-target-element"></div>
</div>
</div>
<div id="focus-container">
<div id="focus-action-element" jsaction="focus:handleFocus">
<button id="focus-target-element">Focus Button</button>
</div>
</div>
`;
function getRequiredElementById(id: string) {
const element = document.getElementById(id);
expect(element).not.toBeNull();
return element!;
}
function createEventContractMultiContainer(
container: Element,
{stopPropagation = false}: {stopPropagation?: boolean} = {},
) {
const eventContractContainerManager = new EventContractMultiContainer(stopPropagation);
eventContractContainerManager.addContainer(container);
return eventContractContainerManager;
}
function createEventContract({
eventContractContainerManager,
eventTypes,
dispatcher,
}: {
eventContractContainerManager: EventContractContainerManager;
eventTypes: Array<string | [string, string]>;
dispatcher?: jasmine.Spy<Dispatcher>;
}): EventContract {
const eventContract = new EventContract(eventContractContainerManager);
for (const eventType of eventTypes) {
if (typeof eventType === 'string') {
eventContract.addEvent(eventType);
} else {
const [aliasedEventType, aliasEventType] = eventType;
eventContract.addEvent(aliasedEventType, aliasEventType);
}
}
if (dispatcher) {
eventContract.registerDispatcher(dispatcher, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
}
return eventContract;
}
function createDispatcherSpy() {
return jasmine.createSpy<Dispatcher>('dispatcher');
}
function getLastDispatchedEventInfoWrapper(dispatcher: jasmine.Spy<Dispatcher>): EventInfoWrapper {
return new EventInfoWrapper(dispatcher.calls.mostRecent().args[0]);
}
function dispatchMouseEvent(
target: Element,
{
type = 'click',
ctrlKey = false,
altKey = false,
shiftKey = false,
metaKey = false,
relatedTarget = null,
}: {
type?: string;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
metaKey?: boolean;
relatedTarget?: Element | null;
} = {},
) {
// createEvent/initMouseEvent is used to support IE11
// tslint:disable:deprecation
const event = document.createEvent('MouseEvent');
event.initMouseEvent(
type,
true,
true,
window,
0,
0,
0,
0,
0,
ctrlKey,
altKey,
shiftKey,
metaKey,
0,
relatedTarget,
);
// tslint:enable:deprecation
spyOn(event, 'preventDefault').and.callThrough();
target.dispatchEvent(event);
return event;
} | {
"end_byte": 4458,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/eventcontract_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/eventcontract_test.ts_4460_13645 | describe('EventContract', () => {
beforeEach(() => {
safeElement.setInnerHtml(document.body, testonlyHtml(domContent));
EventContract.MOUSE_SPECIAL_SUPPORT = false;
// Normalize timestamp.
spyOn(Date, 'now').and.returnValue(0);
});
it('adds event listener after adding container', () => {
const container = getRequiredElementById('container');
const container2 = getRequiredElementById('container2');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const addEventListenerSpy2 = spyOn(container2, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContract.addEvent('click');
expect(addEventListenerSpy).not.toHaveBeenCalled();
eventContractContainerManager.addContainer(container);
eventContractContainerManager.addContainer(container2);
const registeredEventTypes = addEventListenerSpy.calls
.allArgs()
.map(([eventType]) => eventType);
expect(registeredEventTypes).toEqual(['click']);
const registeredEventTypes2 = addEventListenerSpy2.calls
.allArgs()
.map(([eventType]) => eventType);
expect(registeredEventTypes2).toEqual(['click']);
});
it('adds event listener to added containers', () => {
const container = getRequiredElementById('container');
const container2 = getRequiredElementById('container2');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const addEventListenerSpy2 = spyOn(container2, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContractContainerManager.addContainer(container);
eventContractContainerManager.addContainer(container2);
expect(addEventListenerSpy).not.toHaveBeenCalled();
expect(addEventListenerSpy2).not.toHaveBeenCalled();
eventContract.addEvent('click');
const registeredEventTypes = addEventListenerSpy.calls
.allArgs()
.map(([eventType]) => eventType);
expect(registeredEventTypes).toEqual(['click']);
const registeredEventTypes2 = addEventListenerSpy2.calls
.allArgs()
.map(([eventType]) => eventType);
expect(registeredEventTypes2).toEqual(['click']);
});
it('adds event listener for aliased event', () => {
const container = getRequiredElementById('container');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContract.addEvent('animationend', 'webkitanimationend');
eventContractContainerManager.addContainer(container);
const registeredEventTypes = addEventListenerSpy.calls
.allArgs()
.map(([eventType]) => eventType);
expect(registeredEventTypes).toEqual(['webkitanimationend']);
});
it('adds event listener without passive option', () => {
const container = getRequiredElementById('container');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContract.addEvent('touchstart');
eventContractContainerManager.addContainer(container);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith(
'touchstart',
jasmine.any(Function),
false,
);
});
it('adds event listener for passive:false event', () => {
const container = getRequiredElementById('container');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContract.addEvent('touchstart', '', false);
eventContractContainerManager.addContainer(container);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', jasmine.any(Function), {
capture: false,
passive: false,
});
});
it('adds event listener for passive:true event', () => {
const container = getRequiredElementById('container');
const addEventListenerSpy = spyOn(container, 'addEventListener');
const eventContractContainerManager = new EventContractMultiContainer();
const eventContract = createEventContract({eventContractContainerManager, eventTypes: []});
eventContract.addEvent('touchstart', '', true);
eventContractContainerManager.addContainer(container);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', jasmine.any(Function), {
capture: false,
passive: true,
});
});
it('queues events until dispatcher is registered', () => {
const container = getRequiredElementById('click-container');
const targetElement = getRequiredElementById('click-target-element');
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
});
const clickEvent = dispatchMouseEvent(targetElement);
const dispatcher = createDispatcherSpy();
eventContract.registerDispatcher(dispatcher, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
expect(dispatcher).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe(EventType.CLICK);
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(eventInfoWrapper.getIsReplay()).toBe(true);
});
it('dispatches event', () => {
const container = getRequiredElementById('click-container');
const targetElement = getRequiredElementById('click-target-element');
const dispatcher = createDispatcherSpy();
createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
dispatcher,
});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe(EventType.CLICK);
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('dispatches event for `webkitanimationend` alias event type', () => {
if (!window.onwebkitanimationend) {
// Only test this in browsers that have support for it.
return;
}
const container = getRequiredElementById('animationend-container');
const targetElement = getRequiredElementById('animationend-target-element');
const dispatcher = createDispatcherSpy();
createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: [['animationend', 'webkitanimationend']],
dispatcher,
});
// createEvent/initEvent is used to support IE11
// tslint:disable:deprecation
const animationEndEvent = document.createEvent('AnimationEvent');
animationEndEvent.initEvent('webkitanimationend', true, true);
// tslint:enable:deprecation
targetElement.dispatchEvent(animationEndEvent);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('animationend');
expect(eventInfoWrapper.getEvent()).toBe(animationEndEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('cleanUp removes all event listeners and containers', () => {
const container = getRequiredElementById('click-container');
const removeEventListenerSpy = spyOn(container, 'removeEventListener').and.callThrough();
const actionElement = getRequiredElementById('click-action-element');
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = new EventContractContainer(container);
const cleanUpSpy = spyOn(eventContractContainerManager, 'cleanUp').and.callThrough();
const eventContract = createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
eventContract.cleanUp();
// Should not add the click listener back.
eventContract.addEvent('click');
actionElement.click();
expect(dispatcher).toHaveBeenCalledTimes(0);
expect(eventContract.handler('click')).toBeUndefined();
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(cleanUpSpy).toHaveBeenCalledTimes(1);
}); | {
"end_byte": 13645,
"start_byte": 4460,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/eventcontract_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/eventcontract_test.ts_13649_22245 | it('exposes event handlers with `handler()`', () => {
const container = getRequiredElementById('click-container');
const targetElement = getRequiredElementById('click-target-element');
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
dispatcher,
});
const clickEvent = dispatchMouseEvent(targetElement);
// Clear normal dispatcher calls.
dispatcher.calls.reset();
const clickHandler = eventContract.handler(EventType.CLICK)!;
expect(clickHandler).toBeDefined();
clickHandler('click', clickEvent, container);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe(EventType.CLICK);
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('has no event handlers with `handler()` for unregistered event type', () => {
const container = getRequiredElementById('click-container');
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: [],
});
expect(eventContract.handler(EventType.CLICK)).toBeUndefined();
});
it('does not prevent default for click on anchor without dispatcher', () => {
const container = getRequiredElementById('anchor-click-container');
const targetElement = getRequiredElementById('anchor-click-target-element');
createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
});
const clickEvent = dispatchMouseEvent(targetElement);
expect(clickEvent.preventDefault).not.toHaveBeenCalled();
});
describe('nested containers', () => {
let outerContainer: Element;
let outerTargetElement: Element;
let innerContainer: Element;
let innerTargetElement: Element;
beforeEach(() => {
outerContainer = getRequiredElementById('nested-outer-container');
outerTargetElement = getRequiredElementById('nested-outer-target-element');
innerContainer = getRequiredElementById('nested-inner-container');
innerTargetElement = getRequiredElementById('nested-inner-target-element');
});
it('dispatches events in outer container', () => {
const documentListener = jasmine.createSpy('documentListener');
window.document.documentElement.addEventListener('click', documentListener);
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = createEventContractMultiContainer(outerContainer);
createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
eventContractContainerManager.addContainer(innerContainer);
const clickEvent = dispatchMouseEvent(outerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(outerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
});
it('dispatches events in inner container', () => {
const documentListener = jasmine.createSpy('documentListener');
window.document.documentElement.addEventListener('click', documentListener);
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = createEventContractMultiContainer(outerContainer);
createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
eventContractContainerManager.addContainer(innerContainer);
const clickEvent = dispatchMouseEvent(innerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(innerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
});
it('dispatches events in outer container, inner registered first', () => {
const documentListener = jasmine.createSpy('documentListener');
window.document.documentElement.addEventListener('click', documentListener);
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = createEventContractMultiContainer(innerContainer);
createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
eventContractContainerManager.addContainer(outerContainer);
const clickEvent = dispatchMouseEvent(outerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(outerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
});
it('dispatches events in inner container, inner container registered first', () => {
const documentListener = jasmine.createSpy('documentListener');
window.document.documentElement.addEventListener('click', documentListener);
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = createEventContractMultiContainer(innerContainer);
createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
eventContractContainerManager.addContainer(outerContainer);
const clickEvent = dispatchMouseEvent(innerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(innerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
});
it('dispatches events in inner container, inner container removed', () => {
const documentListener = jasmine.createSpy('documentListener');
window.document.documentElement.addEventListener('click', documentListener);
const dispatcher = createDispatcherSpy();
const eventContractContainerManager = createEventContractMultiContainer(outerContainer);
createEventContract({
eventContractContainerManager,
eventTypes: ['click'],
dispatcher,
});
const innerEventContractContainer =
eventContractContainerManager.addContainer(innerContainer);
let clickEvent = dispatchMouseEvent(innerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
let eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(innerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
dispatcher.calls.reset();
documentListener.calls.reset();
eventContractContainerManager.removeContainer(innerEventContractContainer);
clickEvent = dispatchMouseEvent(innerTargetElement);
expect(dispatcher).toHaveBeenCalledTimes(1);
eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(innerTargetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
expect(documentListener).toHaveBeenCalledTimes(1);
});
}); | {
"end_byte": 22245,
"start_byte": 13649,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/eventcontract_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/eventcontract_test.ts_22249_31124 | describe('early events', () => {
it('early events are dispatched', () => {
const container = getRequiredElementById('click-container');
const targetElement = getRequiredElementById('click-target-element');
const removeEventListenerSpy = spyOn(
window.document.documentElement,
'removeEventListener',
).and.callThrough();
const earlyEventContract = new EarlyEventContract();
earlyEventContract.addEvents(['click']);
const clickEvent = dispatchMouseEvent(targetElement);
const earlyJsactionData: EarlyJsactionData | undefined = window._ejsa;
expect(earlyJsactionData).toBeDefined();
expect(earlyJsactionData!.q.length).toBe(1);
expect(earlyJsactionData!.q[0].event).toBe(clickEvent);
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
dispatcher,
});
eventContract.replayEarlyEvents();
expect(window._ejsa).toBeUndefined();
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('early capture events are dispatched', () => {
const container = getRequiredElementById('focus-container');
const targetElement = getRequiredElementById('focus-target-element');
const replaySink = {_ejsa: undefined};
const removeEventListenerSpy = spyOn(container, 'removeEventListener').and.callThrough();
const earlyEventContract = new EarlyEventContract(replaySink, container);
earlyEventContract.addEvents(['focus'], true);
targetElement.focus();
const earlyJsactionData: EarlyJsactionData | undefined = replaySink._ejsa;
expect(earlyJsactionData).toBeDefined();
expect(earlyJsactionData!.q.length).toBe(1);
expect(earlyJsactionData!.q[0].event.type).toBe('focus');
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['focus'],
dispatcher,
});
eventContract.replayEarlyEvents(replaySink._ejsa);
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('focus');
expect(eventInfoWrapper.getEvent().type).toBe('focus');
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('early events are dispatched when target is cleared', () => {
const container = getRequiredElementById('click-container');
const targetElement = getRequiredElementById('click-target-element');
const removeEventListenerSpy = spyOn(
window.document.documentElement,
'removeEventListener',
).and.callThrough();
const earlyEventContract = new EarlyEventContract();
earlyEventContract.addEvents(['click']);
const clickEvent = dispatchMouseEvent(targetElement);
const earlyJsactionData: EarlyJsactionData | undefined = window._ejsa;
expect(earlyJsactionData).toBeDefined();
expect(earlyJsactionData!.q.length).toBe(1);
expect(earlyJsactionData!.q[0].event).toBe(clickEvent);
// Emulating browser behavior of clearing target after dispatch.
Object.defineProperty(clickEvent, 'target', {value: null});
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['click'],
dispatcher,
});
eventContract.replayEarlyEvents();
expect(window._ejsa).toBeUndefined();
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
describe('non-bubbling mouse events', () => {
beforeEach(() => {
EventContract.MOUSE_SPECIAL_SUPPORT = true;
});
afterEach(() => {
EventContract.MOUSE_SPECIAL_SUPPORT = false;
});
it('early mouseout dispatched as mouseleave and mouseout', () => {
const container = getRequiredElementById('mouseleave-container');
const targetElement = getRequiredElementById('mouseleave-target-element');
const removeEventListenerSpy = spyOn(
window.document.documentElement,
'removeEventListener',
).and.callThrough();
const early = new EarlyEventContract();
early.addEvents(['mouseout']);
const mouseOutEvent = dispatchMouseEvent(targetElement, {
type: 'mouseout',
// Indicates that the mouse entered the container and exited the
// target element.
relatedTarget: container,
});
const earlyJsactionData: EarlyJsactionData | undefined = (
window as EarlyJsactionDataContainer
)._ejsa;
expect(earlyJsactionData).toBeDefined();
expect(earlyJsactionData!.q.length).toBe(1);
expect(earlyJsactionData!.q[0].event).toBe(mouseOutEvent);
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['mouseout', 'mouseleave'],
dispatcher,
});
eventContract.replayEarlyEvents();
expect((window as EarlyJsactionDataContainer)._ejsa).toBeUndefined();
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(2);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('mouseleave');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('mouseout');
expect(syntheticMouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('early mouseout dispatched as only mouseleave', () => {
const container = getRequiredElementById('mouseleave-container');
const targetElement = getRequiredElementById('mouseleave-target-element');
const removeEventListenerSpy = spyOn(
window.document.documentElement,
'removeEventListener',
).and.callThrough();
const early = new EarlyEventContract();
early.addEvents(['mouseout']);
const mouseOutEvent = dispatchMouseEvent(targetElement, {
type: 'mouseout',
// Indicates that the mouse entered the container and exited the
// target element.
relatedTarget: container,
});
const earlyJsactionData: EarlyJsactionData | undefined = window._ejsa;
expect(earlyJsactionData).toBeDefined();
expect(earlyJsactionData!.q.length).toBe(1);
expect(earlyJsactionData!.q[0].event).toBe(mouseOutEvent);
const dispatcher = createDispatcherSpy();
const eventContract = createEventContract({
eventContractContainerManager: new EventContractContainer(container),
eventTypes: ['mouseleave'],
dispatcher,
});
eventContract.replayEarlyEvents();
expect(window._ejsa).toBeUndefined();
expect(removeEventListenerSpy).toHaveBeenCalledTimes(1);
expect(dispatcher).toHaveBeenCalledTimes(1);
const eventInfoWrapper = getLastDispatchedEventInfoWrapper(dispatcher);
expect(eventInfoWrapper.getEventType()).toBe('mouseleave');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('mouseout');
expect(syntheticMouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
});
});
}); | {
"end_byte": 31124,
"start_byte": 22249,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/eventcontract_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/html.ts_0_391 | /**
* @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 const safeElement = {
async setInnerHtml(element: Element, content: string) {
element.innerHTML = content;
},
};
export const testonlyHtml = (content: string) => content;
| {
"end_byte": 391,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/html.ts"
} |
angular/packages/core/primitives/event-dispatch/test/event_test.ts_0_2010 | /**
* @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 * as jsactionEvent from '../src/event';
import {EventType} from '../src/event_type';
import {KeyCode} from '../src/key_code';
function validTarget(): HTMLElement {
const target = document.createElement('div');
target.setAttribute('tabIndex', '0');
target.setAttribute('role', 'button');
return target;
}
function invalidTarget(): HTMLElement {
return document.createElement('div');
}
function roleTarget(): HTMLElement {
const target = document.createElement('div');
target.setAttribute('tabIndex', '0');
target.setAttribute('role', 'textbox');
return target;
}
/**
* Returns true if the given key or keyCode acts as a click event for the
* target element.
* @param keyCodeOrKey A numeric key code or string key value.
* @param target Optional target element of the keydown event.
* Defaults to a button element.
* @param originalTarget Optional originalTarget of the keydown
* Defaults to `opt_target`.
*/
function baseIsActionKeyEvent(
keyCodeOrKey: string | number,
target?: HTMLElement,
originalTarget?: HTMLElement,
): boolean {
const key = typeof keyCodeOrKey === 'string' ? keyCodeOrKey : undefined;
const keyCode = typeof keyCodeOrKey === 'number' ? keyCodeOrKey : undefined;
const event = {
type: EventType.KEYDOWN,
which: keyCode,
key,
target: target ?? validTarget(),
originalTarget: originalTarget ?? target ?? validTarget(),
};
try {
// isFocusable() in IE calls getBoundingClientRect(), which fails on orphans
document.body.appendChild(event.target);
event.target.style.height = '4px'; // Make sure we don't report as hidden.
event.target.style.width = '4px';
return jsactionEvent.isActionKeyEvent(event as unknown as Event);
} finally {
document.body.removeChild(event.target);
}
} | {
"end_byte": 2010,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/event_test.ts_2012_11008 | describe('event test.ts', () => {
let divInternal: Element;
beforeEach(() => {
divInternal = document.createElement('div');
});
it('add event listener click w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'click', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('click', handler, false);
expect(eventInfo.eventType).toBe('click');
expect(eventInfo.capture).toBe(false);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener focus w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'focus', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('focus', handler, true);
expect(eventInfo.eventType).toBe('focus');
expect(eventInfo.capture).toBe(true);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener blur w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'blur', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('blur', handler, true);
expect(eventInfo.eventType).toBe('blur');
expect(eventInfo.capture).toBe(true);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener error w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'error', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('error', handler, true);
expect(eventInfo.eventType).toBe('error');
expect(eventInfo.capture).toBe(true);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener load w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'load', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('load', handler, true);
expect(eventInfo.eventType).toBe('load');
expect(eventInfo.capture).toBe(true);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener toggle w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'toggle', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('toggle', handler, true);
expect(eventInfo.eventType).toBe('toggle');
expect(eventInfo.capture).toBe(true);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener touchstart w3 c', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, false);
expect(eventInfo.eventType).toBe('touchstart');
expect(eventInfo.capture).toBe(false);
expect(eventInfo.passive).toBeUndefined();
});
it('add event listener touchstart w3 c with passive:false', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler, false);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, {
capture: false,
passive: false,
});
expect(eventInfo.eventType).toBe('touchstart');
expect(eventInfo.capture).toBe(false);
expect(eventInfo.passive).toBe(false);
});
it('add event listener touchstart w3 c with passive:true', () => {
const addEventListenerSpy = spyOn(divInternal, 'addEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler, true);
expect(addEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, {
capture: false,
passive: true,
});
expect(eventInfo.eventType).toBe('touchstart');
expect(eventInfo.capture).toBe(false);
expect(eventInfo.passive).toBe(true);
});
it('remove event listener touchstart w3 c', () => {
const removeEventListenerSpy = spyOn(divInternal, 'removeEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler);
jsactionEvent.removeEventListener(divInternal, eventInfo);
expect(removeEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, false);
});
it('remove event listener touchstart w3 c with passive:false', () => {
const removeEventListenerSpy = spyOn(divInternal, 'removeEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler, false);
jsactionEvent.removeEventListener(divInternal, eventInfo);
expect(removeEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, {
capture: false,
});
});
it('remove event listener touchstart w3 c with passive:true', () => {
const removeEventListenerSpy = spyOn(divInternal, 'removeEventListener').and.callThrough();
const handler = () => {};
const eventInfo = jsactionEvent.addEventListener(divInternal, 'touchstart', handler, true);
jsactionEvent.removeEventListener(divInternal, eventInfo);
expect(removeEventListenerSpy).toHaveBeenCalledOnceWith('touchstart', handler, {
capture: false,
});
});
it('is modified click event mac meta key', () => {
const event = {metaKey: true} as unknown as Event;
jsactionEvent.testing.setIsMac(true);
expect(jsactionEvent.isModifiedClickEvent(event)).toBe(true);
});
it('is modified click event non mac ctrl key', () => {
const event = {ctrlKey: true} as unknown as Event;
jsactionEvent.testing.setIsMac(false);
expect(jsactionEvent.isModifiedClickEvent(event)).toBe(true);
});
it('is modified click event middle click', () => {
const event = {which: 2} as unknown as Event;
expect(jsactionEvent.isModifiedClickEvent(event)).toBe(true);
});
it('is modified click event middle click IE', () => {
const event = {button: 4} as unknown as Event;
expect(jsactionEvent.isModifiedClickEvent(event)).toBe(true);
});
it('is modified click event shift key', () => {
const event = {shiftKey: true} as unknown as Event;
expect(jsactionEvent.isModifiedClickEvent(event)).toBe(true);
});
it('is valid action key target', () => {
const div = document.createElement('div');
div.setAttribute('role', 'checkbox');
const textarea = document.createElement('textarea');
const input = document.createElement('input');
input.type = 'password';
expect(jsactionEvent.isValidActionKeyTarget(div)).toBe(true);
expect(jsactionEvent.isValidActionKeyTarget(textarea)).toBe(false);
expect(jsactionEvent.isValidActionKeyTarget(input)).toBe(false);
input.setAttribute('role', 'combobox');
expect(input.getAttribute('role')).toBe('combobox');
expect(jsactionEvent.isValidActionKeyTarget(input)).toBe(false);
const search = document.createElement('search') as HTMLElement & {
type: string;
};
search.type = 'search';
expect(search.type).toBe('search');
expect(jsactionEvent.isValidActionKeyTarget(search)).toBe(false);
const holder = document.createElement('div');
const num = document.createElement('input');
num.type = 'number';
holder.appendChild(num);
expect(jsactionEvent.isValidActionKeyTarget(num)).toBe(false);
const div2 = document.createElement('div');
// contentEditable only works on non-orphaned elements.
document.body.appendChild(div2);
div2.contentEditable = 'true';
div2.setAttribute('role', 'combobox');
expect(jsactionEvent.isValidActionKeyTarget(div2)).toBe(false);
div2.removeAttribute('role');
expect(jsactionEvent.isValidActionKeyTarget(div2)).toBe(false);
div.removeAttribute('role');
expect(jsactionEvent.isValidActionKeyTarget(div)).toBe(true);
document.body.removeChild(div2);
});
it('is action key event fails on click', () => {
const event = {type: 'click', target: validTarget} as unknown as Event;
expect(jsactionEvent.isActionKeyEvent(event)).toBe(false);
});
it('is action key event fails on invalid key', () => {
expect(baseIsActionKeyEvent(64)).toBe(false);
expect(baseIsActionKeyEvent('@')).toBe(false);
}); | {
"end_byte": 11008,
"start_byte": 2012,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/event_test.ts_11012_19673 | it('is action key event enter', () => {
expect(baseIsActionKeyEvent(KeyCode.ENTER)).toBe(true);
expect(baseIsActionKeyEvent('Enter')).toBe(true);
});
it('is action key event space', () => {
expect(baseIsActionKeyEvent(KeyCode.SPACE)).toBe(true);
expect(baseIsActionKeyEvent('Enter')).toBe(true);
});
it('is action key real check box', () => {
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
expect(baseIsActionKeyEvent(KeyCode.SPACE, checkbox)).toBe(false);
expect(baseIsActionKeyEvent(KeyCode.ENTER, checkbox)).toBe(false);
expect(baseIsActionKeyEvent('Enter', checkbox)).toBe(false);
expect(baseIsActionKeyEvent('Enter', checkbox)).toBe(false);
});
it('is action key fake check box', () => {
const checkbox = document.createElement('div');
checkbox.setAttribute('tabIndex', '0');
checkbox.setAttribute('role', 'checkbox');
expect(baseIsActionKeyEvent(KeyCode.SPACE, checkbox)).toBe(true);
expect(baseIsActionKeyEvent(KeyCode.ENTER, checkbox)).toBe(false);
expect(baseIsActionKeyEvent(' ', checkbox)).toBe(true);
expect(baseIsActionKeyEvent('Enter', checkbox)).toBe(false);
});
it('is action key event mac enter', () => {
if (!jsactionEvent.isWebKit) {
return;
}
expect(baseIsActionKeyEvent(KeyCode.MAC_ENTER)).toBe(true);
});
it('is action key non control', () => {
const control = document.createElement('div');
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(false);
expect(baseIsActionKeyEvent('Enter', control)).toBe(false);
});
it('is action key disabled control', () => {
const control = document.createElement('button');
control.disabled = true;
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(false);
expect(baseIsActionKeyEvent('Enter', control)).toBe(false);
});
it('is action key non tabbable control', () => {
const control = document.createElement('div');
// Adding role=button will make jsaction treat the div (normally not
// interactable) as a control, although it will remain non-tabbable.
control.setAttribute('role', 'button');
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(false);
expect(baseIsActionKeyEvent('Enter', control)).toBe(false);
});
it('is action key natively activatable control', () => {
const control = document.createElement('button');
expect(baseIsActionKeyEvent(KeyCode.SPACE, control)).toBe(false);
expect(baseIsActionKeyEvent(' ', control)).toBe(false);
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(false);
expect(baseIsActionKeyEvent('Enter', control)).toBe(false);
expect(baseIsActionKeyEvent(KeyCode.MAC_ENTER, control)).toBe(false);
});
it('is action key file input', () => {
const control = document.createElement('input');
control.type = 'file';
expect(baseIsActionKeyEvent(KeyCode.SPACE, control)).toBe(false);
expect(baseIsActionKeyEvent(' ', control)).toBe(false);
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(false);
expect(baseIsActionKeyEvent('Enter', control)).toBe(false);
expect(baseIsActionKeyEvent(KeyCode.MAC_ENTER, control)).toBe(false);
});
it('is action key event not in map', () => {
const control = document.createElement('div');
control.setAttribute('tabIndex', '0');
expect(baseIsActionKeyEvent(KeyCode.ENTER, control)).toBe(true);
expect(baseIsActionKeyEvent('Enter', control)).toBe(true);
expect(baseIsActionKeyEvent(KeyCode.SPACE, control)).toBe(false);
expect(baseIsActionKeyEvent(' ', control)).toBe(false);
});
it('is mouse special event mouseenter', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.MOUSEOVER,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, child)).toBe(true);
});
it('is mouse special event not mouseenter', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: child,
type: EventType.MOUSEOVER,
target: root,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, child)).toBe(false);
});
it('is mouse special event mouseover', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const subchild = document.createElement('div');
child.appendChild(subchild);
const event = {
relatedTarget: child,
type: EventType.MOUSEOVER,
target: subchild,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSEENTER, subchild)).toBe(true);
});
it('is mouse special event mouseleave', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.MOUSEOUT,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, child)).toBe(true);
});
it('is mouse special event not mouseleave', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: child,
type: EventType.MOUSEOUT,
target: root,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, child)).toBe(false);
});
it('is mouse special event mouseout', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const subchild = document.createElement('div');
child.appendChild(subchild);
const event = {
relatedTarget: child,
type: EventType.MOUSEOUT,
target: subchild,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, subchild)).toBe(true);
});
it('is mouse special event not mouse', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.CLICK,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.MOUSELEAVE, child)).toBe(false);
});
it('create mouse special event mouseenter', () => {
const div = document.createElement('div');
const event = document.createEvent('MouseEvent');
event.initEvent('mouseover', false, false);
div.dispatchEvent(event);
const copiedEvent = jsactionEvent.createMouseSpecialEvent(event, div);
expect(copiedEvent.type).toBe(EventType.MOUSEENTER);
expect(copiedEvent.target).toBe(div);
expect(copiedEvent.bubbles).toBe(false);
});
it('create mouse special event mouseleave', () => {
const div = document.createElement('div');
const event = document.createEvent('MouseEvent');
event.initEvent('mouseout', false, false);
div.dispatchEvent(event);
const copiedEvent = jsactionEvent.createMouseSpecialEvent(event, div);
expect(copiedEvent.type).toBe(EventType.MOUSELEAVE);
expect(copiedEvent.target).toBe(div);
expect(copiedEvent.bubbles).toBe(false);
});
it('is mouse special event pointerenter', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.POINTEROVER,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, child)).toBe(true);
}); | {
"end_byte": 19673,
"start_byte": 11012,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/event_test.ts_19677_28012 | it('is mouse special event not pointerenter', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: child,
type: EventType.POINTEROVER,
target: root,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, child)).toBe(false);
});
it('is mouse special event pointerover', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const subchild = document.createElement('div');
child.appendChild(subchild);
const event = {
relatedTarget: child,
type: EventType.POINTEROVER,
target: subchild,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERENTER, subchild)).toBe(true);
});
it('is mouse special event pointerleave', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.POINTEROUT,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, child)).toBe(true);
});
it('is mouse special event not pointerleave', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: child,
type: EventType.POINTEROUT,
target: root,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, child)).toBe(false);
});
it('is mouse special event pointerout', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const subchild = document.createElement('div');
child.appendChild(subchild);
const event = {
relatedTarget: child,
type: EventType.POINTEROUT,
target: subchild,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, root)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, subchild)).toBe(true);
});
it('is mouse special event not mouse', () => {
const root = document.createElement('div');
const child = document.createElement('div');
root.appendChild(child);
const event = {
relatedTarget: root,
type: EventType.CLICK,
target: child,
} as unknown as Event;
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, child)).toBe(false);
expect(jsactionEvent.isMouseSpecialEvent(event, EventType.POINTERLEAVE, child)).toBe(false);
});
it('create mouse special event pointerenter', () => {
const div = document.createElement('div');
const originalEvent = document.createEvent('MouseEvent');
originalEvent.initEvent('pointerover', false, false);
div.dispatchEvent(originalEvent);
const event = jsactionEvent.createMouseSpecialEvent(originalEvent, div);
expect(event.type).toBe(EventType.POINTERENTER);
expect(event.target).toBe(div);
expect(event.bubbles).toBe(false);
});
it('create mouse special event pointerleave', () => {
const div = document.createElement('div');
const originalEvent = document.createEvent('MouseEvent');
originalEvent.initEvent('pointerout', false, false);
div.dispatchEvent(originalEvent);
const event = jsactionEvent.createMouseSpecialEvent(originalEvent, div);
expect(event.type).toBe(EventType.POINTERLEAVE);
expect(event.target).toBe(div);
expect(event.bubbles).toBe(false);
});
it('recreate touch event with touches as click', () => {
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// touches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).touches = [
{clientX: 1, clientY: 2, screenX: 3, screenY: 4, pageX: 5, pageY: 6},
{},
];
const event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
expect(event.type).toBe('click');
expect(event.clientX).toBe(1);
expect(event.clientY).toBe(2);
expect(event.screenX).toBe(3);
expect(event.screenY).toBe(4);
});
it('recreate touch event with changed touches as click', () => {
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// changedTouches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).changedTouches = [
{
clientX: 'other',
clientY: 2,
screenX: 3,
screenY: 4,
pageX: 5,
pageY: 6,
},
];
const event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
expect(event.type).toBe('click');
expect(String(event.clientX)).toBe('other');
expect(event.clientY).toBe(2);
expect(event.screenX).toBe(3);
expect(event.screenY).toBe(4);
// originalEventType is a non-standard added property.
// tslint:disable-next-line:no-any
expect((event as any).originalEventType).toBe('touchend');
});
it('recreate touch event with empty changedTouches and touches as click', () => {
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// changedTouches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).changedTouches = [];
// touches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).touches = [{clientX: 1}, {}];
const event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
expect(event.type).toBe('click');
expect(event.clientX).toBe(1);
});
it('recreate touch event as click, has touch data', () => {
const div = document.createElement('div');
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// touches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).touches = [
{'clientX': 101, 'clientY': 102, 'screenX': 201, 'screenY': 202},
];
let event!: MouseEvent;
div.addEventListener('touchend', (originalEvent) => {
event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
});
div.dispatchEvent(originalEvent);
expect(event.type).toBe(EventType.CLICK);
// originalEventType is a non-standard added property.
// tslint:disable-next-line:no-any
expect((event as any).originalEventType).toBe(EventType.TOUCHEND);
expect(event.target).toBe(div);
expect(event.clientX).toBe(101);
expect(event.clientY).toBe(102);
expect(event.screenX).toBe(201);
expect(event.screenY).toBe(202);
});
it('recreate touch event as click, no touch data', () => {
const div = document.createElement('div');
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
let event!: MouseEvent;
div.addEventListener('touchend', (originalEvent) => {
event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
});
div.dispatchEvent(originalEvent);
expect(event.type).toBe(EventType.CLICK);
// originalEventType is a non-standard added property.
// tslint:disable-next-line:no-any
expect((event as any).originalEventType).toBe(EventType.TOUCHEND);
expect(event.target).toBe(div);
expect(event.clientX).toBeUndefined();
expect(event.clientY).toBeUndefined();
expect(event.screenX).toBeUndefined();
expect(event.screenY).toBeUndefined();
}); | {
"end_byte": 28012,
"start_byte": 19677,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/event_test.ts_28016_32605 | it('recreate touch event as click, behavior', () => {
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// touches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).touches = [
{clientX: 1, clientY: 2, screenX: 3, screenY: 4, pageX: 5, pageY: 6},
{},
];
const event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
expect(event.type).toBe('click');
expect(event.defaultPrevented).toBe(false);
event.preventDefault();
expect(event.defaultPrevented).toBe(true);
// _propagationStopped is a non-standard added property.
// tslint:disable-next-line:no-any
expect((event as any)['_propagationStopped']).toBe(false);
event.stopPropagation();
// _propagationStopped is a non-standard added property.
// tslint:disable-next-line:no-any
expect((event as any)['_propagationStopped']).toBe(true);
});
it('recreate touch event as click, time stamp', () => {
const originalEvent = document.createEvent('UIEvent') as TouchEvent;
originalEvent.initEvent('touchend', false, false);
// touches is readonly.
// tslint:disable-next-line:no-any
(originalEvent as any).touches = [
{clientX: 1, clientY: 2, screenX: 3, screenY: 4, pageX: 5, pageY: 6},
{},
];
const event = jsactionEvent.recreateTouchEventAsClick(originalEvent);
expect(event.type).toBe('click');
expect(event.timeStamp >= Date.now() - 500).toBe(true);
});
it('is space key event', () => {
let event = {
target: validTarget(),
keyCode: KeyCode.SPACE,
} as unknown as KeyboardEvent;
expect(jsactionEvent.isSpaceKeyEvent(event)).toBe(true);
const input = document.createElement('input');
input.type = 'checkbox';
event = {target: input, keyCode: KeyCode.SPACE} as unknown as KeyboardEvent;
expect(jsactionEvent.isSpaceKeyEvent(event)).toBe(false);
});
it('should call prevent default on native html control', () => {
let event = {target: validTarget()} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(true);
event = {target: invalidTarget()} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
event = {target: roleTarget()} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const button = document.createElement('button');
event = {target: button} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(true);
const divWithButtonRole = document.createElement('div');
divWithButtonRole.setAttribute('role', 'button');
event = {target: divWithButtonRole} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(true);
const input = document.createElement('input');
input.type = 'button';
event = {target: input} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(true);
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
event = {target: checkbox} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const radio = document.createElement('input');
radio.type = 'radio';
event = {target: radio} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const select = document.createElement('select');
event = {target: select} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const option = document.createElement('option');
event = {target: option} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const link = document.createElement('a');
link.setAttribute('href', 'http://www.google.com');
event = {target: link} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
const linkWithRole = document.createElement('a');
linkWithRole.setAttribute('href', 'http://www.google.com');
linkWithRole.setAttribute('role', 'menuitem');
event = {target: linkWithRole} as unknown as Event;
expect(jsactionEvent.shouldCallPreventDefaultOnNativeHtmlControl(event)).toBe(false);
});
}); | {
"end_byte": 32605,
"start_byte": 28016,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/BUILD.bazel_0_437 | load("//tools:defaults.bzl", "ts_library")
load("//devtools/tools:defaults.bzl", "karma_web_test_suite")
ts_library(
name = "browser_test_lib",
testonly = True,
srcs = glob(
[
"**/*.ts",
],
),
deps = [
"//packages/core/primitives/event-dispatch",
"//packages/private/testing",
],
)
karma_web_test_suite(
name = "browser_test",
deps = [":browser_test_lib"],
)
| {
"end_byte": 437,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/BUILD.bazel"
} |
angular/packages/core/primitives/event-dispatch/test/event_dispatcher_test.ts_0_9810 | /**
* @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 {EventDispatcher, EventPhase} from '../src/event_dispatcher';
import {createEventInfo, EventInfoWrapper} from '../src/event_info';
import {safeElement, testonlyHtml} from './html';
const domContent = `
<div id="click-container">
<div id="click-action-element" jsaction="click:handleClick">
<div id="click-target-element"></div>
</div>
</div>
<div id="bubbling-container">
<div id="bubbling-third-action-element" jsaction="click:thirdHandleClick">
<div id="bubbling-second-action-element" jsaction="click:secondHandleClick">
<div id="bubbling-first-action-element" jsaction="click:firstHandleClick">
<div id="bubbling-target-element"></div>
</div>
</div>
</div>
</div>
`;
function getRequiredElementById(id: string) {
const element = document.getElementById(id);
expect(element).not.toBeNull();
return element!;
}
function createClickEvent() {
return new MouseEvent('click', {bubbles: true, cancelable: true});
}
function createTestEventInfoWrapper({
eventType = 'click',
event = createClickEvent(),
targetElement = getRequiredElementById('click-target-element'),
container = getRequiredElementById('click-container'),
timestamp = 0,
isReplay,
}: {
eventType?: string;
event?: Event;
targetElement?: Element;
container?: Element;
timestamp?: number;
isReplay?: boolean;
} = {}): EventInfoWrapper {
return new EventInfoWrapper(
createEventInfo({
event,
eventType,
targetElement,
container,
timestamp,
isReplay,
}),
);
}
describe('EventDispatcher', () => {
beforeEach(() => {
safeElement.setInnerHtml(document.body, testonlyHtml(domContent));
});
it('dispatches to dispatchDelegate', () => {
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
expect(event.currentTarget).toBe(getRequiredElementById('click-action-element'));
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper();
dispatcher.dispatch(eventInfoWrapper.eventInfo);
expect(dispatchDelegate).toHaveBeenCalledWith(eventInfoWrapper.getEvent(), 'handleClick');
});
it('replays to dispatchDelegate', async () => {
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
expect(event.currentTarget).toBe(getRequiredElementById('click-action-element'));
expect(event.target).toBe(getRequiredElementById('click-target-element'));
expect(event.eventPhase).toBe(EventPhase.REPLAY);
expect(() => {
event.preventDefault();
}).toThrow();
expect(() => {
event.composedPath();
}).toThrow();
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({isReplay: true});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
await Promise.resolve();
expect(dispatchDelegate).toHaveBeenCalledWith(eventInfoWrapper.getEvent(), 'handleClick');
});
describe('bubbling', () => {
it('dispatches to multiple elements', () => {
const container = getRequiredElementById('bubbling-container');
const targetElement = getRequiredElementById('bubbling-target-element');
const currentTarget = jasmine.createSpy('currentTarget');
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
currentTarget(event.currentTarget);
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({container, targetElement});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
expect(dispatchDelegate).toHaveBeenCalledTimes(3);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'firstHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-first-action-element'),
);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'secondHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-second-action-element'),
);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'thirdHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-third-action-element'),
);
});
it('dispatches to multiple elements in replay', async () => {
const container = getRequiredElementById('bubbling-container');
const targetElement = getRequiredElementById('bubbling-target-element');
const currentTarget = jasmine.createSpy('currentTarget');
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
currentTarget(event.currentTarget);
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({
container,
targetElement,
isReplay: true,
});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
await Promise.resolve();
expect(dispatchDelegate).toHaveBeenCalledTimes(3);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'firstHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-first-action-element'),
);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'secondHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-second-action-element'),
);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'thirdHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-third-action-element'),
);
});
it('stops dispatch if `stopPropagation` is called', () => {
const container = getRequiredElementById('bubbling-container');
const targetElement = getRequiredElementById('bubbling-target-element');
const currentTarget = jasmine.createSpy('currentTarget');
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
currentTarget(event.currentTarget);
event.stopPropagation();
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({container, targetElement});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'firstHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-first-action-element'),
);
});
it('stops dispatch if `stopPropagation` is called in replay', async () => {
const container = getRequiredElementById('bubbling-container');
const targetElement = getRequiredElementById('bubbling-target-element');
const currentTarget = jasmine.createSpy('currentTarget');
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
currentTarget(event.currentTarget);
event.stopPropagation();
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({
container,
targetElement,
isReplay: true,
});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
await Promise.resolve();
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'firstHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-first-action-element'),
);
});
it('stops dispatch if `stopImmediatePropagation` is called', () => {
const container = getRequiredElementById('bubbling-container');
const targetElement = getRequiredElementById('bubbling-target-element');
const currentTarget = jasmine.createSpy('currentTarget');
const dispatchDelegate = jasmine
.createSpy<(event: Event, actionName: string) => void>('dispatchDelegate')
.and.callFake((event) => {
currentTarget(event.currentTarget);
event.stopImmediatePropagation();
});
const dispatcher = new EventDispatcher(dispatchDelegate);
const eventInfoWrapper = createTestEventInfoWrapper({container, targetElement});
dispatcher.dispatch(eventInfoWrapper.eventInfo);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
expect(dispatchDelegate).toHaveBeenCalledWith(
eventInfoWrapper.getEvent(),
'firstHandleClick',
);
expect(currentTarget).toHaveBeenCalledWith(
getRequiredElementById('bubbling-first-action-element'),
);
});
});
});
| {
"end_byte": 9810,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/event_dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_0_7065 | /**
* @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 * as cache from '../src/cache';
import {ActionInfo, createEventInfo, EventInfoWrapper} from '../src/event_info';
import {Dispatcher, registerDispatcher, Replayer} from '../src/dispatcher';
import {EventContract} from '../src/eventcontract';
import {EventContractContainer} from '../src/event_contract_container';
import {safeElement, testonlyHtml} from './html';
import {ActionResolver} from '../src/action_resolver';
import {
populateClickOnlyAction,
preventDefaultForA11yClick,
updateEventInfoForA11yClick,
} from '../src/a11y_click';
import {Property} from '../src/property';
const domContent = `
<div id="click-container">
<div id="click-action-element" jsaction="handleClick">
<div id="click-target-element"></div>
</div>
</div>
<div id="keydown-container">
<div id="keydown-action-element" jsaction="keydown:handleKeydown">
<div id="keydown-target-element"></div>
</div>
</div>
<div id="self-click-container">
<div id="self-click-target-element" jsaction="handleClick"></div>
</div>
<div id="parent-and-child-container">
<div>
<div jsaction="parentHandleClick">
<div id="parent-and-child-action-element" jsaction="childHandleClick">
<div id="parent-and-child-target-element"></div>
</div>
</div>
</div>
</div>
<div id="owner-click-container">
<div id="owner-click-action-element" jsaction="ownerHandleClick">
</div>
<div id="owner-click-target-element">
</div>
</div>
<div id="clickmod-container">
<div id="clickmod-action-element" jsaction="clickmod:handleClickMod">
<div id="clickmod-target-element"></div>
</div>
</div>
<div id="trailing-semicolon-container">
<div id="trailing-semicolon-action-element" jsaction="handleClick;">
<div id="trailing-semicolon-target-element"></div>
</div>
</div>
<div id="no-action-name-container">
<div id="no-action-name-action-element" jsaction="keydown:;;keyup:">
<div id="no-action-name-target-element"></div>
</div>
</div>
<div id="shadow-dom-container">
<div id="shadow-dom-action-element" jsaction="handleClick">
</div>
</div>
<div id="anchor-click-container">
<a id="anchor-click-action-element" href="javascript:void(0);" jsaction="handleClick">
<span id="anchor-click-target-element"></span>
</a>
</div>
<div id="a11y-click-container">
<div id="a11y-click-action-element" jsaction="handleClick">
<div id="a11y-click-target-element" tabindex="0"></div>
</a>
</div>
<div id="a11y-clickonly-container">
<div id="a11y-clickonly-action-element" jsaction="clickonly:handleClickOnly">
<div id="a11y-clickonly-target-element" tabindex="0"></div>
</a>
</div>
<div id="a11y-click-clickonly-container">
<div id="a11y-click-clickonly-action-element" jsaction="clickonly:handleClickOnly;click:handleClick">
<div id="a11y-click-clickonly-target-element" tabindex="0"></div>
</a>
</div>
<div id="anchor-clickmod-container">
<a id="anchor-clickmod-action-element" href="javascript:void(0);" jsaction="clickmod: handleClickMod">
<span id="anchor-clickmod-target-element"></span>
</a>
</div>
<div id="clickmod-container">
<div id="clickmod-action-element" jsaction="clickmod:handleClickMod">
<div id="clickmod-target-element"></div>
</div>
</div>
<div id="a11y-anchor-click-container">
<a id="a11y-anchor-click-action-element" href="javascript:void(0);" jsaction="handleClick">
<span id="a11y-anchor-click-target-element" tabindex="0"></span>
</a>
</div>
<div id="mouseenter-container">
<div id="mouseenter-action-element" jsaction="mouseenter:handleMouseEnter">
<div id="mouseenter-target-element"></div>
</div>
</div>
<div id="mouseleave-container">
<div id="mouseleave-action-element" jsaction="mouseleave:handleMouseLeave">
<div id="mouseleave-target-element"></div>
</div>
</div>
<div id="pointerenter-container">
<div id="pointerenter-action-element" jsaction="pointerenter:handlePointerEnter">
<div id="pointerenter-target-element"></div>
</div>
</div>
<div id="pointerleave-container">
<div id="pointerleave-action-element" jsaction="pointerleave:handlePointerLeave">
<div id="pointerleave-target-element"></div>
</div>
</div>
`;
function getRequiredElementById(id: string) {
const element = document.getElementById(id);
expect(element).not.toBeNull();
return element!;
}
function createEventContract({
container,
eventTypes,
}: {
container: Element;
eventTypes: Array<string | [string, string]>;
}): EventContract {
const eventContract = new EventContract(new EventContractContainer(container));
for (const eventType of eventTypes) {
if (typeof eventType === 'string') {
eventContract.addEvent(eventType);
} else {
const [aliasedEventType, aliasEventType] = eventType;
eventContract.addEvent(aliasedEventType, aliasEventType);
}
}
return eventContract;
}
function createClickEvent() {
return new MouseEvent('click', {bubbles: true, cancelable: true});
}
function dispatchMouseEvent(
target: Element,
{
type = 'click',
ctrlKey = false,
altKey = false,
shiftKey = false,
metaKey = false,
relatedTarget = null,
}: {
type?: string;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
metaKey?: boolean;
relatedTarget?: Element | null;
} = {},
) {
// createEvent/initMouseEvent is used to support IE11
// tslint:disable:deprecation
const event = document.createEvent('MouseEvent');
event.initMouseEvent(
type,
true,
true,
window,
0,
0,
0,
0,
0,
ctrlKey,
altKey,
shiftKey,
metaKey,
0,
relatedTarget,
);
// tslint:enable:deprecation
spyOn(event, 'preventDefault').and.callThrough();
target.dispatchEvent(event);
return event;
}
function dispatchKeyboardEvent(
target: Element,
{
type = 'keydown',
key = '',
location = 0,
ctrlKey = false,
altKey = false,
shiftKey = false,
metaKey = false,
}: {
type?: string;
key?: string;
location?: number;
ctrlKey?: boolean;
altKey?: boolean;
shiftKey?: boolean;
metaKey?: boolean;
} = {},
) {
// createEvent/initKeyboardEvent is used to support IE11
// tslint:disable:deprecation
const event = document.createEvent('KeyboardEvent');
event.initKeyboardEvent(
type,
true,
true,
window,
key,
location,
ctrlKey,
altKey,
shiftKey,
metaKey,
);
// tslint:enable:deprecation
// This is necessary as Chrome does not respect the key parameter in
// `initKeyboardEvent`.
Object.defineProperty(event, 'key', {value: key});
spyOn(event, 'preventDefault').and.callThrough();
target.dispatchEvent(event);
return event;
}
function createTestActionInfo({
name = 'handleClick',
element = document.createElement('div'),
} = {}): ActionInfo {
return {name, element};
} | {
"end_byte": 7065,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_7067_8632 | function createTestEventInfoWrapper({
eventType = 'click',
event = createClickEvent(),
targetElement = document.createElement('div'),
container = document.createElement('div'),
timestamp = 0,
action = createTestActionInfo(),
isReplay = undefined,
}: {
eventType?: string;
event?: Event;
targetElement?: Element;
container?: Element;
timestamp?: number;
action?: ActionInfo;
isReplay?: boolean;
} = {}): EventInfoWrapper {
return new EventInfoWrapper(
createEventInfo({
event,
eventType,
targetElement,
container,
timestamp,
action,
isReplay,
}),
);
}
function createDispatchDelegateSpy() {
return jasmine.createSpy<(eventInfoWrapper: EventInfoWrapper) => void>('dispatchDelegate');
}
function createDispatcher({
dispatchDelegate,
eventContract,
eventReplayer,
a11yClickSupport = false,
syntheticMouseEventSupport = false,
}: {
dispatchDelegate: (eventInfoWrapper: EventInfoWrapper) => void;
eventContract?: EventContract;
eventReplayer?: Replayer;
a11yClickSupport?: boolean;
syntheticMouseEventSupport?: boolean;
}) {
const actionResolver = new ActionResolver({syntheticMouseEventSupport});
if (a11yClickSupport) {
actionResolver.addA11yClickSupport(
updateEventInfoForA11yClick,
preventDefaultForA11yClick,
populateClickOnlyAction,
);
}
const dispatcher = new Dispatcher(dispatchDelegate, {actionResolver, eventReplayer});
if (eventContract) {
registerDispatcher(eventContract, dispatcher);
}
return dispatcher;
} | {
"end_byte": 8632,
"start_byte": 7067,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_8634_18277 | describe('Dispatcher', () => {
beforeEach(() => {
safeElement.setInnerHtml(document.body, testonlyHtml(domContent));
// Normalize timestamp.
spyOn(Date, 'now').and.returnValue(0);
});
it('dispatches event', () => {
const container = getRequiredElementById('click-container');
const actionElement = getRequiredElementById('click-action-element');
const targetElement = getRequiredElementById('click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatches event when targetElement is actionElement', () => {
const container = getRequiredElementById('self-click-container');
const targetElement = getRequiredElementById('self-click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(targetElement);
});
it('dispatch event to child and ignore parent', () => {
const container = getRequiredElementById('parent-and-child-container');
const actionElement = getRequiredElementById('parent-and-child-action-element');
const targetElement = getRequiredElementById('parent-and-child-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('childHandleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatch event through owner', () => {
const container = getRequiredElementById('owner-click-container');
const actionElement = getRequiredElementById('owner-click-action-element');
const targetElement = getRequiredElementById('owner-click-target-element');
targetElement[Property.OWNER] = actionElement;
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('ownerHandleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatches modified click event', () => {
const container = getRequiredElementById('clickmod-container');
const actionElement = getRequiredElementById('clickmod-action-element');
const targetElement = getRequiredElementById('clickmod-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement, {shiftKey: true});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('clickmod');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClickMod');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('caches jsaction attribute', () => {
const container = getRequiredElementById('click-container');
const actionElement = getRequiredElementById('click-action-element');
const targetElement = getRequiredElementById('click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
let clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
let eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
actionElement.setAttribute('jsaction', 'renamedHandleClick');
dispatchDelegate.calls.reset();
clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('re-parses jsaction attribute if the action cache is cleared', () => {
const container = getRequiredElementById('click-container');
const actionElement = getRequiredElementById('click-action-element');
const targetElement = getRequiredElementById('click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
let clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
let eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
actionElement.setAttribute('jsaction', 'renamedHandleClick');
// Clear attribute cache.
cache.clear(actionElement);
dispatchDelegate.calls.reset();
clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('renamedHandleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('handles trailing semicolon in jsaction attribute', () => {
const container = getRequiredElementById('trailing-semicolon-container');
const actionElement = getRequiredElementById('trailing-semicolon-action-element');
const targetElement = getRequiredElementById('trailing-semicolon-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
}); | {
"end_byte": 18277,
"start_byte": 8634,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_18281_27333 | it('handles jsaction attributes without action names, first action', () => {
const container = getRequiredElementById('no-action-name-container');
const actionElement = getRequiredElementById('no-action-name-action-element');
const targetElement = getRequiredElementById('no-action-name-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown', 'keyup'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const keydownEvent = dispatchKeyboardEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('keydown');
expect(eventInfoWrapper.getEvent()).toBe(keydownEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('handles jsaction attributes without action names, last action', () => {
const container = getRequiredElementById('no-action-name-container');
const actionElement = getRequiredElementById('no-action-name-action-element');
const targetElement = getRequiredElementById('no-action-name-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown', 'keyup'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const keyupEvent = dispatchKeyboardEvent(targetElement, {type: 'keyup'});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('keyup');
expect(eventInfoWrapper.getEvent()).toBe(keyupEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('does not handle jsaction attributes without event type or action name', () => {
const container = getRequiredElementById('no-action-name-container');
const targetElement = getRequiredElementById('no-action-name-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown', 'keyup'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('dispatches event from shadow dom', () => {
const container = getRequiredElementById('shadow-dom-container');
const actionElement = getRequiredElementById('shadow-dom-action-element');
// Not supported in ie11.
if (!actionElement.attachShadow) {
return;
}
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const shadow = actionElement.attachShadow({mode: 'open'});
const shadowChild = document.createElement('div');
shadow.appendChild(shadowChild);
shadowChild.click();
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
// Target element is set to the host from the event.
expect(eventInfoWrapper.getTargetElement()).toBe(actionElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('replays to dispatchDelegate', () => {
const dispatchDelegate = createDispatchDelegateSpy();
const dispatcher = createDispatcher({dispatchDelegate});
const eventInfoWrappers = [
createTestEventInfoWrapper({isReplay: true}),
createTestEventInfoWrapper({isReplay: true}),
createTestEventInfoWrapper({isReplay: true}),
];
for (const eventInfoWrapper of eventInfoWrappers) {
dispatcher.dispatch(eventInfoWrapper.eventInfo);
}
expect(dispatchDelegate).toHaveBeenCalledTimes(3);
for (let i = 0; i < eventInfoWrappers.length; i++) {
expect(dispatchDelegate.calls.argsFor(i)).toEqual([eventInfoWrappers[i]]);
}
});
it('replays to event replayer', async () => {
const dispatchDelegate = createDispatchDelegateSpy();
const eventReplayer = jasmine.createSpy<Replayer>('eventReplayer');
const dispatcher = createDispatcher({dispatchDelegate, eventReplayer});
const eventInfoWrappers = [
createTestEventInfoWrapper({isReplay: true}),
createTestEventInfoWrapper({isReplay: true}),
createTestEventInfoWrapper({isReplay: true}),
];
for (const eventInfoWrapper of eventInfoWrappers) {
dispatcher.dispatch(eventInfoWrapper.eventInfo);
}
await Promise.resolve();
expect(dispatchDelegate).toHaveBeenCalledTimes(0);
expect(eventReplayer).toHaveBeenCalledWith(eventInfoWrappers);
});
it('prevents default for click on anchor child', () => {
const container = getRequiredElementById('anchor-click-container');
const actionElement = getRequiredElementById('anchor-click-action-element');
const targetElement = getRequiredElementById('anchor-click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
expect(clickEvent.preventDefault).toHaveBeenCalled();
});
it('prevents default for modified click on anchor child', () => {
const container = getRequiredElementById('anchor-clickmod-container');
const actionElement = getRequiredElementById('anchor-clickmod-action-element');
const targetElement = getRequiredElementById('anchor-clickmod-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate =
jasmine.createSpy<(eventInfoWrapper: EventInfoWrapper) => void>('dispatchDelegate');
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement, {shiftKey: true});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('clickmod');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClickMod');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
expect(clickEvent.preventDefault).toHaveBeenCalled();
});
it('does not prevent default for modified click on non-anchor child', () => {
const container = getRequiredElementById('clickmod-container');
const actionElement = getRequiredElementById('clickmod-action-element');
const targetElement = getRequiredElementById('clickmod-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract});
const clickEvent = dispatchMouseEvent(targetElement, {shiftKey: true});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('clickmod');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClickMod');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
expect(clickEvent.preventDefault).not.toHaveBeenCalled();
}); | {
"end_byte": 27333,
"start_byte": 18281,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_27337_34242 | describe('a11y click', () => {
it('dispatches keydown as click event', () => {
const container = getRequiredElementById('a11y-click-container');
const actionElement = getRequiredElementById('a11y-click-action-element');
const targetElement = getRequiredElementById('a11y-click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const keydownEvent = dispatchKeyboardEvent(targetElement, {key: 'Enter'});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(keydownEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatches keydown event', () => {
const container = getRequiredElementById('keydown-container');
const actionElement = getRequiredElementById('keydown-action-element');
const targetElement = getRequiredElementById('keydown-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const keydownEvent = dispatchKeyboardEvent(targetElement, {key: 'a'});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('keydown');
expect(eventInfoWrapper.getEvent()).toBe(keydownEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleKeydown');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatches clickonly event', () => {
const container = getRequiredElementById('a11y-clickonly-container');
const actionElement = getRequiredElementById('a11y-clickonly-action-element');
const targetElement = getRequiredElementById('a11y-clickonly-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('clickonly');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClickOnly');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('dispatches click event to click handler rather than clickonly', () => {
const container = getRequiredElementById('a11y-click-clickonly-container');
const actionElement = getRequiredElementById('a11y-click-clickonly-action-element');
const targetElement = getRequiredElementById('a11y-click-clickonly-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const clickEvent = dispatchMouseEvent(targetElement);
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(clickEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('prevents default for enter key on anchor child', () => {
const container = getRequiredElementById('a11y-anchor-click-container');
const actionElement = getRequiredElementById('a11y-anchor-click-action-element');
const targetElement = getRequiredElementById('a11y-anchor-click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const keydownEvent = dispatchKeyboardEvent(targetElement, {key: 'Enter'});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(keydownEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
expect(keydownEvent.preventDefault).toHaveBeenCalled();
});
it('prevents default for enter key on anchor child', () => {
const container = getRequiredElementById('a11y-anchor-click-container');
const actionElement = getRequiredElementById('a11y-anchor-click-action-element');
const targetElement = getRequiredElementById('a11y-anchor-click-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['click', 'keydown'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, a11yClickSupport: true});
const keydownEvent = dispatchKeyboardEvent(targetElement, {key: 'Enter'});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('click');
expect(eventInfoWrapper.getEvent()).toBe(keydownEvent);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleClick');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
expect(keydownEvent.preventDefault).toHaveBeenCalled();
});
}); | {
"end_byte": 34242,
"start_byte": 27337,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_34246_44288 | describe('non-bubbling mouse events', () => {
beforeEach(() => {
EventContract.MOUSE_SPECIAL_SUPPORT = true;
});
afterEach(() => {
EventContract.MOUSE_SPECIAL_SUPPORT = false;
});
it('dispatches matching mouseover as mouseenter event', () => {
const container = getRequiredElementById('mouseenter-container');
const actionElement = getRequiredElementById('mouseenter-action-element');
const targetElement = getRequiredElementById('mouseenter-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['mouseenter'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'mouseover',
// Indicates that the mouse exited the container and entered the
// target element.
relatedTarget: container,
});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('mouseenter');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('mouseenter');
expect(syntheticMouseEvent.target).toBe(actionElement);
expect(eventInfoWrapper.getTargetElement()).toBe(actionElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleMouseEnter');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('does not dispatch non-matching mouseover event as mouseenter', () => {
const container = getRequiredElementById('mouseenter-container');
const actionElement = getRequiredElementById('mouseenter-action-element');
const targetElement = getRequiredElementById('mouseenter-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['mouseenter'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'mouseover',
// Indicates that the mouse exited the action element and entered the
// target element.
relatedTarget: actionElement,
});
// For failed `mouseenter` events, a global event is still dispatched without an action.
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('mouseenter');
const mouseEvent = eventInfoWrapper.getEvent();
expect(mouseEvent.type).toBe('mouseover');
expect(mouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('dispatches matching mouseout as mouseleave event', () => {
const container = getRequiredElementById('mouseleave-container');
const actionElement = getRequiredElementById('mouseleave-action-element');
const targetElement = getRequiredElementById('mouseleave-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['mouseleave'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'mouseout',
// Indicates that the mouse entered the container and exited the
// target element.
relatedTarget: container,
});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('mouseleave');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('mouseleave');
expect(syntheticMouseEvent.target).toBe(actionElement);
expect(eventInfoWrapper.getTargetElement()).toBe(actionElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handleMouseLeave');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('does not dispatch non-matching mouseout event as mouseleave', () => {
const container = getRequiredElementById('mouseleave-container');
const actionElement = getRequiredElementById('mouseleave-action-element');
const targetElement = getRequiredElementById('mouseleave-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['mouseleave'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'mouseout',
// Indicates that the mouse entered the action element and exited the
// target element.
relatedTarget: actionElement,
});
// For failed `mouseleave` events, a global event is still dispatched without an action.
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('mouseleave');
const mouseEvent = eventInfoWrapper.getEvent();
expect(mouseEvent.type).toBe('mouseout');
expect(mouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('dispatches matching pointerover as pointerenter event', () => {
const container = getRequiredElementById('pointerenter-container');
const actionElement = getRequiredElementById('pointerenter-action-element');
const targetElement = getRequiredElementById('pointerenter-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['pointerenter'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'pointerover',
// Indicates that the pointer exited the container and entered the
// target element.
relatedTarget: container,
});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('pointerenter');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('pointerenter');
expect(syntheticMouseEvent.target).toBe(actionElement);
expect(eventInfoWrapper.getTargetElement()).toBe(actionElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handlePointerEnter');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
});
it('does not dispatch non-matching pointerover event as pointerenter', () => {
const container = getRequiredElementById('pointerenter-container');
const actionElement = getRequiredElementById('pointerenter-action-element');
const targetElement = getRequiredElementById('pointerenter-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['pointerenter'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'pointerover',
// Indicates that the pointer exited the action element and entered the
// target element.
relatedTarget: actionElement,
});
// For failed `pointerenter` events, a global event is still dispatched without an action.
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('pointerenter');
const mouseEvent = eventInfoWrapper.getEvent();
expect(mouseEvent.type).toBe('pointerover');
expect(mouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
it('dispatches matching pointerout as pointerleave event', () => {
const container = getRequiredElementById('pointerleave-container');
const actionElement = getRequiredElementById('pointerleave-action-element');
const targetElement = getRequiredElementById('pointerleave-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['pointerleave'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'pointerout',
// Indicates that the pointer entered the container and exited the
// target element.
relatedTarget: container,
});
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('pointerleave');
const syntheticMouseEvent = eventInfoWrapper.getEvent();
expect(syntheticMouseEvent.type).toBe('pointerleave');
expect(syntheticMouseEvent.target).toBe(actionElement);
expect(eventInfoWrapper.getTargetElement()).toBe(actionElement);
expect(eventInfoWrapper.getAction()?.name).toBe('handlePointerLeave');
expect(eventInfoWrapper.getAction()?.element).toBe(actionElement);
}); | {
"end_byte": 44288,
"start_byte": 34246,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/test/dispatcher_test.ts_44294_45713 | it('does not dispatch non-matching pointerout event as pointerleave', () => {
const container = getRequiredElementById('pointerleave-container');
const actionElement = getRequiredElementById('pointerleave-action-element');
const targetElement = getRequiredElementById('pointerleave-target-element');
const eventContract = createEventContract({
container,
eventTypes: ['pointerleave'],
});
const dispatchDelegate = createDispatchDelegateSpy();
createDispatcher({dispatchDelegate, eventContract, syntheticMouseEventSupport: true});
dispatchMouseEvent(targetElement, {
type: 'pointerout',
// Indicates that the pointer entered the action element and exited the
// target element.
relatedTarget: actionElement,
});
// For failed `pointerleave` events, a global event is still dispatched without an action.
expect(dispatchDelegate).toHaveBeenCalledTimes(1);
const eventInfoWrapper = dispatchDelegate.calls.mostRecent().args[0];
expect(eventInfoWrapper.getEventType()).toBe('pointerleave');
const mouseEvent = eventInfoWrapper.getEvent();
expect(mouseEvent.type).toBe('pointerout');
expect(mouseEvent.target).toBe(targetElement);
expect(eventInfoWrapper.getTargetElement()).toBe(targetElement);
expect(eventInfoWrapper.getAction()).toBeUndefined();
});
});
}); | {
"end_byte": 45713,
"start_byte": 44294,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/test/dispatcher_test.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_info.ts_0_8798 | /**
* @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
*/
/**
* Records information about the action that should handle a given `Event`.
*/
export interface ActionInfo {
name: string;
element: Element;
}
type ActionInfoInternal = [name: string, element: Element];
/**
* Records information for later handling of events. This type is
* shared, and instances of it are passed, between the eventcontract
* and the dispatcher jsbinary. Therefore, the fields of this type are
* referenced by string literals rather than property literals
* throughout the code.
*
* 'targetElement' is the element the action occurred on, 'actionElement'
* is the element that has the jsaction handler.
*
* A null 'actionElement' identifies an EventInfo instance that didn't match a
* jsaction attribute. This allows us to execute global event handlers with the
* appropriate event type (including a11y clicks and custom events).
* The declare portion of this interface creates a set of externs that make sure
* renaming doesn't happen for EventInfo. This is important since EventInfo
* is shared across multiple binaries.
*/
export declare interface EventInfo {
eventType: string;
event: Event;
targetElement: Element;
/** The element that is the container for this Event. */
eic: Element;
timeStamp: number;
/**
* The action parsed from the JSAction element.
*/
eia?: ActionInfoInternal;
/**
* Whether this `Event` is a replay event, meaning no dispatcher was
* installed when this `Event` was originally dispatched.
*/
eirp?: boolean;
/**
* Whether this `Event` represents a `keydown` event that should be processed
* as a `click`. Only used when a11y click events is on.
*/
eiack?: boolean;
/** Whether action resolution has already run on this `EventInfo`. */
eir?: boolean;
}
/** Added for readability when accessing stable property names. */
export function getEventType(eventInfo: EventInfo) {
return eventInfo.eventType;
}
/** Added for readability when accessing stable property names. */
export function setEventType(eventInfo: EventInfo, eventType: string) {
eventInfo.eventType = eventType;
}
/** Added for readability when accessing stable property names. */
export function getEvent(eventInfo: EventInfo) {
return eventInfo.event;
}
/** Added for readability when accessing stable property names. */
export function setEvent(eventInfo: EventInfo, event: Event) {
eventInfo.event = event;
}
/** Added for readability when accessing stable property names. */
export function getTargetElement(eventInfo: EventInfo) {
return eventInfo.targetElement;
}
/** Added for readability when accessing stable property names. */
export function setTargetElement(eventInfo: EventInfo, targetElement: Element) {
eventInfo.targetElement = targetElement;
}
/** Added for readability when accessing stable property names. */
export function getContainer(eventInfo: EventInfo) {
return eventInfo.eic;
}
/** Added for readability when accessing stable property names. */
export function setContainer(eventInfo: EventInfo, container: Element) {
eventInfo.eic = container;
}
/** Added for readability when accessing stable property names. */
export function getTimestamp(eventInfo: EventInfo) {
return eventInfo.timeStamp;
}
/** Added for readability when accessing stable property names. */
export function setTimestamp(eventInfo: EventInfo, timestamp: number) {
eventInfo.timeStamp = timestamp;
}
/** Added for readability when accessing stable property names. */
export function getAction(eventInfo: EventInfo) {
return eventInfo.eia;
}
/** Added for readability when accessing stable property names. */
export function setAction(eventInfo: EventInfo, actionName: string, actionElement: Element) {
eventInfo.eia = [actionName, actionElement];
}
/** Added for readability when accessing stable property names. */
export function unsetAction(eventInfo: EventInfo) {
eventInfo.eia = undefined;
}
/** Added for readability when accessing stable property names. */
export function getActionName(actionInfo: ActionInfoInternal) {
return actionInfo[0];
}
/** Added for readability when accessing stable property names. */
export function getActionElement(actionInfo: ActionInfoInternal) {
return actionInfo[1];
}
/** Added for readability when accessing stable property names. */
export function getIsReplay(eventInfo: EventInfo) {
return eventInfo.eirp;
}
/** Added for readability when accessing stable property names. */
export function setIsReplay(eventInfo: EventInfo, replay: boolean) {
eventInfo.eirp = replay;
}
/** Added for readability when accessing stable property names. */
export function getA11yClickKey(eventInfo: EventInfo) {
return eventInfo.eiack;
}
/** Added for readability when accessing stable property names. */
export function setA11yClickKey(eventInfo: EventInfo, a11yClickKey: boolean) {
eventInfo.eiack = a11yClickKey;
}
/** Added for readability when accessing stable property names. */
export function getResolved(eventInfo: EventInfo) {
return eventInfo.eir;
}
/** Added for readability when accessing stable property names. */
export function setResolved(eventInfo: EventInfo, resolved: boolean) {
eventInfo.eir = resolved;
}
/** Clones an `EventInfo` */
export function cloneEventInfo(eventInfo: EventInfo): EventInfo {
return {
eventType: eventInfo.eventType,
event: eventInfo.event,
targetElement: eventInfo.targetElement,
eic: eventInfo.eic,
eia: eventInfo.eia,
timeStamp: eventInfo.timeStamp,
eirp: eventInfo.eirp,
eiack: eventInfo.eiack,
eir: eventInfo.eir,
};
}
/**
* Utility function for creating an `EventInfo`.
*
* This can be used from code-size sensitive compilation units, as taking
* parameters vs. an `Object` literal reduces code size.
*/
export function createEventInfoFromParameters(
eventType: string,
event: Event,
targetElement: Element,
container: Element,
timestamp: number,
action?: ActionInfoInternal,
isReplay?: boolean,
a11yClickKey?: boolean,
): EventInfo {
return {
eventType,
event,
targetElement,
eic: container,
timeStamp: timestamp,
eia: action,
eirp: isReplay,
eiack: a11yClickKey,
};
}
/**
* Utility function for creating an `EventInfo`.
*
* This should be used in compilation units that are less sensitive to code
* size.
*/
export function createEventInfo({
eventType,
event,
targetElement,
container,
timestamp,
action,
isReplay,
a11yClickKey,
}: {
eventType: string;
event: Event;
targetElement: Element;
container: Element;
timestamp: number;
action?: ActionInfo;
isReplay?: boolean;
a11yClickKey?: boolean;
}): EventInfo {
return {
eventType,
event,
targetElement,
eic: container,
timeStamp: timestamp,
eia: action ? [action.name, action.element] : undefined,
eirp: isReplay,
eiack: a11yClickKey,
};
}
/**
* Utility class around an `EventInfo`.
*
* This should be used in compilation units that are less sensitive to code
* size.
*/
export class EventInfoWrapper {
constructor(readonly eventInfo: EventInfo) {}
getEventType() {
return getEventType(this.eventInfo);
}
setEventType(eventType: string) {
setEventType(this.eventInfo, eventType);
}
getEvent() {
return getEvent(this.eventInfo);
}
setEvent(event: Event) {
setEvent(this.eventInfo, event);
}
getTargetElement() {
return getTargetElement(this.eventInfo);
}
setTargetElement(targetElement: Element) {
setTargetElement(this.eventInfo, targetElement);
}
getContainer() {
return getContainer(this.eventInfo);
}
setContainer(container: Element) {
setContainer(this.eventInfo, container);
}
getTimestamp() {
return getTimestamp(this.eventInfo);
}
setTimestamp(timestamp: number) {
setTimestamp(this.eventInfo, timestamp);
}
getAction() {
const action = getAction(this.eventInfo);
if (!action) return undefined;
return {
name: action[0],
element: action[1],
};
}
setAction(action: ActionInfo | undefined) {
if (!action) {
unsetAction(this.eventInfo);
return;
}
setAction(this.eventInfo, action.name, action.element);
}
getIsReplay() {
return getIsReplay(this.eventInfo);
}
setIsReplay(replay: boolean) {
setIsReplay(this.eventInfo, replay);
}
getResolved() {
return getResolved(this.eventInfo);
}
setResolved(resolved: boolean) {
setResolved(this.eventInfo, resolved);
}
clone() {
return new EventInfoWrapper(cloneEventInfo(this.eventInfo));
}
}
| {
"end_byte": 8798,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_info.ts"
} |
angular/packages/core/primitives/event-dispatch/src/bootstrap_global.ts_0_1611 | /**
* @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 {Restriction} from './restriction';
import {
addEvents,
createEarlyJsactionData,
getQueuedEventInfos,
registerDispatcher,
removeAllEventListeners,
} from './earlyeventcontract';
import {EventInfo} from './event_info';
/** Creates an `EarlyJsactionData`, adds events to it, and populates it on the window. */
export function bootstrapGlobalEarlyEventContract(
bubbleEventTypes: string[],
captureEventTypes: string[],
) {
const earlyJsactionData = createEarlyJsactionData(window.document.documentElement);
addEvents(earlyJsactionData, bubbleEventTypes);
addEvents(earlyJsactionData, captureEventTypes, /* capture= */ true);
window._ejsa = earlyJsactionData;
}
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
export function getGlobalQueuedEventInfos() {
return getQueuedEventInfos(window._ejsa);
}
/** Registers a dispatcher function on the `EarlyJsactionData` present on the window. */
export function registerGlobalDispatcher(
restriction: Restriction,
dispatcher: (eventInfo: EventInfo) => void,
) {
registerDispatcher(window._ejsa, dispatcher);
}
/** Removes all event listener handlers. */
export function removeAllGlobalEventListeners() {
removeAllEventListeners(window._ejsa);
}
/** Removes the global early event contract. */
export function clearGlobalEarlyEventContract() {
window._ejsa = undefined;
}
| {
"end_byte": 1611,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/bootstrap_global.ts"
} |
angular/packages/core/primitives/event-dispatch/src/a11y_click.ts_0_2158 | /**
* @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 * as eventLib from './event';
import * as eventInfoLib from './event_info';
import {EventType} from './event_type';
/**
* Update `EventInfo` to be `eventType = 'click'` and sets `a11yClickKey` if it
* is a a11y click.
*/
export function updateEventInfoForA11yClick(eventInfo: eventInfoLib.EventInfo) {
if (!eventLib.isActionKeyEvent(eventInfoLib.getEvent(eventInfo))) {
return;
}
eventInfoLib.setA11yClickKey(eventInfo, true);
// A 'click' triggered by a DOM keypress should be mapped to the 'click'
// jsaction.
eventInfoLib.setEventType(eventInfo, EventType.CLICK);
}
/**
* Call `preventDefault` on an a11y click if it is space key or to prevent the
* browser's default action for native HTML controls.
*/
export function preventDefaultForA11yClick(eventInfo: eventInfoLib.EventInfo) {
if (
!eventInfoLib.getA11yClickKey(eventInfo) ||
(!eventLib.isSpaceKeyEvent(eventInfoLib.getEvent(eventInfo)) &&
!eventLib.shouldCallPreventDefaultOnNativeHtmlControl(eventInfoLib.getEvent(eventInfo)))
) {
return;
}
eventLib.preventDefault(eventInfoLib.getEvent(eventInfo));
}
/**
* Sets the `action` to `clickonly` for a click event that is not an a11y click
* and if there is not already a click action.
*/
export function populateClickOnlyAction(
actionElement: Element,
eventInfo: eventInfoLib.EventInfo,
actionMap: {[key: string]: string | undefined},
) {
if (
// If there's already an action, don't attempt to set a CLICKONLY
eventInfoLib.getAction(eventInfo) ||
// Only attempt CLICKONLY if the type is CLICK
eventInfoLib.getEventType(eventInfo) !== EventType.CLICK ||
// a11y clicks are never CLICKONLY
eventInfoLib.getA11yClickKey(eventInfo) ||
actionMap[EventType.CLICKONLY] === undefined
) {
return;
}
eventInfoLib.setEventType(eventInfo, EventType.CLICKONLY);
eventInfoLib.setAction(eventInfo, actionMap[EventType.CLICKONLY]!, actionElement);
}
| {
"end_byte": 2158,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/a11y_click.ts"
} |
angular/packages/core/primitives/event-dispatch/src/restriction.ts_0_344 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview An enum to control who can call certain jsaction APIs.
*/
export enum Restriction {
I_AM_THE_JSACTION_FRAMEWORK,
}
| {
"end_byte": 344,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/restriction.ts"
} |
angular/packages/core/primitives/event-dispatch/src/eventcontract.ts_0_3365 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview Implements the local event handling contract. This
* allows DOM objects in a container that enters into this contract to
* define event handlers which are executed in a local context.
*
* One EventContract instance can manage the contract for multiple
* containers, which are added using the addContainer() method.
*
* Events can be registered using the addEvent() method.
*
* A Dispatcher is added using the registerDispatcher() method. Until there is
* a dispatcher, events are queued. The idea is that the EventContract
* class is inlined in the HTML of the top level page and instantiated
* right after the start of <body>. The Dispatcher class is contained
* in the external deferred js, and instantiated and registered with
* EventContract when the external javascript in the page loads. The
* external javascript will also register the jsaction handlers, which
* then pick up the queued events at the time of registration.
*
* Since this class is meant to be inlined in the main page HTML, the
* size of the binary compiled from this file MUST be kept as small as
* possible and thus its dependencies to a minimum.
*/
import {
EarlyJsactionData,
EarlyJsactionDataContainer,
removeAllEventListeners,
} from './earlyeventcontract';
import * as eventLib from './event';
import {EventContractContainerManager} from './event_contract_container';
import {MOUSE_SPECIAL_SUPPORT} from './event_contract_defines';
import * as eventInfoLib from './event_info';
import {MOUSE_SPECIAL_EVENT_TYPES} from './event_type';
import {Restriction} from './restriction';
/**
* The API of an EventContract that is safe to call from any compilation unit.
*/
export declare interface UnrenamedEventContract {
// Alias for Jsction EventContract registerDispatcher.
ecrd(dispatcher: Dispatcher, restriction: Restriction): void;
}
/** A function that is called to handle events captured by the EventContract. */
export type Dispatcher = (eventInfo: eventInfoLib.EventInfo, globalDispatch?: boolean) => void;
/**
* A function that handles an event dispatched from the browser.
*
* eventType: May differ from `event.type` if JSAction uses a
* short-hand name or is patching over an non-bubbling event with a bubbling
* variant.
* event: The native browser event.
* container: The container for this dispatch.
*/
type EventHandler = (eventType: string, event: Event, container: Element) => void;
/**
* EventContract intercepts events in the bubbling phase at the
* boundary of a container element, and maps them to generic actions
* which are specified using the custom jsaction attribute in
* HTML. Behavior of the application is then specified in terms of
* handler for such actions, cf. jsaction.Dispatcher in dispatcher.js.
*
* This has several benefits: (1) No DOM event handlers need to be
* registered on the specific elements in the UI. (2) The set of
* events that the application has to handle can be specified in terms
* of the semantics of the application, rather than in terms of DOM
* events. (3) Invocation of handlers can be delayed and handlers can
* be delay loaded in a generic way.
*/ | {
"end_byte": 3365,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/eventcontract.ts"
} |
angular/packages/core/primitives/event-dispatch/src/eventcontract.ts_3366_10660 | export class EventContract implements UnrenamedEventContract {
static MOUSE_SPECIAL_SUPPORT = MOUSE_SPECIAL_SUPPORT;
private containerManager: EventContractContainerManager | null;
/**
* The DOM events which this contract covers. Used to prevent double
* registration of event types. The value of the map is the
* internally created DOM event handler function that handles the
* DOM events. See addEvent().
*
*/
private eventHandlers: {[key: string]: EventHandler} = {};
private browserEventTypeToExtraEventTypes: {[key: string]: string[]} = {};
/**
* The dispatcher function. Events are passed to this function for
* handling once it was set using the registerDispatcher() method. This is
* done because the function is passed from another jsbinary, so passing the
* instance and invoking the method here would require to leave the method
* unobfuscated.
*/
private dispatcher: Dispatcher | null = null;
/**
* The list of suspended `EventInfo` that will be dispatched
* as soon as the `Dispatcher` is registered.
*/
private queuedEventInfos: eventInfoLib.EventInfo[] | null = [];
constructor(containerManager: EventContractContainerManager) {
this.containerManager = containerManager;
}
private handleEvent(eventType: string, event: Event, container: Element) {
const eventInfo = eventInfoLib.createEventInfoFromParameters(
/* eventType= */ eventType,
/* event= */ event,
/* targetElement= */ event.target as Element,
/* container= */ container,
/* timestamp= */ Date.now(),
);
this.handleEventInfo(eventInfo);
}
/**
* Handle an `EventInfo`.
*/
private handleEventInfo(eventInfo: eventInfoLib.EventInfo) {
if (!this.dispatcher) {
// All events are queued when the dispatcher isn't yet loaded.
eventInfoLib.setIsReplay(eventInfo, true);
this.queuedEventInfos?.push(eventInfo);
return;
}
this.dispatcher(eventInfo);
}
/**
* Enables jsaction handlers to be called for the event type given by
* name.
*
* If the event is already registered, this does nothing.
*
* @param prefixedEventType If supplied, this event is used in
* the actual browser event registration instead of the name that is
* exposed to jsaction. Use this if you e.g. want users to be able
* to subscribe to jsaction="transitionEnd:foo" while the underlying
* event is webkitTransitionEnd in one browser and mozTransitionEnd
* in another.
*
* @param passive A boolean value that, if `true`, indicates that the event
* handler will never call `preventDefault()`.
*/
addEvent(eventType: string, prefixedEventType?: string, passive?: boolean) {
if (eventType in this.eventHandlers || !this.containerManager) {
return;
}
if (!EventContract.MOUSE_SPECIAL_SUPPORT && MOUSE_SPECIAL_EVENT_TYPES.indexOf(eventType) >= 0) {
return;
}
const eventHandler = (eventType: string, event: Event, container: Element) => {
this.handleEvent(eventType, event, container);
};
// Store the callback to allow us to replay events.
this.eventHandlers[eventType] = eventHandler;
const browserEventType = eventLib.getBrowserEventType(prefixedEventType || eventType);
if (browserEventType !== eventType) {
const eventTypes = this.browserEventTypeToExtraEventTypes[browserEventType] || [];
eventTypes.push(eventType);
this.browserEventTypeToExtraEventTypes[browserEventType] = eventTypes;
}
this.containerManager.addEventListener(
browserEventType,
(element: Element) => {
return (event: Event) => {
eventHandler(eventType, event, element);
};
},
passive,
);
}
/**
* Gets the queued early events and replay them using the appropriate handler
* in the provided event contract. Once all the events are replayed, it cleans
* up the early contract.
*/
replayEarlyEvents(earlyJsactionData: EarlyJsactionData | undefined = window._ejsa) {
// Check if the early contract is present and prevent calling this function
// more than once.
if (!earlyJsactionData) {
return;
}
// Replay the early contract events.
this.replayEarlyEventInfos(earlyJsactionData.q);
// Clean up the early contract.
removeAllEventListeners(earlyJsactionData);
delete window._ejsa;
}
/**
* Replays all the early `EventInfo` objects, dispatching them through the normal
* `EventContract` flow.
*/
replayEarlyEventInfos(earlyEventInfos: eventInfoLib.EventInfo[]) {
for (let i = 0; i < earlyEventInfos.length; i++) {
const earlyEventInfo: eventInfoLib.EventInfo = earlyEventInfos[i];
const eventTypes = this.getEventTypesForBrowserEventType(earlyEventInfo.eventType);
for (let j = 0; j < eventTypes.length; j++) {
const eventInfo = eventInfoLib.cloneEventInfo(earlyEventInfo);
// EventInfo eventType maps to JSAction's internal event type,
// rather than the browser event type.
eventInfoLib.setEventType(eventInfo, eventTypes[j]);
this.handleEventInfo(eventInfo);
}
}
}
/**
* Returns all JSAction event types that have been registered for a given
* browser event type.
*/
private getEventTypesForBrowserEventType(browserEventType: string) {
const eventTypes = [];
if (this.eventHandlers[browserEventType]) {
eventTypes.push(browserEventType);
}
if (this.browserEventTypeToExtraEventTypes[browserEventType]) {
eventTypes.push(...this.browserEventTypeToExtraEventTypes[browserEventType]);
}
return eventTypes;
}
/**
* Returns the event handler function for a given event type.
*/
handler(eventType: string): EventHandler | undefined {
return this.eventHandlers[eventType];
}
/**
* Cleans up the event contract. This resets all of the `EventContract`'s
* internal state. Users are responsible for not using this `EventContract`
* after it has been cleaned up.
*/
cleanUp() {
this.containerManager!.cleanUp();
this.containerManager = null;
this.eventHandlers = {};
this.browserEventTypeToExtraEventTypes = {};
this.dispatcher = null;
this.queuedEventInfos = [];
}
/**
* Register a dispatcher function. Event info of each event mapped to
* a jsaction is passed for handling to this callback. The queued
* events are passed as well to the dispatcher for later replaying
* once the dispatcher is registered. Clears the event queue to null.
*
* @param dispatcher The dispatcher function.
* @param restriction
*/
registerDispatcher(dispatcher: Dispatcher, restriction: Restriction) {
this.ecrd(dispatcher, restriction);
}
/**
* Unrenamed alias for registerDispatcher. Necessary for any codebases that
* split the `EventContract` and `Dispatcher` code into different compilation
* units.
*/
ecrd(dispatcher: Dispatcher, restriction: Restriction) {
this.dispatcher = dispatcher;
if (this.queuedEventInfos?.length) {
for (let i = 0; i < this.queuedEventInfos.length; i++) {
this.handleEventInfo(this.queuedEventInfos[i]);
}
this.queuedEventInfos = null;
}
}
} | {
"end_byte": 10660,
"start_byte": 3366,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/eventcontract.ts"
} |
angular/packages/core/primitives/event-dispatch/src/action_resolver.ts_0_915 | /**
* @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 {Attribute} from './attribute';
import {Char} from './char';
import {EventType} from './event_type';
import {Property} from './property';
import * as a11yClick from './a11y_click';
import * as cache from './cache';
import * as eventInfoLib from './event_info';
import * as eventLib from './event';
/**
* Since maps from event to action are immutable we can use a single map
* to represent the empty map.
*/
const EMPTY_ACTION_MAP: {[key: string]: string} = {};
/**
* This regular expression matches a semicolon.
*/
const REGEXP_SEMICOLON = /\s*;\s*/;
/** If no event type is defined, defaults to `click`. */
const DEFAULT_EVENT_TYPE: string = EventType.CLICK;
/** Resolves actions for Events. */ | {
"end_byte": 915,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/action_resolver.ts"
} |
angular/packages/core/primitives/event-dispatch/src/action_resolver.ts_916_9355 | export class ActionResolver {
private a11yClickSupport: boolean = false;
private clickModSupport: boolean = true;
private readonly syntheticMouseEventSupport: boolean;
private updateEventInfoForA11yClick?: (eventInfo: eventInfoLib.EventInfo) => void = undefined;
private preventDefaultForA11yClick?: (eventInfo: eventInfoLib.EventInfo) => void = undefined;
private populateClickOnlyAction?: (
actionElement: Element,
eventInfo: eventInfoLib.EventInfo,
actionMap: {[key: string]: string | undefined},
) => void = undefined;
constructor({
syntheticMouseEventSupport = false,
clickModSupport = true,
}: {
syntheticMouseEventSupport?: boolean;
clickModSupport?: boolean;
} = {}) {
this.syntheticMouseEventSupport = syntheticMouseEventSupport;
this.clickModSupport = clickModSupport;
}
resolveEventType(eventInfo: eventInfoLib.EventInfo) {
// We distinguish modified and plain clicks in order to support the
// default browser behavior of modified clicks on links; usually to
// open the URL of the link in new tab or new window on ctrl/cmd
// click. A DOM 'click' event is mapped to the jsaction 'click'
// event iff there is no modifier present on the event. If there is
// a modifier, it's mapped to 'clickmod' instead.
//
// It's allowed to omit the event in the jsaction attribute. In that
// case, 'click' is assumed. Thus the following two are equivalent:
//
// <a href="someurl" jsaction="gna.fu">
// <a href="someurl" jsaction="click:gna.fu">
//
// For unmodified clicks, EventContract invokes the jsaction
// 'gna.fu'. For modified clicks, EventContract won't find a
// suitable action and leave the event to be handled by the
// browser.
//
// In order to also invoke a jsaction handler for a modifier click,
// 'clickmod' needs to be used:
//
// <a href="someurl" jsaction="clickmod:gna.fu">
//
// EventContract invokes the jsaction 'gna.fu' for modified
// clicks. Unmodified clicks are left to the browser.
//
// In order to set up the event contract to handle both clickonly and
// clickmod, only addEvent(EventType.CLICK) is necessary.
//
// In order to set up the event contract to handle click,
// addEvent() is necessary for CLICK, KEYDOWN, and KEYPRESS event types. If
// a11y click support is enabled, addEvent() will set up the appropriate key
// event handler automatically.
if (
this.clickModSupport &&
eventInfoLib.getEventType(eventInfo) === EventType.CLICK &&
eventLib.isModifiedClickEvent(eventInfoLib.getEvent(eventInfo))
) {
eventInfoLib.setEventType(eventInfo, EventType.CLICKMOD);
} else if (this.a11yClickSupport) {
this.updateEventInfoForA11yClick!(eventInfo);
}
}
resolveAction(eventInfo: eventInfoLib.EventInfo) {
if (eventInfoLib.getResolved(eventInfo)) {
return;
}
this.populateAction(eventInfo, eventInfoLib.getTargetElement(eventInfo));
eventInfoLib.setResolved(eventInfo, true);
}
resolveParentAction(eventInfo: eventInfoLib.EventInfo) {
const action = eventInfoLib.getAction(eventInfo);
const actionElement = action && eventInfoLib.getActionElement(action);
eventInfoLib.unsetAction(eventInfo);
const parentNode = actionElement && this.getParentNode(actionElement);
if (!parentNode) {
return;
}
this.populateAction(eventInfo, parentNode);
}
/**
* Searches for a jsaction that the DOM event maps to and creates an
* object containing event information used for dispatching by
* jsaction.Dispatcher. This method populates the `action` and `actionElement`
* fields of the EventInfo object passed in by finding the first
* jsaction attribute above the target Node of the event, and below
* the container Node, that specifies a jsaction for the event
* type. If no such jsaction is found, then action is undefined.
*
* @param eventInfo `EventInfo` to set `action` and `actionElement` if an
* action is found on any `Element` in the path of the `Event`.
*/
private populateAction(eventInfo: eventInfoLib.EventInfo, currentTarget: Element) {
let actionElement: Element | null = currentTarget;
while (actionElement && actionElement !== eventInfoLib.getContainer(eventInfo)) {
if (actionElement.nodeType === Node.ELEMENT_NODE) {
this.populateActionOnElement(actionElement, eventInfo);
}
if (eventInfoLib.getAction(eventInfo)) {
// An event is handled by at most one jsaction. Thus we stop at the
// first matching jsaction specified in a jsaction attribute up the
// ancestor chain of the event target node.
break;
}
actionElement = this.getParentNode(actionElement);
}
const action = eventInfoLib.getAction(eventInfo);
if (!action) {
// No action found.
return;
}
if (this.a11yClickSupport) {
this.preventDefaultForA11yClick!(eventInfo);
}
// We attempt to handle the mouseenter/mouseleave events here by
// detecting whether the mouseover/mouseout events correspond to
// entering/leaving an element.
if (this.syntheticMouseEventSupport) {
if (
eventInfoLib.getEventType(eventInfo) === EventType.MOUSEENTER ||
eventInfoLib.getEventType(eventInfo) === EventType.MOUSELEAVE ||
eventInfoLib.getEventType(eventInfo) === EventType.POINTERENTER ||
eventInfoLib.getEventType(eventInfo) === EventType.POINTERLEAVE
) {
// We attempt to handle the mouseenter/mouseleave events here by
// detecting whether the mouseover/mouseout events correspond to
// entering/leaving an element.
if (
eventLib.isMouseSpecialEvent(
eventInfoLib.getEvent(eventInfo),
eventInfoLib.getEventType(eventInfo),
eventInfoLib.getActionElement(action),
)
) {
// If both mouseover/mouseout and mouseenter/mouseleave events are
// enabled, two separate handlers for mouseover/mouseout are
// registered. Both handlers will see the same event instance
// so we create a copy to avoid interfering with the dispatching of
// the mouseover/mouseout event.
const copiedEvent = eventLib.createMouseSpecialEvent(
eventInfoLib.getEvent(eventInfo),
eventInfoLib.getActionElement(action),
);
eventInfoLib.setEvent(eventInfo, copiedEvent);
// Since the mouseenter/mouseleave events do not bubble, the target
// of the event is technically the `actionElement` (the node with the
// `jsaction` attribute)
eventInfoLib.setTargetElement(eventInfo, eventInfoLib.getActionElement(action));
} else {
eventInfoLib.unsetAction(eventInfo);
}
}
}
}
/**
* Walk to the parent node, unless the node has a different owner in
* which case we walk to the owner. Attempt to walk to host of a
* shadow root if needed.
*/
private getParentNode(element: Element): Element | null {
const owner = element[Property.OWNER];
if (owner) {
return owner as Element;
}
const parentNode = element.parentNode;
if (parentNode?.nodeName === '#document-fragment') {
return (parentNode as ShadowRoot | null)?.host ?? null;
}
return parentNode as Element | null;
}
/**
* Accesses the jsaction map on a node and retrieves the name of the
* action the given event is mapped to, if any. It parses the
* attribute value and stores it in a property on the node for
* subsequent retrieval without re-parsing and re-accessing the
* attribute.
*
* @param actionElement The DOM node to retrieve the jsaction map from.
* @param eventInfo `EventInfo` to set `action` and `actionElement` if an
* action is found on the `actionElement`.
*/
private populateActionOnElement(actionElement: Element, eventInfo: eventInfoLib.EventInfo) {
const actionMap = this.parseActions(actionElement);
const actionName = actionMap[eventInfoLib.getEventType(eventInfo)];
if (actionName !== undefined) {
eventInfoLib.setAction(eventInfo, actionName, actionElement);
}
if (this.a11yClickSupport) {
this.populateClickOnlyAction!(actionElement, eventInfo, actionMap);
}
} | {
"end_byte": 9355,
"start_byte": 916,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/action_resolver.ts"
} |
angular/packages/core/primitives/event-dispatch/src/action_resolver.ts_9359_11355 | /**
* Parses and caches an element's jsaction element into a map.
*
* This is primarily for internal use.
*
* @param actionElement The DOM node to retrieve the jsaction map from.
* @return Map from event to qualified name of the jsaction bound to it.
*/
private parseActions(actionElement: Element): {[key: string]: string | undefined} {
let actionMap: {[key: string]: string | undefined} | undefined = cache.get(actionElement);
if (!actionMap) {
const jsactionAttribute = actionElement.getAttribute(Attribute.JSACTION);
if (!jsactionAttribute) {
actionMap = EMPTY_ACTION_MAP;
cache.set(actionElement, actionMap);
} else {
actionMap = cache.getParsed(jsactionAttribute);
if (!actionMap) {
actionMap = {};
const values = jsactionAttribute.split(REGEXP_SEMICOLON);
for (let idx = 0; idx < values.length; idx++) {
const value = values[idx];
if (!value) {
continue;
}
const colon = value.indexOf(Char.EVENT_ACTION_SEPARATOR);
const hasColon = colon !== -1;
const type = hasColon ? value.substr(0, colon).trim() : DEFAULT_EVENT_TYPE;
const action = hasColon ? value.substr(colon + 1).trim() : value;
actionMap[type] = action;
}
cache.setParsed(jsactionAttribute, actionMap);
}
cache.set(actionElement, actionMap);
}
}
return actionMap;
}
addA11yClickSupport(
updateEventInfoForA11yClick: typeof a11yClick.updateEventInfoForA11yClick,
preventDefaultForA11yClick: typeof a11yClick.preventDefaultForA11yClick,
populateClickOnlyAction: typeof a11yClick.populateClickOnlyAction,
) {
this.a11yClickSupport = true;
this.updateEventInfoForA11yClick = updateEventInfoForA11yClick;
this.preventDefaultForA11yClick = preventDefaultForA11yClick;
this.populateClickOnlyAction = populateClickOnlyAction;
}
} | {
"end_byte": 11355,
"start_byte": 9359,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/action_resolver.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_contract_container.ts_0_2770 | /**
* @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 * as eventLib from './event';
import {EventHandlerInfo} from './event_handler';
/**
* An `EventContractContainerManager` provides the common interface for managing
* containers.
*/
export interface EventContractContainerManager {
addEventListener(
eventType: string,
getHandler: (element: Element) => (event: Event) => void,
passive?: boolean,
): void;
cleanUp(): void;
}
/**
* Whether the user agent is running on iOS.
*/
const isIos = typeof navigator !== 'undefined' && /iPhone|iPad|iPod/.test(navigator.userAgent);
/**
* A class representing a container node and all the event handlers
* installed on it. Used so that handlers can be cleaned up if the
* container is removed from the contract.
*/
export class EventContractContainer implements EventContractContainerManager {
/**
* Array of event handlers and their corresponding event types that are
* installed on this container.
*
*/
private handlerInfos: EventHandlerInfo[] = [];
/**
* @param element The container Element.
*/
constructor(readonly element: Element) {}
/**
* Installs the provided installer on the element owned by this container,
* and maintains a reference to resulting handler in order to remove it
* later if desired.
*/
addEventListener(
eventType: string,
getHandler: (element: Element) => (event: Event) => void,
passive?: boolean,
) {
// In iOS, event bubbling doesn't happen automatically in any DOM element,
// unless it has an onclick attribute or DOM event handler attached to it.
// This breaks JsAction in some cases. See "Making Elements Clickable"
// section at http://goo.gl/2VoGnB.
//
// A workaround for this issue is to change the CSS cursor style to 'pointer'
// for the container element, which magically turns on event bubbling. This
// solution is described in the comments section at http://goo.gl/6pEO1z.
//
// We use a navigator.userAgent check here as this problem is present both
// on Mobile Safari and thin WebKit wrappers, such as Chrome for iOS.
if (isIos) {
(this.element as HTMLElement).style.cursor = 'pointer';
}
this.handlerInfos.push(
eventLib.addEventListener(this.element, eventType, getHandler(this.element), passive),
);
}
/**
* Removes all the handlers installed on this container.
*/
cleanUp() {
for (let i = 0; i < this.handlerInfos.length; i++) {
eventLib.removeEventListener(this.element, this.handlerInfos[i]);
}
this.handlerInfos = [];
}
}
| {
"end_byte": 2770,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_contract_container.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_contract_multi_container.ts_0_6767 | /**
* @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 {EventContractContainer, EventContractContainerManager} from './event_contract_container';
/**
* An `EventContractContainerManager` that supports multiple containers.
*/
export class EventContractMultiContainer implements EventContractContainerManager {
/** The list of containers. */
private containers: EventContractContainer[] = [];
/** The list of nested containers. */
private nestedContainers: EventContractContainer[] = [];
/** The list of event handler installers. */
private eventHandlerInstallers: Array<(container: EventContractContainer) => void> = [];
/**
* @param stopPropagation Controls whether events can bubble between
* containers or not.
*/
constructor(private readonly stopPropagation = false) {}
/**
* Installs the provided installer on the element owned by this container,
* and maintains a reference to resulting handler in order to remove it
* later if desired.
*/
addEventListener(
eventType: string,
getHandler: (element: Element) => (event: Event) => void,
passive?: boolean,
) {
const eventHandlerInstaller = (container: EventContractContainer) => {
container.addEventListener(eventType, getHandler, passive);
};
for (let i = 0; i < this.containers.length; i++) {
eventHandlerInstaller(this.containers[i]);
}
this.eventHandlerInstallers.push(eventHandlerInstaller);
}
/**
* Removes all the handlers installed on all containers.
*/
cleanUp() {
const allContainers = [...this.containers, ...this.nestedContainers];
for (let i = 0; i < allContainers.length; i++) {
allContainers[i].cleanUp();
}
this.containers = [];
this.nestedContainers = [];
this.eventHandlerInstallers = [];
}
/**
* Adds a container to the `MultiEventContractContainer`.
* Signs the event contract for a new container. All registered events
* are enabled for this container too. Containers have to be kept disjoint,
* so if the newly added container is a parent/child of existing containers,
* they will be merged. If the container is already tracked by this
* `EventContract`, then the previously registered `EventContractContainer`
* will be returned.
*/
addContainer(element: Element): EventContractContainer {
// If the container is already registered, return.
for (let i = 0; i < this.containers.length; i++) {
if (element === this.containers[i].element) {
return this.containers[i];
}
}
const container = new EventContractContainer(element);
if (this.stopPropagation) {
// Events are not propagated, so containers can be considered independent.
this.setUpContainer(container);
this.containers.push(container);
} else {
if (this.isNestedContainer(container)) {
// This container has an ancestor that is already a contract container.
// Don't install event listeners on it in order to prevent an event from
// being handled multiple times.
this.nestedContainers.push(container);
return container;
}
this.setUpContainer(container);
this.containers.push(container);
this.updateNestedContainers();
}
return container;
}
/**
* Removes an already-added container from the contract.
*/
removeContainer(container: EventContractContainer) {
container.cleanUp();
let removed = false;
for (let i = 0; i < this.containers.length; ++i) {
if (this.containers[i] === container) {
this.containers.splice(i, 1);
removed = true;
break;
}
}
if (!removed) {
for (let i = 0; i < this.nestedContainers.length; ++i) {
if (this.nestedContainers[i] === container) {
this.nestedContainers.splice(i, 1);
break;
}
}
}
if (this.stopPropagation) {
return;
}
this.updateNestedContainers();
}
/**
* Tested whether any current container is a parent of the new container.
*/
private isNestedContainer(container: EventContractContainer): boolean {
for (let i = 0; i < this.containers.length; i++) {
if (containsNode(this.containers[i].element, container.element)) {
return true;
}
}
return false;
}
/** Installs all existing event handlers on a new container. */
private setUpContainer(container: EventContractContainer) {
for (let i = 0; i < this.eventHandlerInstallers.length; i++) {
this.eventHandlerInstallers[i](container);
}
}
/**
* Updates the list of nested containers after an add/remove operation. Only
* containers that are not children of other containers are placed in the
* containers list (and have event listeners on them). This is done in order
* to prevent events from being handled multiple times when `stopPropagation`
* is false.
*/
private updateNestedContainers() {
const allContainers = [...this.nestedContainers, ...this.containers];
const newNestedContainers = [];
const newContainers = [];
for (let i = 0; i < this.containers.length; ++i) {
const container = this.containers[i];
if (isNested(container, allContainers)) {
newNestedContainers.push(container);
// Remove the event listeners from the nested container.
container.cleanUp();
} else {
newContainers.push(container);
}
}
for (let i = 0; i < this.nestedContainers.length; ++i) {
const container = this.nestedContainers[i];
if (isNested(container, allContainers)) {
newNestedContainers.push(container);
} else {
newContainers.push(container);
// The container is no longer nested, add event listeners on it.
this.setUpContainer(container);
}
}
this.containers = newContainers;
this.nestedContainers = newNestedContainers;
}
}
/**
* Checks whether the container is a child of any of the containers.
*/
function isNested(
container: EventContractContainer,
containers: EventContractContainer[],
): boolean {
for (let i = 0; i < containers.length; ++i) {
if (containsNode(containers[i].element, container.element)) {
return true;
}
}
return false;
}
/**
* Checks whether parent contains child.
* IE11 only supports the native `Node.contains` for HTMLElement.
*/
function containsNode(parent: Node, child: Node): boolean {
if (parent === child) {
return false;
}
while (parent !== child && child.parentNode) {
child = child.parentNode;
}
return parent === child;
}
| {
"end_byte": 6767,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_contract_multi_container.ts"
} |
angular/packages/core/primitives/event-dispatch/src/earlyeventcontract.ts_0_3926 | /**
* @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 {createEventInfoFromParameters, EventInfo} from './event_info';
export declare interface EarlyJsactionDataContainer {
_ejsa?: EarlyJsactionData;
_ejsas?: {[appId: string]: EarlyJsactionData | undefined};
}
declare global {
interface Window {
_ejsa?: EarlyJsactionData;
_ejsas?: {[appId: string]: EarlyJsactionData | undefined};
}
}
/**
* Defines the early jsaction data types.
*/
export declare interface EarlyJsactionData {
/** List used to keep track of the early JSAction event types. */
et: string[];
/** List used to keep track of the early JSAction capture event types. */
etc: string[];
/** Early JSAction handler for all events. */
h: (event: Event) => void;
/** Dispatcher handler. Initializes to populating `q`. */
d: (eventInfo: EventInfo) => void;
/** List used to push `EventInfo` objects if the dispatcher is not registered. */
q: EventInfo[];
/** Container for listening to events. */
c: HTMLElement;
}
/**
* EarlyEventContract intercepts events in the bubbling phase at the
* boundary of the document body. This mapping will be passed to the
* late-loaded EventContract.
*/
export class EarlyEventContract {
constructor(
private readonly dataContainer: EarlyJsactionDataContainer = window,
container = window.document.documentElement,
) {
dataContainer._ejsa = createEarlyJsactionData(container);
}
/**
* Installs a list of event types for container .
*/
addEvents(types: string[], capture?: boolean) {
addEvents(this.dataContainer._ejsa!, types, capture);
}
}
/** Creates an `EarlyJsactionData` object. */
export function createEarlyJsactionData(container: HTMLElement) {
const q: EventInfo[] = [];
const d = (eventInfo: EventInfo) => {
q.push(eventInfo);
};
const h = (event: Event) => {
d(
createEventInfoFromParameters(
event.type,
event,
event.target as Element,
container,
Date.now(),
),
);
};
return {
c: container,
q,
et: [],
etc: [],
d,
h,
};
}
/** Add all the events to the container stored in the `EarlyJsactionData`. */
export function addEvents(
earlyJsactionData: EarlyJsactionData,
types: string[],
capture?: boolean,
) {
for (let i = 0; i < types.length; i++) {
const eventType = types[i];
const eventTypes = capture ? earlyJsactionData.etc : earlyJsactionData.et;
eventTypes.push(eventType);
earlyJsactionData.c.addEventListener(eventType, earlyJsactionData.h, capture);
}
}
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
export function getQueuedEventInfos(earlyJsactionData: EarlyJsactionData | undefined) {
return earlyJsactionData?.q ?? [];
}
/** Register a different dispatcher function on the `EarlyJsactionData`. */
export function registerDispatcher(
earlyJsactionData: EarlyJsactionData | undefined,
dispatcher: (eventInfo: EventInfo) => void,
) {
if (!earlyJsactionData) {
return;
}
earlyJsactionData.d = dispatcher;
}
/** Removes all event listener handlers. */
export function removeAllEventListeners(earlyJsactionData: EarlyJsactionData | undefined) {
if (!earlyJsactionData) {
return;
}
removeEventListeners(earlyJsactionData.c, earlyJsactionData.et, earlyJsactionData.h);
removeEventListeners(earlyJsactionData.c, earlyJsactionData.etc, earlyJsactionData.h, true);
}
function removeEventListeners(
container: HTMLElement,
eventTypes: string[],
earlyEventHandler: (e: Event) => void,
capture?: boolean,
) {
for (let i = 0; i < eventTypes.length; i++) {
container.removeEventListener(eventTypes[i], earlyEventHandler, /* useCapture */ capture);
}
}
| {
"end_byte": 3926,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/earlyeventcontract.ts"
} |
angular/packages/core/primitives/event-dispatch/src/cache.ts_0_1974 | /**
* @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 {Property} from './property';
/**
* Map from jsaction annotation to a parsed map from event name to action name.
*/
const parseCache: {[key: string]: {[key: string]: string | undefined}} = {};
/**
* Reads the jsaction parser cache from the given DOM Element.
*/
export function get(element: Element): {[key: string]: string | undefined} | undefined {
return element[Property.JSACTION];
}
/**
* Reads the jsaction parser cache for the given DOM element. If no cache is yet present,
* creates an empty one.
*/
export function getDefaulted(element: Element): {[key: string]: string | undefined} {
const cache = get(element) ?? {};
set(element, cache);
return cache;
}
/**
* Writes the jsaction parser cache to the given DOM Element.
*/
export function set(element: Element, actionMap: {[key: string]: string | undefined}) {
element[Property.JSACTION] = actionMap;
}
/**
* Looks up the parsed action map from the source jsaction attribute value.
*
* @param text Unparsed jsaction attribute value.
* @return Parsed jsaction attribute value, if already present in the cache.
*/
export function getParsed(text: string): {[key: string]: string | undefined} | undefined {
return parseCache[text];
}
/**
* Inserts the parse result for the given source jsaction value into the cache.
*
* @param text Unparsed jsaction attribute value.
* @param parsed Attribute value parsed into the action map.
*/
export function setParsed(text: string, parsed: {[key: string]: string | undefined}) {
parseCache[text] = parsed;
}
/**
* Clears the jsaction parser cache from the given DOM Element.
*
* @param element .
*/
export function clear(element: Element) {
if (Property.JSACTION in element) {
delete element[Property.JSACTION];
}
}
| {
"end_byte": 1974,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/cache.ts"
} |
angular/packages/core/primitives/event-dispatch/src/key_code.ts_0_578 | /**
* @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
*/
/**
* If on a Macintosh with an extended keyboard, the Enter key located in the
* numeric pad has a different ASCII code.
*/
export const MAC_ENTER = 3;
/** The Enter key. */
export const ENTER = 13;
/** The Space key. */
export const SPACE = 32;
/** Special keycodes used by jsaction for the generic click action. */
export const KeyCode = {MAC_ENTER, ENTER, SPACE};
| {
"end_byte": 578,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/key_code.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_dispatcher.ts_0_7293 | /**
* @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 {ActionResolver} from './action_resolver';
import {Dispatcher} from './dispatcher';
import {EventInfo, EventInfoWrapper} from './event_info';
import {isCaptureEventType} from './event_type';
import {UnrenamedEventContract} from './eventcontract';
import {Restriction} from './restriction';
/**
* A replayer is a function that is called when there are queued events, from the `EventContract`.
*/
export type Replayer = (eventInfoWrappers: Event[]) => void;
/** An internal symbol used to indicate whether propagation should be stopped or not. */
export const PROPAGATION_STOPPED_SYMBOL = Symbol.for('propagationStopped');
/** Extra event phases beyond what the browser provides. */
export const EventPhase = {
REPLAY: 101,
};
const PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS =
' Because event replay occurs after browser dispatch, `preventDefault` would have no ' +
'effect. You can check whether an event is being replayed by accessing the event phase: ' +
'`event.eventPhase === EventPhase.REPLAY`.';
const PREVENT_DEFAULT_ERROR_MESSAGE = `\`preventDefault\` called during event replay.`;
const COMPOSED_PATH_ERROR_MESSAGE_DETAILS =
' Because event replay occurs after browser ' +
'dispatch, `composedPath()` will be empty. Iterate parent nodes from `event.target` or ' +
'`event.currentTarget` if you need to check elements in the event path.';
const COMPOSED_PATH_ERROR_MESSAGE = `\`composedPath\` called during event replay.`;
declare global {
interface Event {
[PROPAGATION_STOPPED_SYMBOL]?: boolean;
}
}
/**
* A dispatcher that uses browser-based `Event` semantics, for example bubbling, `stopPropagation`,
* `currentTarget`, etc.
*/
export class EventDispatcher {
private readonly actionResolver: ActionResolver;
private readonly dispatcher: Dispatcher;
constructor(
private readonly dispatchDelegate: (event: Event, actionName: string) => void,
private readonly clickModSupport = true,
) {
this.actionResolver = new ActionResolver({clickModSupport});
this.dispatcher = new Dispatcher(
(eventInfoWrapper: EventInfoWrapper) => {
this.dispatchToDelegate(eventInfoWrapper);
},
{
actionResolver: this.actionResolver,
},
);
}
/**
* The entrypoint for the `EventContract` dispatch.
*/
dispatch(eventInfo: EventInfo): void {
this.dispatcher.dispatch(eventInfo);
}
/** Internal method that does basic disaptching. */
private dispatchToDelegate(eventInfoWrapper: EventInfoWrapper) {
if (eventInfoWrapper.getIsReplay()) {
prepareEventForReplay(eventInfoWrapper);
}
prepareEventForBubbling(eventInfoWrapper);
while (eventInfoWrapper.getAction()) {
prepareEventForDispatch(eventInfoWrapper);
// If this is a capture event, ONLY dispatch if the action element is the target.
if (
isCaptureEventType(eventInfoWrapper.getEventType()) &&
eventInfoWrapper.getAction()!.element !== eventInfoWrapper.getTargetElement()
) {
return;
}
this.dispatchDelegate(eventInfoWrapper.getEvent(), eventInfoWrapper.getAction()!.name);
if (propagationStopped(eventInfoWrapper)) {
return;
}
this.actionResolver.resolveParentAction(eventInfoWrapper.eventInfo);
}
}
}
function prepareEventForBubbling(eventInfoWrapper: EventInfoWrapper) {
const event = eventInfoWrapper.getEvent();
const originalStopPropagation = eventInfoWrapper.getEvent().stopPropagation.bind(event);
const stopPropagation = () => {
event[PROPAGATION_STOPPED_SYMBOL] = true;
originalStopPropagation();
};
patchEventInstance(event, 'stopPropagation', stopPropagation);
patchEventInstance(event, 'stopImmediatePropagation', stopPropagation);
}
function propagationStopped(eventInfoWrapper: EventInfoWrapper) {
const event = eventInfoWrapper.getEvent();
return !!event[PROPAGATION_STOPPED_SYMBOL];
}
function prepareEventForReplay(eventInfoWrapper: EventInfoWrapper) {
const event = eventInfoWrapper.getEvent();
const target = eventInfoWrapper.getTargetElement();
const originalPreventDefault = event.preventDefault.bind(event);
patchEventInstance(event, 'target', target);
patchEventInstance(event, 'eventPhase', EventPhase.REPLAY);
patchEventInstance(event, 'preventDefault', () => {
originalPreventDefault();
throw new Error(
PREVENT_DEFAULT_ERROR_MESSAGE + (ngDevMode ? PREVENT_DEFAULT_ERROR_MESSAGE_DETAILS : ''),
);
});
patchEventInstance(event, 'composedPath', () => {
throw new Error(
COMPOSED_PATH_ERROR_MESSAGE + (ngDevMode ? COMPOSED_PATH_ERROR_MESSAGE_DETAILS : ''),
);
});
}
function prepareEventForDispatch(eventInfoWrapper: EventInfoWrapper) {
const event = eventInfoWrapper.getEvent();
const currentTarget = eventInfoWrapper.getAction()?.element;
if (currentTarget) {
patchEventInstance(event, 'currentTarget', currentTarget, {
// `currentTarget` is going to get reassigned every dispatch.
configurable: true,
});
}
}
/**
* Patch `Event` instance during non-standard `Event` dispatch. This patches just the `Event`
* instance that the browser created, it does not patch global properties or methods.
*
* This is necessary because dispatching an `Event` outside of browser dispatch results in
* incorrect properties and methods that need to be polyfilled or do not work.
*
* JSAction dispatch adds two extra "phases" to event dispatch:
* 1. Event delegation - the event is being dispatched by a delegating event handler on a container
* (typically `window.document.documentElement`), to a delegated event handler on some child
* element. Certain `Event` properties will be unintuitive, such as `currentTarget`, which would
* be the container rather than the child element. Bubbling would also not work. In order to
* emulate the browser, these properties and methods on the `Event` are patched.
* 2. Event replay - the event is being dispatched by the framework once the handlers have been
* loaded (during hydration, or late-loaded). Certain `Event` properties can be unset by the
* browser because the `Event` is no longer actively being dispatched, such as `target`. Other
* methods have no effect because the `Event` has already been dispatched, such as
* `preventDefault`. Bubbling would also not work. These properties and methods are patched,
* either to fill in information that the browser may have removed, or to throw errors in methods
* that no longer behave as expected.
*/
function patchEventInstance<T>(
event: Event,
property: string,
value: T,
{configurable = false}: {configurable?: boolean} = {},
) {
Object.defineProperty(event, property, {value, configurable});
}
/**
* Registers deferred functionality for an EventContract and a Jsaction
* Dispatcher.
*/
export function registerDispatcher(
eventContract: UnrenamedEventContract,
dispatcher: EventDispatcher,
) {
eventContract.ecrd((eventInfo: EventInfo) => {
dispatcher.dispatch(eventInfo);
}, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
}
| {
"end_byte": 7293,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_dispatcher.ts"
} |
angular/packages/core/primitives/event-dispatch/src/char.ts_0_528 | /**
* @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 const Char = {
/**
* The separator between the namespace and the action name in the
* jsaction attribute value.
*/
NAMESPACE_ACTION_SEPARATOR: '.' as const,
/**
* The separator between the event name and action in the jsaction
* attribute value.
*/
EVENT_ACTION_SEPARATOR: ':' as const,
};
| {
"end_byte": 528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/char.ts"
} |
angular/packages/core/primitives/event-dispatch/src/bootstrap_app_scoped.ts_0_2257 | /**
* @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 {Restriction} from './restriction';
import {
EarlyJsactionDataContainer,
addEvents,
createEarlyJsactionData,
getQueuedEventInfos,
registerDispatcher,
removeAllEventListeners,
} from './earlyeventcontract';
import {EventInfo} from './event_info';
/**
* Creates an `EarlyJsactionData`, adds events to it, and populates it on a nested object on
* the window.
*/
export function bootstrapAppScopedEarlyEventContract(
container: HTMLElement,
appId: string,
bubbleEventTypes: string[],
captureEventTypes: string[],
dataContainer: EarlyJsactionDataContainer = window,
) {
const earlyJsactionData = createEarlyJsactionData(container);
if (!dataContainer._ejsas) {
dataContainer._ejsas = {};
}
dataContainer._ejsas[appId] = earlyJsactionData;
addEvents(earlyJsactionData, bubbleEventTypes);
addEvents(earlyJsactionData, captureEventTypes, /* capture= */ true);
}
/** Get the queued `EventInfo` objects that were dispatched before a dispatcher was registered. */
export function getAppScopedQueuedEventInfos(
appId: string,
dataContainer: EarlyJsactionDataContainer = window,
) {
return getQueuedEventInfos(dataContainer._ejsas?.[appId]);
}
/**
* Registers a dispatcher function on the `EarlyJsactionData` present on the nested object on the
* window.
*/
export function registerAppScopedDispatcher(
restriction: Restriction,
appId: string,
dispatcher: (eventInfo: EventInfo) => void,
dataContainer: EarlyJsactionDataContainer = window,
) {
registerDispatcher(dataContainer._ejsas?.[appId], dispatcher);
}
/** Removes all event listener handlers. */
export function removeAllAppScopedEventListeners(
appId: string,
dataContainer: EarlyJsactionDataContainer = window,
) {
removeAllEventListeners(dataContainer._ejsas?.[appId]);
}
/** Clear the early event contract. */
export function clearAppScopedEarlyEventContract(
appId: string,
dataContainer: EarlyJsactionDataContainer = window,
) {
if (!dataContainer._ejsas) {
return;
}
dataContainer._ejsas[appId] = undefined;
}
| {
"end_byte": 2257,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/bootstrap_app_scoped.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_type.ts_0_678 | /**
* @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
*/
/*
* Names of events that are special to jsaction. These are not all
* event types that are legal to use in either HTML or the addEvent()
* API, but these are the ones that are treated specially. All other
* DOM events can be used in either addEvent() or in the value of the
* jsaction attribute. Beware of browser specific events or events
* that don't bubble though: If they are not mentioned here, then
* event contract doesn't work around their peculiarities.
*/ | {
"end_byte": 678,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_type.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_type.ts_679_8146 | export const EventType = {
/**
* Mouse middle click, introduced in Chrome 55 and not yet supported on
* other browsers.
*/
AUXCLICK: 'auxclick',
/**
* The change event fired by browsers when the `value` attribute of input,
* select, and textarea elements are changed.
*/
CHANGE: 'change',
/**
* The click event. In addEvent() refers to all click events, in the
* jsaction attribute it refers to the unmodified click and Enter/Space
* keypress events. In the latter case, a jsaction click will be triggered,
* for accessibility reasons. See clickmod and clickonly, below.
*/
CLICK: 'click',
/**
* Specifies the jsaction for a modified click event (i.e. a mouse
* click with the modifier key Cmd/Ctrl pressed). This event isn't
* separately enabled in addEvent(), because in the DOM, it's just a
* click event.
*/
CLICKMOD: 'clickmod',
/**
* Specifies the jsaction for a click-only event. Click-only doesn't take
* into account the case where an element with focus receives an Enter/Space
* keypress. This event isn't separately enabled in addEvent().
*/
CLICKONLY: 'clickonly',
/**
* The dblclick event.
*/
DBLCLICK: 'dblclick',
/**
* Focus doesn't bubble, but you can use it in addEvent() and
* jsaction anyway. EventContract does the right thing under the
* hood.
*/
FOCUS: 'focus',
/**
* This event only exists in IE. For addEvent() and jsaction, use
* focus instead; EventContract does the right thing even though
* focus doesn't bubble.
*/
FOCUSIN: 'focusin',
/**
* Analog to focus.
*/
BLUR: 'blur',
/**
* Analog to focusin.
*/
FOCUSOUT: 'focusout',
/**
* Submit doesn't bubble, so it cannot be used with event
* contract. However, the browser helpfully fires a click event on
* the submit button of a form (even if the form is not submitted by
* a click on the submit button). So you should handle click on the
* submit button instead.
*/
SUBMIT: 'submit',
/**
* The keydown event. In addEvent() and non-click jsaction it represents the
* regular DOM keydown event. It represents click actions in non-Gecko
* browsers.
*/
KEYDOWN: 'keydown',
/**
* The keypress event. In addEvent() and non-click jsaction it represents the
* regular DOM keypress event. It represents click actions in Gecko browsers.
*/
KEYPRESS: 'keypress',
/**
* The keyup event. In addEvent() and non-click jsaction it represents the
* regular DOM keyup event. It represents click actions in non-Gecko
* browsers.
*/
KEYUP: 'keyup',
/**
* The mouseup event. Can either be used directly or used implicitly to
* capture mouseup events. In addEvent(), it represents a regular DOM
* mouseup event.
*/
MOUSEUP: 'mouseup',
/**
* The mousedown event. Can either be used directly or used implicitly to
* capture mouseenter events. In addEvent(), it represents a regular DOM
* mouseover event.
*/
MOUSEDOWN: 'mousedown',
/**
* The mouseover event. Can either be used directly or used implicitly to
* capture mouseenter events. In addEvent(), it represents a regular DOM
* mouseover event.
*/
MOUSEOVER: 'mouseover',
/**
* The mouseout event. Can either be used directly or used implicitly to
* capture mouseover events. In addEvent(), it represents a regular DOM
* mouseout event.
*/
MOUSEOUT: 'mouseout',
/**
* The mouseenter event. Does not bubble and fires individually on each
* element being entered within a DOM tree.
*/
MOUSEENTER: 'mouseenter',
/**
* The mouseleave event. Does not bubble and fires individually on each
* element being entered within a DOM tree.
*/
MOUSELEAVE: 'mouseleave',
/**
* The mousemove event.
*/
MOUSEMOVE: 'mousemove',
/**
* The pointerup event. Can either be used directly or used implicitly to
* capture pointerup events. In addEvent(), it represents a regular DOM
* pointerup event.
*/
POINTERUP: 'pointerup',
/**
* The pointerdown event. Can either be used directly or used implicitly to
* capture pointerenter events. In addEvent(), it represents a regular DOM
* mouseover event.
*/
POINTERDOWN: 'pointerdown',
/**
* The pointerover event. Can either be used directly or used implicitly to
* capture pointerenter events. In addEvent(), it represents a regular DOM
* pointerover event.
*/
POINTEROVER: 'pointerover',
/**
* The pointerout event. Can either be used directly or used implicitly to
* capture pointerover events. In addEvent(), it represents a regular DOM
* pointerout event.
*/
POINTEROUT: 'pointerout',
/**
* The pointerenter event. Does not bubble and fires individually on each
* element being entered within a DOM tree.
*/
POINTERENTER: 'pointerenter',
/**
* The pointerleave event. Does not bubble and fires individually on each
* element being entered within a DOM tree.
*/
POINTERLEAVE: 'pointerleave',
/**
* The pointermove event.
*/
POINTERMOVE: 'pointermove',
/**
* The pointercancel event.
*/
POINTERCANCEL: 'pointercancel',
/**
* The gotpointercapture event is fired when
* Element.setPointerCapture(pointerId) is called on a mouse input, or
* implicitly when a touch input begins.
*/
GOTPOINTERCAPTURE: 'gotpointercapture',
/**
* The lostpointercapture event is fired when
* Element.releasePointerCapture(pointerId) is called, or implicitly after a
* touch input ends.
*/
LOSTPOINTERCAPTURE: 'lostpointercapture',
/**
* The error event. The error event doesn't bubble, but you can use it in
* addEvent() and jsaction anyway. EventContract does the right thing under
* the hood (except in IE8 which does not use error events).
*/
ERROR: 'error',
/**
* The load event. The load event doesn't bubble, but you can use it in
* addEvent() and jsaction anyway. EventContract does the right thing
* under the hood.
*/
LOAD: 'load',
/**
* The unload event.
*/
UNLOAD: 'unload',
/**
* The touchstart event. Bubbles, will only ever fire in browsers with
* touch support.
*/
TOUCHSTART: 'touchstart',
/**
* The touchend event. Bubbles, will only ever fire in browsers with
* touch support.
*/
TOUCHEND: 'touchend',
/**
* The touchmove event. Bubbles, will only ever fire in browsers with
* touch support.
*/
TOUCHMOVE: 'touchmove',
/**
* The input event.
*/
INPUT: 'input',
/**
* The scroll event.
*/
SCROLL: 'scroll',
/**
* The toggle event. The toggle event doesn't bubble, but you can use it in
* addEvent() and jsaction anyway. EventContract does the right thing
* under the hood.
*/
TOGGLE: 'toggle',
/**
* A custom event. The actual custom event type is declared as the 'type'
* field in the event details. Supported in Firefox 6+, IE 9+, and all Chrome
* versions.
*
* This is an internal name. Users should use jsaction's fireCustomEvent to
* fire custom events instead of relying on this type to create them.
*/
CUSTOM: '_custom',
};
/** All event types that do not bubble or capture and need a polyfill. */
export const MOUSE_SPECIAL_EVENT_TYPES = [
EventType.MOUSEENTER,
EventType.MOUSELEAVE,
'pointerenter',
'pointerleave',
];
/** All event types that are registered in the bubble phase. */ | {
"end_byte": 8146,
"start_byte": 679,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_type.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_type.ts_8147_9841 | export const BUBBLE_EVENT_TYPES = [
EventType.CLICK,
EventType.DBLCLICK,
EventType.FOCUSIN,
EventType.FOCUSOUT,
EventType.KEYDOWN,
EventType.KEYUP,
EventType.KEYPRESS,
EventType.MOUSEOVER,
EventType.MOUSEOUT,
EventType.SUBMIT,
EventType.TOUCHSTART,
EventType.TOUCHEND,
EventType.TOUCHMOVE,
'touchcancel',
'auxclick',
'change',
'compositionstart',
'compositionupdate',
'compositionend',
'beforeinput',
'input',
'select',
'copy',
'cut',
'paste',
'mousedown',
'mouseup',
'wheel',
'contextmenu',
'dragover',
'dragenter',
'dragleave',
'drop',
'dragstart',
'dragend',
'pointerdown',
'pointermove',
'pointerup',
'pointercancel',
'pointerover',
'pointerout',
'gotpointercapture',
'lostpointercapture',
// Video events.
'ended',
'loadedmetadata',
// Page visibility events.
'pagehide',
'pageshow',
'visibilitychange',
// Content visibility events.
'beforematch',
];
/** All event types that are registered in the capture phase. */
export const CAPTURE_EVENT_TYPES = [
EventType.FOCUS,
EventType.BLUR,
EventType.ERROR,
EventType.LOAD,
EventType.TOGGLE,
];
/**
* Whether or not an event type should be registered in the capture phase.
* @param eventType
* @returns bool
*/
export const isCaptureEventType = (eventType: string) =>
CAPTURE_EVENT_TYPES.indexOf(eventType) >= 0;
/** All event types that are registered early. */
const EARLY_EVENT_TYPES = BUBBLE_EVENT_TYPES.concat(CAPTURE_EVENT_TYPES);
/**
* Whether or not an event type is registered in the early contract.
*/
export const isEarlyEventType = (eventType: string) => EARLY_EVENT_TYPES.indexOf(eventType) >= 0; | {
"end_byte": 9841,
"start_byte": 8147,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_type.ts"
} |
angular/packages/core/primitives/event-dispatch/src/property.ts_0_1212 | /**
* @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
*/
/** All properties that are used by jsaction. */
export const Property = {
/**
* The parsed value of the jsaction attribute is stored in this
* property on the DOM node. The parsed value is an Object. The
* property names of the object are the events; the values are the
* names of the actions. This property is attached even on nodes
* that don't have a jsaction attribute as an optimization, because
* property lookup is faster than attribute access.
*/
JSACTION: '__jsaction' as const,
/**
* The owner property references an a logical owner for a DOM node. JSAction
* will follow this reference instead of parentNode when traversing the DOM
* to find jsaction attributes. This allows overlaying a logical structure
* over a document where the DOM structure can't reflect that structure.
*/
OWNER: '__owner' as const,
};
declare global {
interface Node {
[Property.JSACTION]?: {[key: string]: string | undefined};
[Property.OWNER]?: ParentNode;
}
}
| {
"end_byte": 1212,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/property.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_handler.ts_0_456 | /**
* @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
*/
/**
*
* Information about a registered event handler, which can be used to
* deregister the event handler.
*/
export interface EventHandlerInfo {
eventType: string;
handler: (event: Event) => void;
capture: boolean;
passive?: boolean;
}
| {
"end_byte": 456,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_handler.ts"
} |
angular/packages/core/primitives/event-dispatch/src/attribute.ts_0_847 | /**
* @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 const Attribute = {
/**
* The jsaction attribute defines a mapping of a DOM event to a
* generic event (aka jsaction), to which the actual event handlers
* that implement the behavior of the application are bound. The
* value is a semicolon separated list of colon separated pairs of
* an optional DOM event name and a jsaction name. If the optional
* DOM event name is omitted, 'click' is assumed. The jsaction names
* are dot separated pairs of a namespace and a simple jsaction
* name.
*
* See grammar in README.md for expected syntax in the attribute value.
*/
JSACTION: 'jsaction' as const,
};
| {
"end_byte": 847,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/attribute.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event_contract_defines.ts_0_379 | /**
* @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
*/
/**
* @define Support for the non-bubbling mouseenter and mouseleave events. This
* flag can be overridden in a build rule.
*/
export const MOUSE_SPECIAL_SUPPORT = false;
| {
"end_byte": 379,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event_contract_defines.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event.ts_0_8113 | /**
* @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 {EventHandlerInfo} from './event_handler';
import {isCaptureEventType, EventType} from './event_type';
import {KeyCode} from './key_code';
/**
* Gets a browser event type, if it would differ from the JSAction event type.
*/
export function getBrowserEventType(eventType: string) {
// Mouseenter and mouseleave events are not handled directly because they
// are not available everywhere. In browsers where they are available, they
// don't bubble and aren't visible at the container boundary. Instead, we
// synthesize the mouseenter and mouseleave events from mouseover and
// mouseout events, respectively. Cf. eventcontract.js.
if (eventType === EventType.MOUSEENTER) {
return EventType.MOUSEOVER;
} else if (eventType === EventType.MOUSELEAVE) {
return EventType.MOUSEOUT;
} else if (eventType === EventType.POINTERENTER) {
return EventType.POINTEROVER;
} else if (eventType === EventType.POINTERLEAVE) {
return EventType.POINTEROUT;
}
return eventType;
}
/**
* Registers the event handler function with the given DOM element for
* the given event type.
*
* @param element The element.
* @param eventType The event type.
* @param handler The handler function to install.
* @param passive A boolean value that, if `true`, indicates that the function
* specified by `handler` will never call `preventDefault()`.
* @return Information needed to uninstall the event handler eventually.
*/
export function addEventListener(
element: Element,
eventType: string,
handler: (event: Event) => void,
passive?: boolean,
): EventHandlerInfo {
// All event handlers are registered in the bubbling
// phase.
//
// All browsers support focus and blur, but these events only are propagated
// in the capture phase. Very legacy browsers do not support focusin or
// focusout.
//
// It would be a bad idea to register all event handlers in the
// capture phase because then regular onclick handlers would not be
// executed at all on events that trigger a jsaction. That's not
// entirely what we want, at least for now.
//
// Error and load events (i.e. on images) do not bubble so they are also
// handled in the capture phase.
let capture = false;
if (isCaptureEventType(eventType)) {
capture = true;
}
const options = typeof passive === 'boolean' ? {capture, passive} : capture;
element.addEventListener(eventType, handler, options);
return {eventType, handler, capture, passive};
}
/**
* Removes the event handler for the given event from the element.
* the given event type.
*
* @param element The element.
* @param info The information needed to deregister the handler, as returned by
* addEventListener(), above.
*/
export function removeEventListener(element: Element, info: EventHandlerInfo) {
if (element.removeEventListener) {
// It's worth noting that some browser releases have been inconsistent on this, and unless
// you have specific reasons otherwise, it's probably wise to use the same values used for
// the call to addEventListener() when calling removeEventListener().
const options = typeof info.passive === 'boolean' ? {capture: info.capture} : info.capture;
element.removeEventListener(info.eventType, info.handler as EventListener, options);
// `detachEvent` is an old DOM API.
// tslint:disable-next-line:no-any
} else if ((element as any).detachEvent) {
// `detachEvent` is an old DOM API.
// tslint:disable-next-line:no-any
(element as any).detachEvent(`on${info.eventType}`, info.handler);
}
}
/**
* Cancels propagation of an event.
* @param e The event to cancel propagation for.
*/
export function stopPropagation(e: Event) {
e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
}
/**
* Prevents the default action of an event.
* @param e The event to prevent the default action for.
*/
export function preventDefault(e: Event) {
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
}
/**
* Gets the target Element of the event. In Firefox, a text node may appear as
* the target of the event, in which case we return the parent element of the
* text node.
* @param e The event to get the target of.
* @return The target element.
*/
export function getTarget(e: Event): Element {
let el = e.target as Element;
// In Firefox, the event may have a text node as its target. We always
// want the parent Element the text node belongs to, however.
if (!el.getAttribute && el.parentNode) {
el = el.parentNode as Element;
}
return el;
}
/**
* Whether we are on a Mac. Not pulling in useragent just for this.
*/
let isMac: boolean = typeof navigator !== 'undefined' && /Macintosh/.test(navigator.userAgent);
/**
* Determines and returns whether the given event (which is assumed to be a
* click event) is a middle click.
* NOTE: There is not a consistent way to identify middle click
* http://www.unixpapa.com/js/mouse.html
*/
function isMiddleClick(e: Event): boolean {
return (
// `which` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).which === 2 ||
// `which` is an old DOM API.
// tslint:disable-next-line:no-any
((e as any).which == null &&
// `button` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).button === 4) // middle click for IE
);
}
/**
* Determines and returns whether the given event (which is assumed
* to be a click event) is modified. A middle click is considered a modified
* click to retain the default browser action, which opens a link in a new tab.
* @param e The event.
* @return Whether the given event is modified.
*/
export function isModifiedClickEvent(e: Event): boolean {
return (
// `metaKey` is an old DOM API.
// tslint:disable-next-line:no-any
(isMac && (e as any).metaKey) ||
// `ctrlKey` is an old DOM API.
// tslint:disable-next-line:no-any
(!isMac && (e as any).ctrlKey) ||
isMiddleClick(e) ||
// `shiftKey` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).shiftKey
);
}
/** Whether we are on WebKit (e.g., Chrome). */
export const isWebKit: boolean =
typeof navigator !== 'undefined' &&
!/Opera/.test(navigator.userAgent) &&
/WebKit/.test(navigator.userAgent);
/** Whether we are on IE. */
export const isIe: boolean =
typeof navigator !== 'undefined' &&
(/MSIE/.test(navigator.userAgent) || /Trident/.test(navigator.userAgent));
/** Whether we are on Gecko (e.g., Firefox). */
export const isGecko: boolean =
typeof navigator !== 'undefined' &&
!/Opera|WebKit/.test(navigator.userAgent) &&
/Gecko/.test(navigator.product);
/**
* Determines and returns whether the given element is a valid target for
* keypress/keydown DOM events that act like regular DOM clicks.
* @param el The element.
* @return Whether the given element is a valid action key target.
*/
export function isValidActionKeyTarget(el: Element): boolean {
if (!('getAttribute' in el)) {
return false;
}
if (isTextControl(el)) {
return false;
}
if (isNativelyActivatable(el)) {
return false;
}
// `isContentEditable` is an old DOM API.
// tslint:disable-next-line:no-any
if ((el as any).isContentEditable) {
return false;
}
return true;
}
/**
* Whether an event has a modifier key activated.
* @param e The event.
* @return True, if a modifier key is activated.
*/
function hasModifierKey(e: Event): boolean {
return (
// `ctrlKey` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).ctrlKey ||
// `shiftKey` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).shiftKey ||
// `altKey` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).altKey ||
// `metaKey` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).metaKey
);
} | {
"end_byte": 8113,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event.ts_8115_14494 | /**
* Determines and returns whether the given event has a target that already
* has event handlers attached because it is a native HTML control. Used to
* determine if preventDefault should be called when isActionKeyEvent is true.
* @param e The event.
* @return If preventDefault should be called.
*/
export function shouldCallPreventDefaultOnNativeHtmlControl(e: Event): boolean {
const el = getTarget(e);
const tagName = el.tagName.toUpperCase();
const role = (el.getAttribute('role') || '').toUpperCase();
if (tagName === 'BUTTON' || role === 'BUTTON') {
return true;
}
if (!isNativeHTMLControl(el)) {
return false;
}
if (tagName === 'A') {
return false;
}
/**
* Fix for physical d-pads on feature phone platforms; the native event
* (ie. isTrusted: true) needs to fire to show the OPTION list. See
* b/135288469 for more info.
*/
if (tagName === 'SELECT') {
return false;
}
if (processSpace(el)) {
return false;
}
if (isTextControl(el)) {
return false;
}
return true;
}
/**
* Determines and returns whether the given event acts like a regular DOM click,
* and should be handled instead of the click. If this returns true, the caller
* will call preventDefault() to prevent a possible duplicate event.
* This is represented by a keypress (keydown on Gecko browsers) on Enter or
* Space key.
* @param e The event.
* @return True, if the event emulates a DOM click.
*/
export function isActionKeyEvent(e: Event): boolean {
let key =
// `which` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).which ||
// `keyCode` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).keyCode;
if (!key && (e as KeyboardEvent).key) {
key = ACTION_KEY_TO_KEYCODE[(e as KeyboardEvent).key];
}
if (isWebKit && key === KeyCode.MAC_ENTER) {
key = KeyCode.ENTER;
}
if (key !== KeyCode.ENTER && key !== KeyCode.SPACE) {
return false;
}
const el = getTarget(e);
if (e.type !== EventType.KEYDOWN || !isValidActionKeyTarget(el) || hasModifierKey(e)) {
return false;
}
// For <input type="checkbox">, we must only handle the browser's native click
// event, so that the browser can toggle the checkbox.
if (processSpace(el) && key === KeyCode.SPACE) {
return false;
}
// If this element is non-focusable, ignore stray keystrokes (b/18337209)
// Sscreen readers can move without tab focus, so any tabIndex is focusable.
// See B/21809604
if (!isFocusable(el)) {
return false;
}
const type = (
el.getAttribute('role') ||
(el as HTMLInputElement).type ||
el.tagName
).toUpperCase();
const isSpecificTriggerKey = IDENTIFIER_TO_KEY_TRIGGER_MAPPING[type] % key === 0;
const isDefaultTriggerKey = !(type in IDENTIFIER_TO_KEY_TRIGGER_MAPPING) && key === KeyCode.ENTER;
const hasType = el.tagName.toUpperCase() !== 'INPUT' || !!(el as HTMLInputElement).type;
return (isSpecificTriggerKey || isDefaultTriggerKey) && hasType;
}
/**
* Checks whether a DOM element can receive keyboard focus.
* This code is based on goog.dom.isFocusable, but simplified since we shouldn't
* care about visibility if we're already handling a keyboard event.
*/
function isFocusable(el: Element): boolean {
return (
(el.tagName in NATIVELY_FOCUSABLE_ELEMENTS || hasSpecifiedTabIndex(el)) &&
!(el as HTMLInputElement).disabled
);
}
/**
* @param element Element to check.
* @return Whether the element has a specified tab index.
*/
function hasSpecifiedTabIndex(element: Element): boolean {
// IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),
// which returns an object with a 'specified' property if tabIndex is
// specified. This works on other browsers, too.
const attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
return attrNode != null && attrNode.specified;
}
/** Element tagnames that are focusable by default. */
const NATIVELY_FOCUSABLE_ELEMENTS: {[key: string]: number} = {
'A': 1,
'INPUT': 1,
'TEXTAREA': 1,
'SELECT': 1,
'BUTTON': 1,
};
/** @return True, if the Space key was pressed. */
export function isSpaceKeyEvent(e: Event): boolean {
const key =
// `which` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).which ||
// `keyCode` is an old DOM API.
// tslint:disable-next-line:no-any
(e as any).keyCode;
const el = getTarget(e);
const elementName = ((el as HTMLInputElement).type || el.tagName).toUpperCase();
return key === KeyCode.SPACE && elementName !== 'CHECKBOX';
}
/**
* Determines whether the event corresponds to a non-bubbling mouse
* event type (mouseenter, mouseleave, pointerenter, and pointerleave).
*
* During mouseover (mouseenter) and pointerover (pointerenter), the
* relatedTarget is the element being entered from. During mouseout (mouseleave)
* and pointerout (pointerleave), the relatedTarget is the element being exited
* to.
*
* In both cases, if relatedTarget is outside target, then the corresponding
* special event has occurred, otherwise it hasn't.
*
* @param e The mouseover/mouseout event.
* @param type The type of the mouse special event.
* @param element The element on which the jsaction for the
* mouseenter/mouseleave event is defined.
* @return True if the event is a mouseenter/mouseleave event.
*/
export function isMouseSpecialEvent(e: Event, type: string, element: Element): boolean {
// `relatedTarget` is an old DOM API.
// tslint:disable-next-line:no-any
const related = (e as any).relatedTarget as Node;
return (
((e.type === EventType.MOUSEOVER && type === EventType.MOUSEENTER) ||
(e.type === EventType.MOUSEOUT && type === EventType.MOUSELEAVE) ||
(e.type === EventType.POINTEROVER && type === EventType.POINTERENTER) ||
(e.type === EventType.POINTEROUT && type === EventType.POINTERLEAVE)) &&
(!related || (related !== element && !element.contains(related)))
);
}
/**
* Creates a new EventLike object for a mouseenter/mouseleave event that's
* derived from the original corresponding mouseover/mouseout event.
* @param e The event.
* @param target The element on which the jsaction for the mouseenter/mouseleave
* event is defined.
* @return A modified event-like object copied from the event object passed into
* this function.
*/ | {
"end_byte": 14494,
"start_byte": 8115,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event.ts_14495_22475 | export function createMouseSpecialEvent(e: Event, target: Element): Event {
// We have to create a copy of the event object because we need to mutate
// its fields. We do this for the special mouse events because the event
// target needs to be retargeted to the action element rather than the real
// element (since we are simulating the special mouse events with mouseover/
// mouseout).
//
// Since we're making a copy anyways, we might as well attempt to convert
// this event into a pseudo-real mouseenter/mouseleave event by adjusting
// its type.
//
// tslint:disable-next-line:no-any
const copy: {-readonly [P in keyof Event]?: Event[P]} = {};
for (const property in e) {
if (property === 'srcElement' || property === 'target') {
continue;
}
const key = property as keyof Event;
// Making a copy requires iterating through all properties of `Event`.
// tslint:disable-next-line:no-dict-access-on-struct-type
const value = e[key];
if (typeof value === 'function') {
continue;
}
// Value should be the expected type, but the value of `key` is not known
// statically.
// tslint:disable-next-line:no-any
copy[key] = value as any;
}
if (e.type === EventType.MOUSEOVER) {
copy['type'] = EventType.MOUSEENTER;
} else if (e.type === EventType.MOUSEOUT) {
copy['type'] = EventType.MOUSELEAVE;
} else if (e.type === EventType.POINTEROVER) {
copy['type'] = EventType.POINTERENTER;
} else {
copy['type'] = EventType.POINTERLEAVE;
}
copy['target'] = copy['srcElement'] = target;
copy['bubbles'] = false;
return copy as Event;
}
/**
* Returns touch data extracted from the touch event: clientX, clientY, screenX
* and screenY. If the event has no touch information at all, the returned
* value is null.
*
* The fields of this Object are unquoted.
*
* @param event A touch event.
*/
export function getTouchData(
event: TouchEvent,
): {clientX: number; clientY: number; screenX: number; screenY: number} | null {
const touch =
(event.changedTouches && event.changedTouches[0]) || (event.touches && event.touches[0]);
if (!touch) {
return null;
}
return {
clientX: touch.clientX,
clientY: touch.clientY,
screenX: touch.screenX,
screenY: touch.screenY,
};
}
declare interface SyntheticMouseEvent extends Event {
// Redeclared from Event to indicate that it is not readonly.
defaultPrevented: boolean;
originalEventType: string;
_propagationStopped?: boolean;
}
/**
* Creates a new EventLike object for a "click" event that's derived from the
* original corresponding "touchend" event for a fast-click implementation.
*
* It takes a touch event, adds common fields found in a click event and
* changes the type to 'click', so that the resulting event looks more like
* a real click event.
*
* @param event A touch event.
* @return A modified event-like object copied from the event object passed into
* this function.
*/
export function recreateTouchEventAsClick(event: TouchEvent): MouseEvent {
const click: {-readonly [P in keyof MouseEvent]?: MouseEvent[P]} & Partial<SyntheticMouseEvent> =
{};
click['originalEventType'] = event.type;
click['type'] = EventType.CLICK;
for (const property in event) {
if (property === 'type' || property === 'srcElement') {
continue;
}
const key = property as keyof TouchEvent;
// Making a copy requires iterating through all properties of `TouchEvent`.
// tslint:disable-next-line:no-dict-access-on-struct-type
const value = event[key];
if (typeof value === 'function') {
continue;
}
// Value should be the expected type, but the value of `key` is not known
// statically.
// tslint:disable-next-line:no-any
click[key as keyof MouseEvent] = value as any;
}
// Ensure that the event has the most recent timestamp. This timestamp
// may be used in the future to validate or cancel subsequent click events.
click['timeStamp'] = Date.now();
// Emulate preventDefault and stopPropagation behavior
click['defaultPrevented'] = false;
click['preventDefault'] = syntheticPreventDefault;
click['_propagationStopped'] = false;
click['stopPropagation'] = syntheticStopPropagation;
// Emulate click coordinates using touch info
const touch = getTouchData(event);
if (touch) {
click['clientX'] = touch.clientX;
click['clientY'] = touch.clientY;
click['screenX'] = touch.screenX;
click['screenY'] = touch.screenY;
}
return click as MouseEvent;
}
/**
* An implementation of "preventDefault" for a synthesized event. Simply
* sets "defaultPrevented" property to true.
*/
function syntheticPreventDefault(this: Event) {
(this as SyntheticMouseEvent).defaultPrevented = true;
}
/**
* An implementation of "stopPropagation" for a synthesized event. It simply
* sets a synthetic non-standard "_propagationStopped" property to true.
*/
function syntheticStopPropagation(this: Event) {
(this as SyntheticMouseEvent)._propagationStopped = true;
}
/**
* Mapping of KeyboardEvent.key values to
* KeyCode values.
*/
const ACTION_KEY_TO_KEYCODE: {[key: string]: number} = {
'Enter': KeyCode.ENTER,
' ': KeyCode.SPACE,
};
/**
* Mapping of HTML element identifiers (ARIA role, type, or tagName) to the
* keys (enter and/or space) that should activate them. A value of zero means
* that both should activate them.
*/
export const IDENTIFIER_TO_KEY_TRIGGER_MAPPING: {[key: string]: number} = {
'A': KeyCode.ENTER,
'BUTTON': 0,
'CHECKBOX': KeyCode.SPACE,
'COMBOBOX': KeyCode.ENTER,
'FILE': 0,
'GRIDCELL': KeyCode.ENTER,
'LINK': KeyCode.ENTER,
'LISTBOX': KeyCode.ENTER,
'MENU': 0,
'MENUBAR': 0,
'MENUITEM': 0,
'MENUITEMCHECKBOX': 0,
'MENUITEMRADIO': 0,
'OPTION': 0,
'RADIO': KeyCode.SPACE,
'RADIOGROUP': KeyCode.SPACE,
'RESET': 0,
'SUBMIT': 0,
'SWITCH': KeyCode.SPACE,
'TAB': 0,
'TREE': KeyCode.ENTER,
'TREEITEM': KeyCode.ENTER,
};
/**
* Returns whether or not to process space based on the type of the element;
* checks to make sure that type is not null.
* @param element The element.
* @return Whether or not to process space based on type.
*/
function processSpace(element: Element): boolean {
const type = (element.getAttribute('type') || element.tagName).toUpperCase();
return type in PROCESS_SPACE;
}
/**
* Returns whether or not the given element is a text control.
* @param el The element.
* @return Whether or not the given element is a text control.
*/
function isTextControl(el: Element): boolean {
const type = (el.getAttribute('type') || el.tagName).toUpperCase();
return type in TEXT_CONTROLS;
}
/**
* Returns if the given element is a native HTML control.
* @param el The element.
* @return If the given element is a native HTML control.
*/
export function isNativeHTMLControl(el: Element): boolean {
return el.tagName.toUpperCase() in NATIVE_HTML_CONTROLS;
}
/**
* Returns if the given element is natively activatable. Browsers emit click
* events for natively activatable elements, even when activated via keyboard.
* For these elements, we don't need to raise a11y click events.
* @param el The element.
* @return If the given element is a native HTML control.
*/
function isNativelyActivatable(el: Element): boolean {
return (
el.tagName.toUpperCase() === 'BUTTON' ||
(!!(el as HTMLInputElement).type && (el as HTMLInputElement).type.toUpperCase() === 'FILE')
);
}
/**
* HTML <input> types (not ARIA roles) which will auto-trigger a click event for
* the Space key, with side-effects. We will not call preventDefault if space is
* pressed, nor will we raise a11y click events. For all other elements, we can
* suppress the default event (which has no desired side-effects) and handle the
* keydown ourselves.
*/
const PROCESS_SPACE: {[key: string]: boolean} = {
'CHECKBOX': true,
'FILE': true,
'OPTION': true,
'RADIO': true,
}; | {
"end_byte": 22475,
"start_byte": 14495,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event.ts"
} |
angular/packages/core/primitives/event-dispatch/src/event.ts_22477_23336 | /** TagNames and Input types for which to not process enter/space as click. */
const TEXT_CONTROLS: {[key: string]: boolean} = {
'COLOR': true,
'DATE': true,
'DATETIME': true,
'DATETIME-LOCAL': true,
'EMAIL': true,
'MONTH': true,
'NUMBER': true,
'PASSWORD': true,
'RANGE': true,
'SEARCH': true,
'TEL': true,
'TEXT': true,
'TEXTAREA': true,
'TIME': true,
'URL': true,
'WEEK': true,
};
/** TagNames that are native HTML controls. */
const NATIVE_HTML_CONTROLS: {[key: string]: boolean} = {
'A': true,
'AREA': true,
'BUTTON': true,
'DIALOG': true,
'IMG': true,
'INPUT': true,
'LINK': true,
'MENU': true,
'OPTGROUP': true,
'OPTION': true,
'PROGRESS': true,
'SELECT': true,
'TEXTAREA': true,
};
/** Exported for testing. */
export const testing = {
setIsMac(value: boolean) {
isMac = value;
},
}; | {
"end_byte": 23336,
"start_byte": 22477,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/event.ts"
} |
angular/packages/core/primitives/event-dispatch/src/dispatcher.ts_0_5675 | /**
* @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 {EventInfo, EventInfoWrapper} from './event_info';
import {EventType} from './event_type';
import {Restriction} from './restriction';
import {UnrenamedEventContract} from './eventcontract';
import * as eventLib from './event';
import {ActionResolver} from './action_resolver';
/**
* A replayer is a function that is called when there are queued events,
* either from the `EventContract` or when there are no detected handlers.
*/
export type Replayer = (eventInfoWrappers: EventInfoWrapper[]) => void;
/**
* Receives a DOM event, determines the jsaction associated with the source
* element of the DOM event, and invokes the handler associated with the
* jsaction.
*/
export class Dispatcher {
// The ActionResolver to use to resolve actions.
private actionResolver?: ActionResolver;
/** The replayer function to be called when there are queued events. */
private eventReplayer?: Replayer;
/** Whether the event replay is scheduled. */
private eventReplayScheduled = false;
/** The queue of events. */
private readonly replayEventInfoWrappers: EventInfoWrapper[] = [];
/**
* Options are:
* - `eventReplayer`: When the event contract dispatches replay events
* to the Dispatcher, the Dispatcher collects them and in the next tick
* dispatches them to the `eventReplayer`. Defaults to dispatching to `dispatchDelegate`.
* @param dispatchDelegate A function that should handle dispatching an `EventInfoWrapper` to handlers.
*/
constructor(
private readonly dispatchDelegate: (eventInfoWrapper: EventInfoWrapper) => void,
{
actionResolver,
eventReplayer,
}: {actionResolver?: ActionResolver; eventReplayer?: Replayer} = {},
) {
this.actionResolver = actionResolver;
this.eventReplayer = eventReplayer;
}
/**
* Receives an event or the event queue from the EventContract. The event
* queue is copied and it attempts to replay.
* If event info is passed in it looks for an action handler that can handle
* the given event. If there is no handler registered queues the event and
* checks if a loader is registered for the given namespace. If so, calls it.
*
* Alternatively, if in global dispatch mode, calls all registered global
* handlers for the appropriate event type.
*
* The three functionalities of this call are deliberately not split into
* three methods (and then declared as an abstract interface), because the
* interface is used by EventContract, which lives in a different jsbinary.
* Therefore the interface between the three is defined entirely in terms that
* are invariant under jscompiler processing (Function and Array, as opposed
* to a custom type with method names).
*
* @param eventInfo The info for the event that triggered this call or the
* queue of events from EventContract.
*/
dispatch(eventInfo: EventInfo): void {
const eventInfoWrapper = new EventInfoWrapper(eventInfo);
this.actionResolver?.resolveEventType(eventInfo);
this.actionResolver?.resolveAction(eventInfo);
const action = eventInfoWrapper.getAction();
if (action && shouldPreventDefaultBeforeDispatching(action.element, eventInfoWrapper)) {
eventLib.preventDefault(eventInfoWrapper.getEvent());
}
if (this.eventReplayer && eventInfoWrapper.getIsReplay()) {
this.scheduleEventInfoWrapperReplay(eventInfoWrapper);
return;
}
this.dispatchDelegate(eventInfoWrapper);
}
/**
* Schedules an `EventInfoWrapper` for replay. The replaying will happen in its own
* stack once the current flow cedes control. This is done to mimic
* browser event handling.
*/
private scheduleEventInfoWrapperReplay(eventInfoWrapper: EventInfoWrapper) {
this.replayEventInfoWrappers.push(eventInfoWrapper);
if (this.eventReplayScheduled) {
return;
}
this.eventReplayScheduled = true;
Promise.resolve().then(() => {
this.eventReplayScheduled = false;
this.eventReplayer!(this.replayEventInfoWrappers);
});
}
}
/**
* Creates an `EventReplayer` that calls the `replay` function for every `eventInfoWrapper` in
* the queue.
*/
export function createEventReplayer(replay: (eventInfoWrapper: EventInfoWrapper) => void) {
return (eventInfoWrappers: EventInfoWrapper[]) => {
for (const eventInfoWrapper of eventInfoWrappers) {
replay(eventInfoWrapper);
}
};
}
/**
* Returns true if the default action of this event should be prevented before
* this event is dispatched.
*/
function shouldPreventDefaultBeforeDispatching(
actionElement: Element,
eventInfoWrapper: EventInfoWrapper,
): boolean {
// Prevent browser from following <a> node links if a jsaction is present
// and we are dispatching the action now. Note that the targetElement may be
// a child of an anchor that has a jsaction attached. For that reason, we
// need to check the actionElement rather than the targetElement.
return (
actionElement.tagName === 'A' &&
(eventInfoWrapper.getEventType() === EventType.CLICK ||
eventInfoWrapper.getEventType() === EventType.CLICKMOD)
);
}
/**
* Registers deferred functionality for an EventContract and a Jsaction
* Dispatcher.
*/
export function registerDispatcher(eventContract: UnrenamedEventContract, dispatcher: Dispatcher) {
eventContract.ecrd((eventInfo: EventInfo) => {
dispatcher.dispatch(eventInfo);
}, Restriction.I_AM_THE_JSACTION_FRAMEWORK);
}
| {
"end_byte": 5675,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/primitives/event-dispatch/src/dispatcher.ts"
} |
angular/packages/core/testing/PACKAGE.md_0_63 | Provides infrastructure for testing Angular core functionality. | {
"end_byte": 63,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/core/testing/PACKAGE.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.